fun is our keyword - fsharp

Pages

Tuesday, January 31, 2012

Option types in fsharp is equivalent
to nullable types in csharp, when an expression or a value can’t be evaluated
or is invalid csharp results in null, and here in fsharp it is None.

fsharp snippet

let divide x y = x / y

let divideSafe x = function

| y when y <> 0 -> Some(x/y)

| _ -> None

Its
csharp equivalent is

publicint divide(int x, int y)

{

return x
/ y;

}

publicint?
divideSafe(int x, int y)

{

if (y
== 0) returnnull;

return x
/ y;

}

in both version of the divideSafe implementation if the
divider is a non-zero value the value is evaluated. when it is zero, None is
returned.

Result as seen in fsharp interactive (FSI):

val
divide : int -> int -> int

val
divideSafe : int -> int -> int option

>
divideSafe 3 0;;

val
it : int option = None

>
divide 3 0;;

System.DivideByZeroException:
Attempted to divide by zero.

at <StartupCode$FSI_0004>.$FSI_0004.main@()

Stopped
due to error

>

Accessing value from option type:

As in csharp with nullable types you should always check if
an option type holds a value or not before accessing its value, otherwise
exception is thrown. Options module implements IsSome, IsNone for this check.
If IsNone yields false you can safely access the value as option.Value. the following is another way of accessing the value with
pattern matching.

Saturday, January 28, 2012

The inspiration came to me
when I ended up at Luca Bolognese talk
while searching for something else on Channel9, and now am a (slow) learner of
fsharp. This posts lists some of the resources I came across. I will be
updating this post as soon as any resources become available, feel free to
comment if you have any.