Functions
Named functions
Declared a
letbinding (like a variable)Naming convention: camelCase
No
returnkeyword: the function always returns the last expression in its bodyNo
()around all parameters, no,between parameters()required around parameter with type annotation (1) or deconstruction (2)
let square x = x * x // Function with 1 parameter
let res = square 2 // Returns 4
// (1) Parentheses required for annotations of type
let square' (x: int) : int = x * x
// (2) Brackets required when deconstructing an object
// (here it's a single-case discriminated union π
let hotelId (HotelId value) = valueFunctions of 2 or more parameters
Separate parameters and arguments with spaces:
Inference
The inference of the add function can be confusing: the + works for any numbers and for strings too, but add is limited to int! To get it work, we need to write let inline add ...
β Related to a special kind of generics: statically resolved type parameters (SRTP) π
β οΈοΈ , creates another kind of functions using tuples π
Functions without parameter
Use () (like in C#)
βοΈ unit means "nothing" π
Multi-line function
Indentation required, but no need for {}
Can contain sub-function
Anonymous function
A.k.a. Lambda, arrow function
Syntax:
fun {parameters} -> body(β in Cβ―{parameters} β body)In general,
()required all around, for precedence reason
_.Member shorthand (Fβ― 8)
Naming convention related to functions
It's usual in Fβ― to use short names:
x,y,z: parameters for values of the same typef,g,h: parameters for input functionsxs: list ofx_: discard an element not used (like in Cβ― 7.0)
βοΈ Suited for a short function body or for a generic function:
π When x, y, and z are great variable names by Mark Seemann
Piping
Pipe operator |> : same idea that in UNIX with |
β value |> function send a value to a function
β match left-to-right reading order: "subject verb"
β same order than with OOP: object.method
Pipeline: chain of pipings
Style of coding to emphasize the data flowing from functions to functions β without intermediary variable π
Similar to a built-in fluent API β no need to return the object at the end of each method π
If/then/else expression
In Fβ―, if/then(/else) is an expression, not a statement, so every branch (then and else) should return a value and both returned values should be type-compatible.
π‘ if b then x else y β Cβ― ternary operator b ? x : y
β When then returns "nothing", else is optional:
π‘ We can use elif keyword instead of else if.
Match expression
Equivalent in Cβ― 8 :
Last updated
Was this helpful?