Problem #1

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? 

  1. First off, we created a list; this is pretty easy in F#. We could have used either this terminology or the :: append technique.
  2. 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].
  3. 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 :)

  kick it on DotNetKicks.com


Currently rated 5.0 by 1 people

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

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

Related posts

Comments

February 28. 2008 03:08

Jesus DeLaTorre

I used this solution. I started doing something similiar at my blog

#light
let thisList = [1; 2; 3; 4; 5; 6]
let l = List.length thisList
List.nth thisList (l - 1)
|> printf "Answer: %d"

Jesus DeLaTorre