Tuesday, January 31, 2012

fsharp understanding Options


            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 

        public int divide(int x, int y)
        {
            return x / y;
        }
        public int? divideSafe(int x, int y)
        {
            if (y == 0) return null;
            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.

    let doMath x y =
        let z = divideSafe x y
        match z with
            | None -> printfn "Oups! expression evaluated to nothing!"
            | _ -> printfn "%s %d" "Expression evaluated to :" z.Value

Result as seen in fsharp interactive (FSI):

val doMath : int -> int -> unit

> doMath 3 0;;
Oups! expression eavaluated to nothing!
val it : unit = ()

> doMath 8 2;;
Expression evaluated to : 4
val it : unit = ()


HaPpY Coding!!! J

EDIT :

        DivideByZeroException does not happens in the case of float types, instead it yields one of the special floating point numbers Infinity or -Infinity

No comments:

Post a Comment