OCaml中的对应项

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
2个回答

15
你可以直译它:
type 'a seq = Nil | Cons of 'a * ('a * 'a) seq

这是一个样例用法:

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

我认为他定义树类型的方式比这种方式更加Camly,你不觉得吗? - bruce_ricard
@double_squeeze,我不确定你的意思。它既不更加Camly,也不更少,它只是完全不同的类型。 - Andreas Rossberg
我不确定你对“完全不同”的定义是什么,因为它们之间存在双射。 - bruce_ricard
2
@ double_squeeze,这里没有双射。例如,Cons(“ s”,Nil)无法转换为tree。反过来,更有趣的是,树Node(1,Leaf 2,Node(3,Leaf 4,Leaf 5))没有表示为seq,因为它是不平衡的-强制平衡是seq类型的目的。 - Andreas Rossberg

13

在OCaml中的等价代码如下:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接