yjasrc
yjasrc

Reputation: 513

Any special meaning in OCaml type definition

When I'm looking into the build-in type definition of stack:

(*ocaml-2.04/stdlib/stack.ml*)
type 'a t = { mutable c : 'a list }  (*What does t mean here*)
exception Empty
let create () = { c = [] }
let clear s = s.c <- []
let push x s = s.c <- x :: s.c
let pop s = match s.c with hd::tl -> s.c <- tl; hd | [] -> raise Empty
let length s = List.length s.c
let iter f s = List.iter f s.c

What does the variable "t" in the type mean. I thought it should only be primitive type in the type definition. Thanks for explaining.

Upvotes: 0

Views: 132

Answers (2)

Bikal Lem
Bikal Lem

Reputation: 2423

In ocaml t is the coding convention used to denote the type encapsulated by the defining module. In your code sample, t means the Stack type. Since by default ocaml assumes the name of the file with the module, t is referred to as Stack.t.

To see its usage type the following in the ocaml toplevel(REPL) and see the output.

  # let emtpy_stack = Stack.create();;
    val empty_stack : '_a Stack.t = <abstr>

Here empty_stack is a variable of type Stack.t albeit an empty stack.

Additionally, say if you want to define a function that takes Stack as the argument; Here is one way of defining it with type annotations,

 # let stack_func s:(int) Stack.t = s;;
   val stack_dummy : int Stack.t -> int Stack.t = <fun>

Upvotes: 3

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66818

t is the name of the type being defined. It's a parameterized type that takes one parameter. In the definition, the parameter (the so-called formal parameter) is named 'a.

It probably just looks funny because it's a one-character name :-)

Maybe these examples will help clarify:

 # type intsequence = int list;;
 type intsequence = int list
 # type 'a sequence = 'a list;;
 type 'a sequence = 'a list
 # type 'a t = 'a list;;
 type 'a t = 'a list
 # 

The first type has no parameters. It's just a synonym for int list. The second type has a parameter named 'a in the definition. The third is identical to the second, except that the type is named t rather than sequence.

Upvotes: 1

Related Questions