Yan Cui
I help clients go faster for less using serverless technologies.
This article is brought to you by
Don’t reinvent the patterns. Catalyst gives you consistent APIs for messaging, data, and workflow with key microservice patterns like circuit-breakers and retries for free.
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:
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:
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:
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:
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:
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:
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:
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:
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#:
F# supports if-then-else structure, but the thing the sets if statements in F# apart is that if expressions return a value:
F# has some syntactic sugar to help you combat deeply nested if expression with the elif keyword:
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:
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 ():
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:
Whenever you’re ready, here are 3 ways I can help you:
- Production-Ready Serverless: Join 20+ AWS Heroes & Community Builders and 1000+ other students in levelling up your serverless game. This is your one-stop shop for quickly levelling up your serverless skills.
- I help clients launch product ideas, improve their development processes and upskill their teams. If you’d like to work together, then let’s get in touch.
- Join my community on Discord, ask questions, and join the discussion on all things AWS and Serverless.