F#: Different Syntaxes To Same End

So have 5 books on F# and that I working through.  Ironically, the best place to learn F# is not a book but to work through the tutorials in TryFSharp.  The best book to use after going through TryFSharp is Jon Skeets Real-World Functional Programming

image

I am in the middle of Chapter 2 when Jon uses the following example to show high-order functions:

  1. let numbers = [1..20]
  2. let IsOdd x = x % 2 = 1
  3. let Square x = x * x
  4.  
  5. List.filter IsOdd numbers
  6. List.map Square numbers

 

I thought, how many ways do I know how accomplish the same thing?  In FSharp, I know 3 ways.  Way #1 is what the code sample above does.  Another way is to pipe-forward the function calls:

  1. let numbers = [1..20]
  2. let IsOdd x = x % 2 = 1
  3. let Square x = x * x
  4.  
  5. numbers
  6.     |> List.filter IsOdd
  7.     |> List.map Square

 

And finally, I can can use anonymous functions:

  1. let numbers = [1..20]
  2. numbers
  3.     |>List.filter(fun x -> x % 2 = 1)
  4.     |>List.map(fun x -> x * x)

 

Being that I am coming to F# from C#, I prefer option #2.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: