I'm doing problem 7 of the OCaml exercises. It basically asks given a nested list as defined:
type 'a node = | One of 'a | Many of 'a node list
Write a function function flatten
that flattens it:
assert ( flatten [ One "a"; Many [ One "b"; Many [ One "c"; One "d" ]; One "e" ] ] = [ "a"; "b"; "c"; "d"; "e" ])
The solution provided by the website is as follows:
let flatten list = let rec aux acc = function | [] -> acc | One x :: t -> aux (x :: acc) t | Many l :: t -> aux (aux acc l) t in List.rev (aux [] list);;
I'm wondering why they do x :: acc
and then reverse the list instead of acc @ [x]
which would avoid the need to reverse the list at the end?