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.
Currently rated 5.0 by 1 people
- Currently 5/5 Stars.
- 1
- 2
- 3
- 4
- 5
Tags:
Categories: