Why error is occured when call module functions

Hi :slight_smile:

I’m learning OCaml module syntax currently and confusing why this syntax is not allowed and why OCaml says “unbound value pp”.

Code:

  1 module Tree = struct
  2     type 'a tree =
  3         Br of 'a * 'a tree * 'a tree
  4         | Lf
  5 
  6     let create v =
  7         Br(v,Lf,Lf)
  8 
  9     let link_left dst src =
 10         match src with
 11         | Br(v,_,r) -> Br(v,dst,r)
 12         | _ -> Lf
 13 
 14     let link_right dst src =
 15         match src with
 16         | Br(v,l,_) -> Br(v,l,dst)
 17         | _ -> Lf
 18 
 19     let rec size = function
 20         | Br(v,l,r) -> 1 + max (size l) (size r)
 21         | Lf -> 0
 22 
 23     let rec pp f = function
 24         | Br(v,l,r) -> (f v); (pp f l); (pp f r)
 25         | Lf -> ()
 26 end
 27 
 28 
 29 (* test *)
 30 let _ =
 31     let a = create 1 in
 32     let b = create 2 in
 33     let c = create 3 in
 34     let tree = link_left b a |> link_right c in
 35     let fmt = Printf.printf "%d\n" in
 36     pp fmt tree;;
~                       

What I want to learn the semantics of syntax in the above code is three points:

  1. 31, 32, 33 : let .. = create n How can I call create function? create is inside module Tree but this code works. I don’t know why.

  2. 31, 32, 33 : let .. = create n If I change create function to Tree.create, generates stuff what I don’t understand. the return value is Tree.tree not 'a tree. Why it has happened? questions 1 and 2 make me difficult to understand module syntax.

  3. 36: pp fmt tree;; create, link_left, link_right, and size are no problems when I call them but, the function pp occurred error when I call it.

Thank you.

From your description, you most probably defined a type tree, a function create and another module Tree earlier in your file or REPL session. You may also be using an editor terminal and not evaluating the full buffer. Consequently, you end with left-over values, types and modules from your previous attempts.

Using Test.create,

let _ =
  let a = Test.create 1 in
  let b = Test.create 2 in
  let c = Test.create 3 in
  let tree = Test.link_left b a |> Test.link_right c in
  let fmt = Printf.printf "%d\n" in
  Test.pp fmt tree

or opening the Tree module with

let () =
  let open Tree in
  let a = create 1 in
  let b = create 2 in
  let c = create 3 in
  let tree = link_left b a |> link_right c in
  let fmt = Printf.printf "%d\n" in
  pp fmt tree

should work fine.

1 Like