Flattening a list of lists in OCaml


I am implementing this hoemwork functionality using Ocaml:

  • Not allowed to use List module
  • the function has type 'a list list -> 'a list
  • the function return a list consisting of the lists in x concatenated together (just top level of lists is concatenated, unlike List.flatten)
  • For example : [[1,2,3],[45]] => [1,2,3,4,5] and [[[1,2,3],[4,5]],[[6,7]]] => [[1,2,3],[4,5],[6,7]]

I am not sure where to start, can anyone give me some suggestion? Thank you

Best Solution

I don't see the difference between List.flatten and your function.

To answer to your question: as usual with lists, try to think about the base cases:

  • what do you do when you concatenate an empty list with something ?
  • what do you do when you concatenate a non-empty list (with a head and a tail) with something ?

Wrap everything into a pattern match, cook it for few hours, and that's done :-)