type: note

Functions

Functions in fennel are denoted in two main ways

Fn

(fn function-name [args …]
CODE
)

fn creates a function with an optional name (name is locally scoped if provided, anonymous otherwise) and a list of arguments surrounded by square brackets

Lambda

lambda follows the same structure as fn, but with slightly more overhead to ensure that the function is called with the correct number of arguments.

If you want a lambda function to have optional arguments, prepend the argument with a ?

; takes x & z with optional argument y
; returns x - z if y = nil, or x - z * y if y is present
(λ subtract-and-mult [x ?y z]
(print (- x (* (or ?y 1) z))))

(subtract-and-mult 5) ; -> error, missing argument
(subtract-and-mult 5 nil 3) ; -> 2
(subtract-and-mult 5 2 3) ;  -> -1