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
>
divideSafe 3 0;;
>
divide 3 0;;
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 =
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