Learning F# – Part 3

Disclaimer: I do not claim credit for the code examples and much of the contents here, these are mostly extracts from the book by Chris Smith, Programming F#: A comprehensive guide for writing simple code to solve complex problems. In fact, if you’re thinking of learning F# and like what you read here, you should buy the book yourself, it’s easy to read and the author has gone go great lengths to keep things simple and included a lot of code examples for you to try out yourself.

Functions

You define functions the same way you define values, except everything after the name of the function servers as the function’s parameters. The following defines a function called square that takes an integer, x, and returns its square:

clip_image001

Unlike C#, F# has no return keyword. The last expression to be evaluated in the function determines the return type.

Also, from the FSI output above, it shows the function square has signature int -> int, which reads as “a function taking an integer and returning an integer”.

Type Inference

Take this add function for example:

clip_image002

Looking at this you might be wondering why does the compiler think that the add function only takes integers? The + operator also works on floats too!

The reason is type inference. Unlike C#, F# doesn’t require you to explicitly state the types of all the parameters to a function, it figures it out based on usage. Because the + operator works for many different types such as byte, int, and decimal, the compiler simply defaults to int if there is no additional information.

The following FSI snippet shows what type inference in action if we not only define the add function but also call it passing in floats, then the function’s signature will be inferred to be of type float -> float -> float instead:

clip_image003

However, you can provide a type annotation, or hint, to the F# compiler about what the types are. To do this, simply replace a function parameter with the following form ident -> (ident: type) like this:

clip_image004

This works because the only overload for + that takes a float as its first parameter is float -> float -> float, so the F# compiler infers y to be a float as well.

Type inference can reduce code clutter by having the compiler figure out what types to use, but the occasional type annotation is required and can sometimes improve code readability.

Generic Functions

You can write functions that work for any type of a parameter, such as an identity function below:

clip_image005

Because the type inference system could not determine a fixed type for value x in the ident function, it was generic. If a parameter is generic, then that parameter can be of any type.

The type of a generic parameter can have the name of any valid identifier prefixed with an apostrophe, but typically letters of the alphabet starting with ‘a’ as you can see from the FSI snippet for the ident function above.

Writing generic code is important for maximizing code reuse.

Scope

Every value declared in F# has a specific scope, more formally referred to as a declaration space.

The default scope is module scope, meaning variables can be used anywhere after their declaration. However, values defined within a function are scoped only to that function.

For example:

clip_image006

The scoping of a variable is important because F# supports nested functions – i.e. you can declare new function values within the body of a function. Nested functions have access to any value declared in a higher scope as well as any new values declared within itself. The following examples shows this in action:

clip_image007

In F#, having two values with the same name doesn’t lead to a compiler error; rather it simply leads to shadowing. When this happens, both values exists in memory, except there is no way to access the previously declared value. For example:

clip_image008

This technique of intentionally shadowing values is useful for giving the illusion of updating values without relying on mutation. Think strings in C#, which is an immutable type that allows reassignment using the same shadowing technique.

Control Flow

You can branch control flow using the if keyword which works exactly like an if statement in C#:

clip_image001[6]

F# supports if-then-else structure, but the thing the sets if statements in F# apart is that if expressions return a value:

clip_image002[7]

F# has some syntactic sugar to help you combat deeply nested if expression with the elif keyword:

clip_image003[6]

Because the result of the if expression is a value, every clause of an if expression must return the same type.

But if you only have a single if and no corresponding else, then the clause must return unit, which is a special type in F# that means essentially “no value”.

Core Types

Besides the primitive types, the F# library includes several core types that will allow you to organize, manipulate and process data:

image

Unit

The unit type is a value signifying nothing of consequence. unit can be thought of as a concrete representation of void and is represented in code via ():

clip_image001[8]

if expressions without a matching else must return unit because if they did return a value, what would happen if else was hit?

Also, in F#, every function must return a value, think method in C# and the void return type, so even if the function doesn’t conceptually return anything then it should return a unit value.

The ignore function can swallow a function’s return value if you want to return unit:

clip_image002[9]

Leave a Comment

Your email address will not be published. Required fields are marked *