Problem #7

March 12, 2008 – 10:46 am

Flatten a nested list structure.

This solution builds off the last one in that you need to to recursively match the your result so far and tail recursively add the the rest of the result.


let rec flatten_list slist =
   match slist with
   | [] -> []
   | y::ys -> y @ flatten_list ys

There was not much to it. As you can see with the test case.


[["a";"b"];["c"];["e"]] |> flatten_list |> List.iter (printf "[%s]") ;

flatten_list’s type definition is (’a list list -> ‘a list) So that means it takes in ‘a list list and returns ‘a list.

In the test case [”a”;”b”];[”c”];[”e”] is in fact a list of ‘a lists. [”e”] is still a list, just a list of a single element. Since the type definition is (’a list list -> ‘a list), we can use a different type for ‘a

Such as

[["a";"b"];["c"];["e"]] |> flatten_list |> List.iter (printf "[%d]") ;

*Note* that we didn’t to change printf just for printing purposes.

  1. One Response to “Problem #7”

  2. chhtinbzi1htxhnk

    By Tabatha Hurley on Nov 12, 2008

Post a Comment