Reputation: 5
I am trying to build a function in Ocaml which parses a list of lists, eg from [[0;1];[3;4;8]] to [0;1;3;4;8]. I tried to do something like:
#let rec parse listoflists=
match listoflists with
[[]]->[]
|[h::t]->h::parse [t];;
but it doesn't work... I also need an explanation, because I don't understand how the lists of lists actually work...
I don't have to use the Ocaml library functions.
Upvotes: 0
Views: 506
Reputation: 66808
If you can understand a list, then I claim you already know about lists of lists. This is the beauty of recursion.
The only real difficulty (as I see it) is keeping track of which list you're talking about. Your code needs to work with the list of lists itself, which consists of one list (call it h
) followed by some other lists. It also needs to work with the list h, which consists of some element (call it hh
) followed by some other elements.
It seems to me there are three interesting cases: (a) the list of lists is empty; (b) the first element of the list of lists h
is empty (c) neither the list of lists nor h
is empty.
You are not handling all three of these cases. That's one way to see that your code probably wouldn't work.
Here is a match
that matches the three cases, which might help a little:
match listoflists with
| [] -> ... (* List of lists is empty *)
| [] :: t -> ... (* First list h is empty *)
| (hh :: ht) :: t -> ... (* Neither is empty *)
Upvotes: 1