我正在为一堂课学习OCaml,并被赋予了计算二叉树镜像的任务。我很卡住,甚至不知道如何开始...
type btree = Empty | Node of int * btree * btree
;;
let mirror : btree -> btree
= fun t -> (* Code *)
示例输入:
let tree1 = Node(1, Node(2, Node(3, Empty, Empty), Empty), Node(4, Empty, Empty))
;;
示例输出:
mirror tree1 = Node(1, Node(4, Empty, Empty), Node(2, Empty, Node(3, Empty, Empty)))
;;
使用match
功能。
您可以match
由其类型定义的值结构。在您的示例中,btree
类型的值是使用 Empty
构造函数或元组构造函数 Node of int * btree * btree
创建的。你最终应该得到这样的东西:
...
match t with
| Node (num, lt, rt) -> (* do something to switch the subtrees, and mirror the subtrees themselves *)
| Empty -> (* do nothing *)
...
并且由于 mirror
函数的类型为 btree -> btree
,因此每个匹配事例都必须返回 btree
类型的有效值。
请参阅:http://ocaml.org/learn/tutorials/data_types_and_matching.html#Pattern-matching-on-datatypes