F Sharp Options - F Sharp (programming language)

What is F# - Options?

The option type in F# is used for calculations when there may or may not exist a value for a variable or function. Option types are used for representing optional values in calculations. They can have two possible values − Some(x) or None.

  • A function which is used to perform a division will be returning a value in normal situation, but throws exceptions in case of a zero denominator. Using options here will aid the user to indicate whether the function has been failed or succeeded.
  • An option can have a underlying type which can hold any value of that particular type, or there can be no value.

Using Options

Let us now take the example of division function. Look at the below program −

Write a function div, and let us send two arguments to it 20 and 5 −

On compiling and and executing the program, it produces the below result.

If the second argument is zero, the program will throw an exception −

On compiling and and executing the program, it produces the below result.

In earlier cases, we use option types in order to return certain (value) when the operation is successful. Or we return None if the operation gets failed.

Example

On compiling and and executing the program, it produces the below result.

Option Properties and Methods

The option type supports the belowproperties and methods −

The below example demonstrates the use of options −

Property or method

Type

Description

None

'T option

A static property that enables you to create an option value that has the None value.

IsNone

bool

Returns true if the option has the None value.

IsSome

bool

Returns true if the option has a value that is not None.

Some

'T option

A static member that creates an option that has a value that is not None.

Value

'T

Returns the underlying value, or throws a NullReferenceException if the value is None.

Example 1

On compiling and and executing the program, it produces the below result.

Example 2

On compiling and and executing the program, it produces the below result-

Example 3

On compiling and and executing the program, it produces the below result-

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

F Sharp (programming language) Topics