Click here to Skip to main content
13,458,194 members
Click here to Skip to main content
Add your own
alternative version

Tagged as


1 bookmarked
Posted 31 Jan 2012

F# example usage of option types

, 4 Feb 2012
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

Technical Lead
India India
I code, learn, listen, and some day in a near future be a proud farmer.

You may also be interested in...


Comments and Discussions

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