Quantcast
Channel: Active questions tagged ocaml - Stack Overflow
Viewing all articles
Browse latest Browse all 531

Flattening a Nested List in OCaml

$
0
0

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?


Viewing all articles
Browse latest Browse all 531

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>