Converting a tree

I am trying to convert my tree to a list using recursion:

 let rec bt_to_list mytree = match mytree with
  |Empty -> []
  |Node(lt,x,rt) -> [x]:: (bt_to_list lt) :: (bt_to_list rt)

I have an error:

Error: This expression has type 'a list list
but an expression was expected of type 'a list
The type variable 'a occurs inside 'a list

Why is that? My logic seems right to me.
Thank you!

In your code, [x], bt_to_list lt, and bt_to_list rt all have type 'a list. However, you are using :: to append 'a list with another 'a list.

The fix is using list concatenation operator @: (x :: (bt_to_list lt)) @ (bt_to_list rt)

1 Like