Functions

Named functions

  • Declared a let binding (like a variable)

  • Naming convention: camelCase

  • No return keyword: the function always returns the last expression in its body

  • No () 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) = value

Functions of 2 or more parameters

Separate parameters and arguments with spaces:

Inference

⚠️️ , 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)

It's usual in Fβ™― to use short names:

  • x, y, z : parameters for values of the same type

  • f, g, h : parameters for input functions

  • xs : list of x

  • _ : 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?