3
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
4

2 回答 2

15

你可以直译过来:

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

这是一个示例用法:

let s = Cons(1, Cons((1,2), Nil))   (* s : int seq *)
于 2013-08-04T16:15:53.450 回答
13

OCaml 中的等价物如下:

type 'a seq = Nil | Cons of 'a * ('a * 'a) seq
于 2013-08-04T16:13:44.173 回答