Various return types through choices in F#

F# has a type called Choice which makes it possible for a function to return values of different types. A function can return either a boolean, or a string or an integer wrapped in a Choice object. So in fact the function still returns a single return type, i.e. a Choice, but the type contained within a Choices can vary.

Choices are represented by specialised ChoiceOf objects such as Choice1Of2 or Choice2Of7. If a function has, say, 3 possible return types then it must be able return 3 objects: Choice1Of3, Choice2Of3 and Choice3Of3. Let’s see an example:

let myFirstChoiceFuntion (i:int) = 
    if i = 0 then 
        Choice1Of3 true
    else if i < 10 then
        Choice2Of3 "This is less than 10"
    else
        Choice3Of3 (i * 2)

This is a function that accepts an integer and can return 3 different choice types depending on the integer parameter value: true if 0, a string if less than 10 and the double of the input parameter, i.e. an integer otherwise.

We can extract the value from the choice in a pattern matching function:

let choice0 = myFirstChoiceFuntion 0 
let choice5 = myFirstChoiceFuntion 5
let choice100 = myFirstChoiceFuntion 100

let choicePatternMatch ch = 
    match ch with
    | Choice1Of3 t -> printfn "This is a boolean choice: %b" t
    | Choice2Of3 t -> printfn "This is a string choice: %s" t
    | Choice3Of3 t -> printfn "This is an integer choice: %i" t

choicePatternMatch choice0
choicePatternMatch choice5
choicePatternMatch choice100

Here we simply print a string in each case and the value from the choice after calling the function with 0, 5 and 100. Here’s the output:

This is a boolean choice: true
This is a string choice: This is less than 10
This is an integer choice: 200

Choices can be useful if a function should be able to return a primary value, such as the result of a calculation OR a string that holds an exception message in case there was something wrong during the calculation process. Pattern matching can then help define whether the calculation went well.

View all F# related articles here.

Advertisement

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: