F#: Different Syntaxes To Same End
June 18, 2013 Leave a comment
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
I am in the middle of Chapter 2 when Jon uses the following example to show high-order functions:
- let numbers = [1..20]
- let IsOdd x = x % 2 = 1
- let Square x = x * x
- List.filter IsOdd numbers
- 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:
- let numbers = [1..20]
- let IsOdd x = x % 2 = 1
- let Square x = x * x
- numbers
- |> List.filter IsOdd
- |> List.map Square
And finally, I can can use anonymous functions:
- let numbers = [1..20]
- numbers
- |>List.filter(fun x -> x % 2 = 1)
- |>List.map(fun x -> x * x)
Being that I am coming to F# from C#, I prefer option #2.