Xah Lee, 2009-03
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›)”.*) (* examples: *) let x = 5;; (x:int) + (3:int);; (* ⇒ 8 *)
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 call “type constructor”. A type constructor's first letter must be Capitalized.
(* example of defining types. *) type t1 = X;; type t2 = Alice;; (* above defines “t1” to be the name of a type that's just the symbol “X”. and “t2” is the name of the type of 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;;
Here are some examples:
blog comments powered by Disqus