Closure Syntax

Closures are created with vertical bars: |..| ...

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Speaker Notes

This slide should take about 3 minutes.
  • The arguments go between the |..|. The body can be surrounded by { .. }, but if it is a single expression these can be omitted.

  • Argument types are optional, and are inferred if not given. The return type is also optional, but can only be written if using { .. } around the body.

  • The examples can both be written as mere nested functions instead – they do not capture any variables from their lexical environment. We will see captures next.

More to Explore

  • The ability to store functions in variables doesn’t just apply to closures, regular functions can be put in variables and then invoked the same way that closures can: Example in the playground.

    • The linked example also demonstrates that closures that don’t capture anything can also coerce to a regular function pointer.