在OCaml中打印二叉树

Rez*_*our 1 binary-tree ocaml 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
Run Code Online (Sandbox Code Playgroud)

这是我收到的错误:

$ 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
Run Code Online (Sandbox Code Playgroud)

hca*_*rty 6

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

let rec print_tree_infix tree = function
Run Code Online (Sandbox Code Playgroud)

function隐式模式对一个值相匹配.所以你已经定义了一个函数,它接受两个参数而不是一个参数,第一个参数tree在里面未被使用print_tree_infix.如果您将该行更改为

let rec print_tree_infix = function
Run Code Online (Sandbox Code Playgroud)

你的函数将以一个bintree值作为参数.

其次,OCaml中的空白并不重要.当你写作

let mytree = Node(Node(Leaf 6, 3, Leaf 9), 8, Node(Leaf 7, 9, Leaf 2))
print_tree_infix mytree
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

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

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