Reza Hajianpour
Reza Hajianpour

Reputation: 851

Print a binary tree in OCaml

I'm a newbie in OCaml and languages of ML family. I have this binary tree and I want to print each leaf. Here's my code, but apparently it doesn't work. Will you please tell me what's wrong with it? Thanks.

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

This is the error I received:

$ 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

Upvotes: 1

Views: 2915

Answers (1)

hcarty
hcarty

Reputation: 1671

There are a few tweaks to make to your code. First, in your function definition:

let rec print_tree_infix tree = function

the function implicitly pattern matches against one value. So you've defined a function which takes two arguments rather than one, with the first argument tree going unused inside of print_tree_infix. If you change that line to

let rec print_tree_infix = function

your function will take one bintree value as its argument.

Second, whitespace is not significant in OCaml. When you write

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

OCaml parses that as if print_tree_infix mytree is part of the same expression you're assigning to mytree. You can fix that parsing issue by adding an extra let like this

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

which lets OCaml know that these are two independent definitions.

With those changes your code should work as expected!

Upvotes: 6

Related Questions