Problem #7

Sorry for the delay, but here is problem #7!

"Flatten a nested list structure." (recursively)

 So we're just making a list full of lists into just one list with recursion.

    1 #light

    2 

    3 let someList = [[1;2;3];[4;5];[6;7];[8]]

    4 let rec listFixer listy =

    5             if List.nonempty listy then

    6                 let top = listy |> List.hd

    7                 let tail = listy |> List.tl

    8                 top @ (listFixer tail)

    9             else

   10                 []

This function just takes the tip of the list, sets it as the head of the list (top in the function) and passes the tail through the function again to sort it out. When the function finally reaches the end of the list, the function does nothing. Easy!

Something new to note here is the @ operator. This operator appends the head of the list to the rest of the list. 

This solution was very much inspired by Robert Pickering's book Foundations of F#, which had a very similar example problem when covering lists. Be sure to check it out if you haven't already.

kick it on DotNetKicks.com


Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Tags:
Categories:

1 Comments
Actions: E-mail | Permalink | Comment RSSRSS comment feed

Related posts

Comments

March 12. 2008 09:07

Jesus DeLaTorre

I was working on the problem last night and your solution is *not* wrong. It is perfectly fine.

Here is my solution

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

Jesus DeLaTorre

Add comment


(Will show your Gravatar icon)  

  Country flag

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]



Live preview

July 25. 2008 20:31