JJY
JJY

Reputation: 11

Let OCaml function work with lists and ints

How can I make this function can fit with List and Int?

type 'a tree = 
  | Leaf
  | Node of 'a tree * 'a * 'a tree;;

let rec fold_inorder f acc t =
  match t with
  | Leaf           -> acc
  | Node (l, x, r) -> 
      let ar = fold_inorder f acc r in
      let an = x :: ar in
      fold_inorder f an l;;

I am trying to

fold_inorder (fun acc x -> acc + x) 0 (Node (Node (Leaf,1,Leaf), 2, Node (Leaf,3,Leaf)));;

But give me error:

Error: This expression has type int but an expression was expected of type
         'a list

Upvotes: 0

Views: 66

Answers (1)

Silvio Mayolo
Silvio Mayolo

Reputation: 70367

You've restricted your accumulator type to being a list. In your recursion, you write

let an = x :: ar in
fold_inorder f an l;;

an is clearly a list (it was constructed using the :: list constructor), and it's being passed as the second argument to fold_inorder. Hence, fold_inorder can only accept lists as the second argument. On the other hand, when you call fold_inorder at the bottom, you pass 0 as the second argument, which is an integer and not a list, hence the error.

Rather than using :: to build an (the middle accumulator), you should use your supplied f function, which was given in order to combine values.

let an = f ar x in

Upvotes: 2

Related Questions