fn constructs an anonymous first-class function (lambda).
Syntax
(fn (⟨arg⟩* [&key (⟨kw-var⟩ ⟨default-expr⟩)*])
⟨body-element⟩*
⟨expr⟩)
;; ⟨arg⟩ := ⟨var⟩ | _ | ⟨pattern⟩
Coalton also provides reader shorthand for compact lambdas: ƒ.
Semantics
(fn (...) ...)evaluates to a function value of type(⟨inputs⟩ -> ⟨outputs⟩).- Positional parameters
⟨arg⟩*may be variables,_, or patterns (such as(Tuple a b)). All bound variable names within the positional parameters must be distinct, and all keyword parameter names must be distinct. (fn () ...)with zero parameters has type(Void -> ⟨return-type⟩)(or(&key ... -> ⟨return-type⟩)when keyword parameters are present).- Optional keyword parameters follow
&key; each(⟨kw-var⟩ ⟨default-expr⟩)requires a default expression evaluated sequentially left-to-right when omitted by the caller. - The body is an implicit
progn(supporting multiple expressions and shorthandletbindings) and returns the value(s) of the final⟨expr⟩(which may be a single value,Void, or multiple values viavalues). - Each
fnintroduces its own lexicalreturnscope:(return ...)inside the body exits thefnrather than an outerdefine. breakandcontinueinside anfncannot target afororfor*loop outside thatfn.
Examples
;; Map an anonymous function over a list
(coalton
(map (fn (x) (+ (* x x) 1))
(the (List Integer) [1 2 3 4])))
; => (2 5 10 17)
;; Destructuring a Tuple parameter and using a keyword argument
(coalton
(progn
(let scale = (fn ((Tuple x y) &key (factor 2))
(Tuple (* x factor) (* y factor))))
(Tuple (scale (Tuple 3 4))
(scale (Tuple 3 4) :factor 10))))
; => #.(TUPLE #.(TUPLE 6 8) #.(TUPLE 30 40))
Other notes
- When a
fnis bound to a local variable inletorlet*(or via shorthandlet) and does not escape its lexical scope (i.e., it is only called directly and never returned, stored in a data structure, or captured by an escaping closure), the compiler emits a Common Lispflet/labelsbinding declareddynamic-extentso the host Lisp compiler can stack-allocate the closure. See Performance and Optimization. - Macro authors who generate internal
fnwrappers and wantreturninside the macro’s user body to exit the outer enclosing function can write(fn :transparent-to-return (⟨arg⟩*) ⟨body⟩+).