Alright, on to the code. The first of the 99 problems goes as follows:
"Find the last element of a list."
Sounds easy enough -- we'll start by creating a list, reversing it and printing the first element of the reversed list. Make sure your Tabs for F# are set to 5 spaces instead of a tab since F# looks at whitespace as part of determining what is what (tools->options->text editor->F#->Tabs).
1 #light
2
3 let myList =
4 [1; 2; 3; 4]
5 |> List.rev
6 |> List.hd
7 |> printf "Answer: %d"
Which gives us the result "Answer: 4" -- What did we do here to get this result?
- First off, we created a list; this is pretty easy in F#. We could have used either this terminology or the :: append technique.
- To understand the next part of this statement, we first need to realize what exactly the |> (pipeline) operator is doing. To quote fsharp.it, "This operator allows [us] to chain functions, passing the output of one of them to the next one." Great, so in effect what the List.rev statement is doing is reversing the list [1; 2; 3; 4].
- Now we're going to grab the head element of the first list and print the result.
Please lemme know what you think -- and if you have a better solution, by all means... Trying to get my object oriented brain wrapped around this functional programming :)
Currently rated 5.0 by 1 people
- Currently 5/5 Stars.
- 1
- 2
- 3
- 4
- 5
Tags:
99 problems,
f#,
pipeline
Categories: