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.
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”.
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.
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.
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.
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.
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”.
Besides the primitive types, the F# library includes several core types that will allow you to organize, manipulate and process data:
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:
Enjoy what you’re reading? Subscribe to my newsletter and get more content on AWS and serverless technologies delivered straight to your inbox.
I’m an AWS Serverless Hero and the author of Production-Ready Serverless. I have run production workload at scale in AWS for nearly 10 years and I have been an architect or principal engineer with a variety of industries ranging from banking, e-commerce, sports streaming to mobile gaming. I currently work as an independent consultant focused on AWS and serverless.
In this course, we’ll cover everything you need to know to use AWS Step Functions service effectively. Including basic concepts, HTTP and event triggers, activities, design patterns and best practices.
Here is a complete list of all my posts on serverless and AWS Lambda. In the meantime, here are a few of my most popular blog posts.
- Lambda optimization tip – enable HTTP keep-alive
- You are thinking about serverless costs all wrong
- Many faced threats to Serverless security
- We can do better than percentile latencies
- I’m afraid you’re thinking about AWS Lambda cold starts all wrong
- Yubl’s road to Serverless
- AWS Lambda – should you have few monolithic functions or many single-purposed functions?
- AWS Lambda – compare coldstart time with different languages, memory and code sizes
- Guys, we’re doing pagination wrong