在 OCaml 中打印二叉树

Print a binary tree in OCaml

我是 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

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

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 知道这是两个独立的定义。

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