Click here to Skip to main content
Click here to Skip to main content

Tagged as

F# example usage of option types

, 4 Feb 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
F# example usage of option types
Option types in F# is equivalent to nullable types in C#, when an expression or a value can’t be evaluated or is invalid C# results in null, and here in F# it is None.
let divide x y = x / y
let divideSafe x = function
    | y when y <> 0 -> Some(x/y)
    | _ -> None
divideSafe implementation if the divider is a non-zero value the value is evaluated. When it is zero, None is returned.
Accessing value from option type:
As in C# with nullable types, you should always check if an option type holds a value or not before accessing its value, otherwise an 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
Check blog post[^] for comparison with C# version.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Software Developer
India India
I code, learn, listen, and some day in a near future be a proud farmer.
Follow on   Twitter

Comments and Discussions

-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.150123.1 | Last Updated 4 Feb 2012
Article Copyright 2012 by VallarasuS
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid