2013-06-23 73 views
0

任何特殊的意义。当我寻找到堆栈的内部类型定义:OCaml中类型定义

(*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 

什么的类型变量“t”的意思。我认为它只能是类型定义中的原始类型。感谢您的解释。

回答

3

在ocaml中t是用于表示由定义模块封装的类型的编码约定。在您的代码示例中,t表示堆栈类型。由于默认情况下,ocaml假定文件的名称与模块,t被称为Stack.t。

要在ocaml toplevel(REPL)中查看它的用法类型,请参阅输出。

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

这里empty_stackStack.t类型的虽然是空堆栈的变量。

另外,假如你想定义一个以Stack为参数的函数,这里有一种用类型注释来定义它的方法,

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

t是被定义的类型的名称。这是一个参数化类型,需要一个参数。在定义中,参数(所谓的形式参数)被命名为'a

它可能只是看起来很有趣,因为它是一个字符的名称:-)

也许这些例子将有助于澄清:

# 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 
# 

第一类没有参数。这只是int list的同义词。第二种类型在定义中有一个名为'a'的参数。第三个与第二个相同,不同之处在于该类型被命名为t而不是sequence

+0

恩......我明白了。感谢分享知识。 – yjasrc