Options in F#

There are functions whose purpose is to locate an object in a collection or database. They either find the resource or they don’t. In case they find it then they return it from the function body. What if the resource is not found? E.g. we might be looking for the first number above 100 in an integer list. Then it is either found or not, we don’t know in advance. Mainstream OOP languages like C# or Java would return null or the maybe the default value of the type that’s being searched.

In F# we have the Option object to solve this problem. F# understands the “null” keyword as well but it’s mainly used when interacting with other .NET languages. Otherwise F# has no real notion of null as in an object that’s not pointing to an address in memory. F#’s approximation of a missing value is an Option that has no enclosed object. It’s called None. None is an object that indicates missing data which is not the same as null. Its opposite is called Some which has an enclosed object of some type. Both Some and None create an instance of type Option but None contains nothing.

Here’s how we can instantiate a None and a Some:

let none = None
let some = Some "Hello world"

Some accepts an argument which will be the enclosed object, a string in our example.

The recommended way to extract a value from a Some is through pattern matching as Some and None make up a discriminated union:

match some with
    | Some message -> printfn "Today's message is %s" message
    | None -> printfn "No message"

That will take the “Some” path of course and print the following in the interactive window:

Today’s message is Hello world

Conversely…

match none with
    | Some message -> printfn "Today's message is %s" message
    | None -> printfn "No message"

…prints “No message”.

Let’s see another example where we try to find the first string of a certain length in a string list:

let longString (l:List<string>, minLength:int) =
    List.tryPick (fun (s:string) -> if s.Length > minLength then Some s else None) l

let longStringRes = longString (["hello"; "world"; "goodbye"],3)

match longStringRes with
    | Some word -> printfn "First word found: %s" word
    | None -> printfn "No word"

longString accepts a list of strings and a minimum length to search for. We supply a lambda expression to the List.tryPick function. The lambda declares that if an element in the list matches the criteria then we return it otherwise we return a None.

Then comes an example with 3 strings and a minimum length of 3. The pattern matching function will find “hello”. If we change 3 to 30 then a None is returned.

View all F# related articles here.

Advertisements

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

One Response to Options in F#

  1. Pingback: F# Weekly #25, 2017 – Paket 5 and new Rider EAP – Sergey Tihon's Blog

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 )

Google+ photo

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

Connecting to %s

ultimatemindsettoday

A great WordPress.com site

Elliot Balynn's Blog

A directory of wonderful thoughts

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

HarsH ReaLiTy

A Good Blog is Hard to Find

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

the software architecture

thoughts, ideas, diagrams,enterprise code, design pattern , solution designs

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

Anything around ASP.NET MVC,WEB API, WCF, Entity Framework & AngularJS

Cyber Matters

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

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: