Allan Jiang
Allan Jiang

Reputation: 11331

Flattening a list of lists in OCaml

I am implementing this hoemwork functionality using Ocaml:

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

Upvotes: 0

Views: 8316

Answers (2)

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66808

Thomas has given excellent advice. Your basic operation is going to be to append one list to another. It might help to write this function as a separate function first. It will look something like this:

let rec myappend a b =
    match a with
    | [] -> (* Empty list prefixed to b (easy case) *)
    | ahead :: atail -> (* Recursive case *)

Armed with your own append function, you can carry out another level of recursion to append all the top-level lists as Thomas suggests.

Upvotes: 2

Thomas
Thomas

Reputation: 5048

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 :-)

Upvotes: 6

Related Questions