Reputation: 3684
I have a tree type defined as
type 'a tree = Nil | Node of ('a tree * 'a * 'a tree)
I need to build a list of elements in this tree. I tried (without tail-recursion):
let elements t =
let rec walk node =
match node with
| Nil -> []
| Node(lChild, x, rChild) ->
(walk lChild) :: [x] :: (walk rChild)
in
walk set
But I get a type error: expression (walk lChild)
has type 'a list
but an expression was expected of type 'a
So I guess my question can be reduced to "how to add a list of elements to a list".
Thanks!
Upvotes: 0
Views: 84
Reputation: 139
ivg's answer is correct. To be a bit clearer :
let xs = [2;3;4]
1 :: xs
returns [1;2;3;4]
, xs
's type is int list
, 1
is an int
. So if you use an 'a list
, the ::
operator needs to have an 'a
typed element to its left.
To concatenate lists, try
[1] @ [2;3;4]
Upvotes: 1
Reputation: 35210
You need @
operator, that concatenates two lists.
::
is a consing operator and it can only prepend an element to the list, i.e., the left hand side of it should be an element, and the right should be the list.
Upvotes: 5