# Types in Ocaml

## Defining Types

### Explicit Declaration of Type

You can explicit say what's your function input's type. Usually you don't need to, because ocaml can correctly infer it.

(* A function f, with input n, of type int *) let f (n:int) = n + 1;;

You can explicitly put type info on any variable in a expression,
using this syntax

.`var_name`:`type_literal`

let x = 5;; (x:int) + (3:int);; (* ⇒ 8 *)

### Defining Your Own Type

Remember, Ocaml has these built-in simple types: int, float, bool, char, string, unit.

You can define your own type, by assigning a type expression to a name. The syntax is this:
`type `

.
`name` = `type_expression`

The simplest type is just a arbitrary letter sequence, which is called “type constructor”. A type constructor's first letter must be Capitalized.

(* example of defining types. *) type t1 = X;; type t2 = Alice;; (* above defines a type named “t1”, and values of this type is just the symbol “X”. And “t2” another type. The items belonging to this type is just the symbol “Alice”. *) X;; (* evaluate X *)

Type expression can use the operator `|`

, which means “alternative”, “one of”, or “or”.

type myGirls = Many | Jane | Alice ;; type mySign = Positive | Negative | Zero;; type testResult = PassTest | FailTest | Undecided;;

Ask me question on patreon