在OCaml中打印二叉树

时间:2016-08-24 15:58:54

标签: ocaml binary-tree binary-search-tree

我是OCaml的新手和ML家族的语言。我有这个二叉树,我想打印每个叶子。这是我的代码,但显然它不起作用。你能告诉我它有什么问题吗?感谢。

open Core.Std
open Printf

type bintree = Leaf of int
             | Node of bintree * int * bintree

let rec print_tree_infix tree = function
    Leaf n ->
    Printf.printf "%d" n
  | Node (left, n, right) ->
    Printf.printf "%d" n;
    print_tree_infix left;
    print_tree_infix right

let mytree = Node(Node(Leaf 6, 3, Leaf 9), 8, Node(Leaf 7, 9, Leaf 2))
print_tree_infix mytree

这是我收到的错误:

$ ocaml setup.ml -build 
Finished, 0 targets (0 cached) in 00:00:00.
+ ~/.opam/system/bin/ocamlfind ocamldep -package core -package threads -modules src/main.ml > src/main.ml.depends
File "src/main.ml", line 16, characters 0-16:
Error: Syntax error
Command exited with code 2.
Compilation unsuccessful after building 1 target (0 cached) in 00:00:00.
E: Failure("Command ''/usr/bin/ocamlbuild' src/main.byte -tag debug' terminated with error code 10")
make: *** [Makefile:7: build] Error 1

1 个答案:

答案 0 :(得分:6)

对您的代码进行一些调整。首先,在您的函数定义中:

let rec print_tree_infix tree = function

function隐式模式与一个值匹配。因此,您已经定义了一个函数,它接受两个参数而不是一个参数,第一个参数treeprint_tree_infix内部未被使用。如果您将该行更改为

let rec print_tree_infix = function

您的函数将以bintree值作为参数。

其次,OCaml中的空格并不重要。当你写

let mytree = Node(Node(Leaf 6, 3, Leaf 9), 8, Node(Leaf 7, 9, Leaf 2))
print_tree_infix mytree

OCaml解析,好像print_tree_infix mytree是您分配给mytree的同一个表达式的一部分。您可以通过添加这样的额外let

来解决该解析问题
let mytree = Node(Node(Leaf 6, 3, Leaf 9), 8, Node(Leaf 7, 9, Leaf 2))
let () = print_tree_infix mytree

让OCaml知道这些是两个独立的定义。

通过这些更改,您的代码应该按预期工作!