data Seq a = Nil | Cons a (Seq (a,a))
Run Code Online (Sandbox Code Playgroud)
好吧,所以这是一段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
Run Code Online (Sandbox Code Playgroud)
And*_*erg 15
你可以完全翻译它:
type 'a seq = Nil | Cons of 'a * ('a * 'a) seq
Run Code Online (Sandbox Code Playgroud)
以下是一个示例用法:
let s = Cons(1, Cons((1,2), Nil)) (* s : int seq *)
Run Code Online (Sandbox Code Playgroud)
Jef*_*eld 13
OCaml中的等价物如下:
type 'a seq = Nil | Cons of 'a * ('a * 'a) seq
Run Code Online (Sandbox Code Playgroud)