-->

Adventures in F# - Part 3

dev fsharp

It’s hard to accustomed to F# notation after getting used to OO languages like C#. Today I’ll work on the advanced section of the TryFSharp.org site. As I go forward the concepts are taking longer and becoming harder to grasp!

Notes

  • Currying is an interesting concept. It means you don’t have to provide all of the arguments when calling a function. for example

An addition function can be defined as

let add x y = x + y

and another function using this definition can be defined as

let addFive = add 5

In this case addFive returns another function which is waiting for the rest if the arguments. For example the following code snippet prints 17

let add x y = x + y
let addFive = add 5
printfn "%d" (addFive 12)
  • Operators can be overloaded but it should be used with care as it may make the code obfuscated in some cases
type Point(x:float, y:float) =
  member this.X = x
  member this.Y = y

  static member (+) (p1:Point, p2:Point) = 
      new Point(p1.X + p2.X, p1.Y+p2.Y)

let p1, p2 = new Point(0., 1.), new Point(1.,1.)
p1 + p2
  • Active Patterns allow to wrap arbitrary values in a union-like data structure for easy pattern matching.

For example:

let (|Even|Odd|) n =
    if n % 2 = 0 then
        Even
    else
        Odd

In this case Even and Odd are union constructors, so our active pattern either returns an instance of Even or an instance of Odd.

Conclusion

Today I completed the first 2 sections of Advanced section in TryFSharp.org, only 2 more to go. Even though I’m planning to finish all the material in the site it feels like the advanced topics are not covered in depth. The examples provided are too complex for an absolute beginner. I found the F# Programming Wiki as a better resource for these topics and I’m now going over both these resources.

Resources