反对OCaml

时间:2013-08-04 15:17:33

标签: haskell ocaml

data Seq a = Nil | Cons a (Seq (a,a))

好的,所以这是一段haskell声明二叉树的嵌套数据类型,

在OCaml中还有一个对应部分吗?

如果是,请在OCaml代码中显示。

我试过了,但我想确定这与上述内容是否相同:

type tree = Leaf of int | Node of int * tree * tree;; 

let l = Leaf 3;; 

let a = Node (1, l, l);; 

let a = Node (1, a, l);; 

let a = Node (1, a, l);; 

let a = Node (1, a, l);; 

let a = Node (1, a, l);; 

let rec value tree = match tree with 
| Leaf x -> x 
| Node (v, x, y) -> v + (value x) + (value y);; 

let rec len tree = match tree with 
| Leaf x -> 1 
| Node (v, x, y) -> 1 + (len x) + (len y);; 

value a;; 
len a;; 



# #use 
"1.ml";; 
type tree = Leaf of int | Node of int * tree * tree 
val l : tree = Leaf 3 
val a : tree = Node (1, Leaf 3, Leaf 3) 
val a : tree = Node (1, Node (1, Leaf 3, Leaf 3), Leaf 3) 
val a : tree = Node (1, Node (1, Node (1, Leaf 3, Leaf 3), Leaf 3), Leaf 3) 
val a : tree = 
Node (1, Node (1, Node (1, Node (1, Leaf 3, Leaf 3), Leaf 3), Leaf 3), 
Leaf 3) 
val a : tree = 
Node (1, 
Node (1, Node (1, Node (1, Node (1, Leaf 3, Leaf 3), Leaf 3), Leaf 3), 
Leaf 3), 
Leaf 3) 
val value : tree -> int = <fun> 
val len : tree -> int = <fun> 
- : int = 23 
- : int = 11

2 个答案:

答案 0 :(得分:15)

你可以完全翻译它:

type 'a seq = Nil | Cons of 'a * ('a * 'a) seq

以下是一个示例用法:

let s = Cons(1, Cons((1,2), Nil))   (* s : int seq *)

答案 1 :(得分:13)

OCaml中的等价物如下:

type 'a seq = Nil | Cons of 'a * ('a * 'a) seq