.\" Automatically generated by Pandoc 2.17.1.1 .\" .\" Define V font for inline verbatim, using C font in formats .\" that render this, and otherwise B font. .ie "\f[CB]x\f[]"x" \{\ . ftr V B . ftr VI BI . ftr VB B . ftr VBI BI .\} .el \{\ . ftr V CR . ftr VI CI . ftr VB CB . ftr VBI CBI .\} .TH "fennel-reference" "5" "2024-02-23" "fennel 1.4.2-dev" "Fennel Reference" .hy .SH NAME .PP fennel-reference - Fennel Reference .SH DESCRIPTION .PP This document covers the syntax, built-in macros, and special forms recognized by the Fennel compiler. It does not include built-in Lua functions; see the Lua reference manual (https://www.lua.org/manual/5.1/) or the Lua primer (https://fennel-lang.org/lua-primer) for that. This is not an introductory text; see the tutorial (https://fennel-lang.org/tutorial) for that. If you already have a piece of Lua code you just want to see translated to Fennel, use antifennel (https://fennel-lang.org/see). .PP A macro is a function which runs at compile time and transforms some Fennel code into different Fennel. A special form (or special) is a primitive construct which emits Lua code directly. When you are coding, you don\[aq]t need to care about the difference between built-in macros and special forms; it is an implementation detail. .PP Remember that Fennel relies completely on Lua for its runtime. Everything Fennel does happens at compile-time, so you will need to familiarize yourself with Lua\[aq]s standard library functions. Thankfully it\[aq]s much smaller than almost any other language. .PP The one exception to this compile-time rule is the \f[V]fennel.view\f[R] function which returns a string representation of any Fennel data suitable for printing. But this is not part of the language itself; it is a library function which can be used from Lua just as easily. .PP Fennel source code should be UTF-8-encoded text. .SH SYNTAX .PP \f[V](parentheses)\f[R]: used to delimit lists, which are primarily used to denote calls to functions, macros, and specials, but also can be used in binding contexts to bind to multiple values. Lists are a compile-time construct; they are not used at runtime. For example: \f[V](print \[dq]hello world\[dq])\f[R] .PP \f[V]{curly brackets}\f[R]: used to denote key/value table literals, also known as dictionaries. For example: \f[V]{:a 1 :b 2}\f[R] In a table if you have a string key followed by a symbol of the same name as the string, you can use \f[V]:\f[R] as the key and it will be expanded to a string containing the name of the following symbol. .IP .nf \f[C] {: this} ; is shorthand for {:this this} \f[R] .fi .PP \f[V][square brackets]\f[R]: used to denote sequential tables, which can be used for literal data structures and also in specials and macros to delimit where new identifiers are introduced, such as argument lists or let bindings. For example: \f[V][1 2 3]\f[R] .PP The syntax for numbers is the same as Lua\[aq]s (https://www.lua.org/manual/5.4/manual.html#3.1), except that underscores may be used to separate digits for readability. Non-ASCII digits are not yet supported. .PP The syntax for strings uses double-quotes \f[V]\[dq]\f[R] around the string\[aq]s contents. Double quotes inside a string must be escaped with backslashes. The syntax for these is the same as Lua\[aq]s (https://www.lua.org/manual/5.4/manual.html#3.1), except that strings may contain newline characters. Single-quoted or long bracket strings are not supported. .PP Fennel has a lot fewer restrictions on identifiers than Lua. Identifiers are represented by symbols, but identifiers are not exactly the same as symbols; some symbols are used by macros for things other than identifiers. Symbols may not begin with digits or a colon, but may have digits anywhere else. Beyond that, any unicode characters are accepted as long as they are not unprintable or whitespace, one of the delimiter characters mentioned above, one of the a prefix characters listed below, or one of these reserved characters: .IP \[bu] 2 single quote: \f[V]\[aq]\f[R] .IP \[bu] 2 tilde: \f[V]\[ti]\f[R] .IP \[bu] 2 semicolon: \f[V];\f[R] .IP \[bu] 2 at: \f[V]\[at]\f[R] .PP Underscores are allowed in identifier names, but dashes are preferred as word separators. By convention, identifiers starting with underscores are used to indicate that a local is bound but not meant to be used. .PP The ampersand character \f[V]&\f[R] is allowed in symbols but not in identifiers. This allows it to be reserved for macros, like the behavior of \f[V]&as\f[R] in destructuring. .PP Symbols that contain a dot \f[V].\f[R] or colon \f[V]:\f[R] are considered \[dq]multi symbols\[dq]. The part of the symbol before the first dot or colon is used as an identifier, and the part after the dot or colon is a field looked up on the local identified. A colon is only allowed before the final segment of a multi symbol, so \f[V]x.y:z\f[R] is valid but \f[V]a:b.c\f[R] is not. Colon multi symbols can only be used for method calls. .PP Fennel also supports certain kinds of strings that begin with a colon as long as they don\[aq]t contain any characters which wouldn\[aq]t be allowed in a symbol, for example \f[V]:fennel-lang.org\f[R] is another way of writing the string \[dq]fennel-lang.org\[dq]. .PP Spaces, tabs, newlines, vertical tabs, form feeds, and carriage returns are counted as whitespace. Non-ASCII whitespace characters are not yet supported. .PP Certain prefixes are expanded by the parser into longhand equivalents: .IP \[bu] 2 \f[V]#foo\f[R] expands to \f[V](hashfn foo)\f[R] .IP \[bu] 2 \f[V]\[ga]foo\f[R] expands to \f[V](quote foo)\f[R] .IP \[bu] 2 \f[V],foo\f[R] expands to \f[V](unquote foo)\f[R] .PP A semicolon and everything following it up to the end of the line is a comment. .SH FUNCTIONS .SS \f[V]fn\f[R] function .PP Creates a function which binds the arguments given inside the square brackets. Will accept any number of arguments; ones in excess of the declared ones are ignored, and if not enough arguments are supplied to cover the declared ones, the remaining ones are given values of \f[V]nil\f[R]. .PP Example: .IP .nf \f[C] (fn pxy [x y] (print (+ x y))) \f[R] .fi .PP Giving it a name is optional; if one is provided it will be bound to it as a local. The following mean exactly the same thing; the first is preferred mostly for indentation reasons, but also because it allows recursion: .IP .nf \f[C] (fn pxy [x y] (print (+ x y))) (local pxy (fn [x y] (print (+ x y)))) \f[R] .fi .PP Providing a name that\[aq]s a table field will cause it to be inserted in a table instead of bound as a local: .IP .nf \f[C] (local functions {}) (fn functions.p [x y z] (print (* x (+ y z)))) ;; equivalent to: (set functions.p (fn [x y z] (print (* x (+ y z))))) \f[R] .fi .PP Like Lua, functions in Fennel support tail-call optimization, allowing (among other things) functions to recurse indefinitely without overflowing the stack, provided the call is in a tail position. .PP The final form in this and all other function forms is used as the return value. .SS \f[V]lambda\f[R]/\f[V]\[*l]\f[R] nil-checked function .PP Creates a function like \f[V]fn\f[R] does, but throws an error at runtime if any of the listed arguments are nil, unless its identifier begins with \f[V]?\f[R]. .PP Example: .IP .nf \f[C] (lambda [x ?y z] (print (- x (* (or ?y 1) z)))) \f[R] .fi .PP Note that the Lua runtime will fill in missing arguments with nil when they are not provided by the caller, so an explicit nil argument is no different than omitting an argument. .PP Programmers coming from other languages in which it is an error to call a function with a different number of arguments than it is defined with often get tripped up by the behavior of \f[V]fn\f[R]. This is where \f[V]lambda\f[R] is most useful. .PP The \f[V]lambda\f[R], \f[V]case\f[R], \f[V]case-try\f[R], \f[V]match\f[R] and \f[V]match-try\f[R] forms are the only place where the \f[V]?foo\f[R] notation is used by the compiler to indicate that a nil value is allowed, but it is a useful notation to communicate intent anywhere a new local is introduced. .PP The \f[V]\[*l]\f[R] form is an alias for \f[V]lambda\f[R] and behaves identically. .SS Docstrings and metadata .PP The \f[V]fn\f[R], \f[V]lambda\f[R], \f[V]\[*l]\f[R] and \f[V]macro\f[R] forms accept an optional docstring. .IP .nf \f[C] (fn pxy [x y] \[dq]Print the sum of x and y\[dq] (print (+ x y))) (\[*l] pxyz [x ?y z] \[dq]Print the sum of x, y, and z. If y is not provided, defaults to 0.\[dq] (print (+ x (or ?y 0) z))) \f[R] .fi .PP These are ignored by default outside of the REPL, unless metadata is enabled from the CLI (\f[V]---metadata\f[R]) or compiler options \f[V]{useMetadata=true}\f[R], in which case they are stored in a metadata table along with the arglist, enabling viewing function docs via the \f[V]doc\f[R] macro. .IP .nf \f[C] ;; this only works in the repl >> ,doc pxy (pxy x y) Print the sum of x and y \f[R] .fi .PP All function metadata will be garbage collected along with the function itself. Docstrings and other metadata can also be accessed via functions on the fennel API with \f[V]fennel.doc\f[R] and \f[V]fennel.metadata\f[R]. .PP \f[I](Since 1.1.0)\f[R] .PP All forms that accept a docstring will also accept a metadata table in the same place: .IP .nf \f[C] (fn add [...] {:fnl/docstring \[dq]Add arbitrary amount of numbers.\[dq] :fnl/arglist [a b & more]} (match (values (select :# ...) ...) (0) 0 (1 a) a (2 a b) (+ a b) (_ a b) (add (+ a b) (select 3 ...)))) \f[R] .fi .PP Here the arglist is overridden by that in the metadata table (note that the contents of the table are implicitly quoted). Calling \f[V],doc\f[R] command in the REPL prints specified argument list: .IP .nf \f[C] >> ,doc add (add a b & more) Add arbitrary amount of numbers. \f[R] .fi .PP \f[I](Since 1.3.0)\f[R] .PP Arbitrary metadata keys are allowed in the metadata table syntax: .IP .nf \f[C] (fn foo [] {:deprecated \[dq]v1.9.0\[dq] :fnl/docstring \[dq]*DEPRECATED* use foo2\[dq]} ;; old way to do stuff ) (fn foo2 [x] {:added \[dq]v2.0.0\[dq] :fnl/docstring \[dq]Incompatible but better version of foo!\[dq]} ;; do stuff better, now with x! x) \f[R] .fi .PP In this example, the \f[V]deprecated\f[R] and \f[V]added\f[R] keys are used to store a version of a hypothetical library on which the functions were deprecated or added. External tooling then can leverage this information by using Fennel\[aq]s metadata API: .IP .nf \f[C] >> (local {: metadata} (require :fennel)) >> (metadata:get foo :deprecated) \[dq]v1.9.0\[dq] >> (metadata:get foo2 :added) \[dq]v2.0.0\[dq] \f[R] .fi .PP Such metadata can be any data literal, including tables, with the only restriction that there are no side effects. Fennel\[aq]s lists are disallowed as metadata values. .PP \f[I](Since 1.3.1)\f[R] .PP For editing convenience, the metadata table literals are allowed after docstrings: .IP .nf \f[C] (fn some-function [x ...] \[dq]Docstring for some-function.\[dq] {:fnl/arglist [x & xs] :other :metadata} (let [xs [...]] ;; ... )) \f[R] .fi .PP In this case, the documentation string is automatically inserted to the metadata table by the compiler. .PP The whole metadata table can be obtained by calling \f[V]metadata:get\f[R] without the \f[V]key\f[R] argument: .IP .nf \f[C] >> (local {: metadata} (require :fennel)) >> (metadata:get some-function) {:fnl/arglist [\[dq]x\[dq] \[dq]&\[dq] \[dq]xs\[dq]] :fnl/docstring \[dq]Docstring for some-function.\[dq] :other \[dq]metadata\[dq]} \f[R] .fi .PP Fennel itself only uses the \f[V]fnl/docstring\f[R] and \f[V]fnl/arglist\f[R] metadata keys but third-party code can make use of arbitrary keys. .SS Hash function literal shorthand .PP It\[aq]s pretty easy to create function literals, but Fennel provides an even shorter form of functions. Hash functions are anonymous functions of one form, with implicitly named arguments. All of the below functions are functionally equivalent: .IP .nf \f[C] (fn [a b] (+ a b)) \f[R] .fi .IP .nf \f[C] (hashfn (+ $1 $2)) ; implementation detail; don\[aq]t use directly \f[R] .fi .IP .nf \f[C] #(+ $1 $2) \f[R] .fi .PP This style of anonymous function is useful as a parameter to higher order functions. It\[aq]s recommended only for simple one-line functions that get passed as arguments to other functions. .PP The current implementation only allows for hash functions to use up to 9 arguments, each named \f[V]$1\f[R] through \f[V]$9\f[R], or those with varargs, delineated by \f[V]$...\f[R] instead of the usual \f[V]...\f[R]. A lone \f[V]$\f[R] in a hash function is treated as an alias for \f[V]$1\f[R]. .PP Hash functions are defined with the \f[V]hashfn\f[R] macro or special character \f[V]#\f[R], which wraps its single argument in a function literal. For example, .IP .nf \f[C] #$3 ; same as (fn [x y z] z) #[$1 $2 $3] ; same as (fn [a b c] [a b c]) #{:a $1 :b $2} ; same as (fn [a b] {:a a :b b}) #$ ; same as (fn [x] x) (aka the identity function) #val ; same as (fn [] val) #[:one :two $...] ; same as (fn [...] [\[dq]one\[dq] \[dq]two\[dq] ...]) \f[R] .fi .PP Hash arguments can also be used as parts of multisyms. For instance, \f[V]#$.foo\f[R] is a function which will return the value of the \[dq]foo\[dq] key in its first argument. .PP Unlike regular functions, there is no implicit \f[V]do\f[R] in a hash function, and thus it cannot contain multiple forms without an explicit \f[V]do\f[R]. The body itself is directly used as the return value rather than the last element in the body. .SS \f[V]partial\f[R] partial application .PP Returns a new function which works like its first argument, but fills the first few arguments in place with the given ones. This is related to currying but different because calling it will call the underlying function instead of waiting till it has the \[dq]correct\[dq] number of args. .PP Example: .IP .nf \f[C] (fn add-print [x y] (print (+ x y))) (partial add-print 2) \f[R] .fi .PP This example returns a function which will print a number that is 2 greater than the argument it is passed. .SH BINDING .SS \f[V]let\f[R] scoped locals .PP Introduces a new scope in which a given set of local bindings are used. .PP Example: .IP .nf \f[C] (let [x 89 y 198] (print (+ x y 12))) ; => 299 \f[R] .fi .PP These locals cannot be changed with \f[V]set\f[R] but they can be shadowed by an inner \f[V]let\f[R] or \f[V]local\f[R]. Outside the body of the \f[V]let\f[R], the bindings it introduces are no longer visible. The last form in the body is used as the return value. .PP Any time you bind a local, you can destructure it if the value is a table or a function call which returns multiple values: .PP Example: .IP .nf \f[C] (let [(x y z) (unpack [10 9 8])] (+ x y z)) ; => 27 \f[R] .fi .PP Example: .IP .nf \f[C] (let [[a b c] [1 2 3]] (+ a b c)) ; => 6 \f[R] .fi .PP If a table key is a string with the same name as the local you want to bind to, you can use shorthand of just \f[V]:\f[R] for the key name followed by the local name. This works for both creating tables and destructuring them. .PP Example: .IP .nf \f[C] (let [{:msg message : val} {:msg \[dq]hello there\[dq] :val 19}] (print message) val) ; prints \[dq]hello there\[dq] and returns 19 \f[R] .fi .PP When destructuring a sequential table, you can capture all the remainder of the table in a local by using \f[V]&\f[R]: .PP Example: .IP .nf \f[C] (let [[a b & c] [1 2 3 4 5 6]] (table.concat c \[dq],\[dq])) ; => \[dq]3,4,5,6\[dq] \f[R] .fi .PP \f[I](Since 1.3.0)\f[R]: This also works with function argument lists, but it has a small performance cost, so it\[aq]s recommended to use \f[V]...\f[R] instead in cases that are sensitive to overhead. .PP When destructuring a non-sequential table, you can capture the original table along with the destructuring by using \f[V]&as\f[R]: .PP Example: .IP .nf \f[C] (let [{:a a :b b &as all} {:a 1 :b 2 :c 3 :d 4}] (+ a b all.c all.d)) ; => 10 \f[R] .fi .SS \f[V]local\f[R] declare local .PP Introduces a new local inside an existing scope. Similar to \f[V]let\f[R] but without a body argument. Recommended for use at the top-level of a file for locals which will be used throughout the file. .PP Example: .IP .nf \f[C] (local tau-approx 6.28318) \f[R] .fi .PP Supports destructuring and multiple-value binding. .SS \f[V]case\f[R] pattern matching .PP \f[I](Since 1.3.0)\f[R] .PP Evaluates its first argument, then searches thru the subsequent pattern/body clauses to find one where the pattern matches the value, and evaluates the corresponding body. Pattern matching can be thought of as a combination of destructuring and conditionals. .PP \f[B]Note\f[R]: Lua also has \[dq]patterns\[dq] which are matched against strings similar to how regular expressions work in other languages; these are two distinct concepts with similar names. .PP Example: .IP .nf \f[C] (case mytable 59 :will-never-match-hopefully [9 q 5] (print :q q) [1 a b] (+ a b)) \f[R] .fi .PP In the example above, we have a \f[V]mytable\f[R] value followed by three pattern/body clauses. .PP The first clause will only match if \f[V]mytable\f[R] is 59. .PP The second clause will match if \f[V]mytable\f[R] is a table with 9 as its first element, any non-nil value as its second value and 5 as its third element; if it matches, then it evaluates \f[V](print :q q)\f[R] with \f[V]q\f[R] bound to the second element of \f[V]mytable\f[R]. .PP The final clause will only match if \f[V]mytable\f[R] has 1 as its first element and two non-nil values after it; if so then it will add up the second and third elements. .PP If no clause matches, the form evaluates to nil. .PP Patterns can be tables, literal values, or symbols. Any symbol is implicitly checked to be not \f[V]nil\f[R]. Symbols can be repeated in an expression to check for the same value. .PP Example: .IP .nf \f[C] (case mytable ;; the first and second values of mytable are not nil and are the same value [a a] (* a 2) ;; the first and second values are not nil and are not the same value [a b] (+ a b)) \f[R] .fi .PP It\[aq]s important to note that expressions are checked \f[I]in order!\f[R] In the above example, since \f[V][a a]\f[R] is checked first, we can be confident that when \f[V][a b]\f[R] is checked, the two values must be different. Had the order been reversed, \f[V][a b]\f[R] would always match as long as they\[aq]re not \f[V]nil\f[R] - even if they have the same value! .PP You may allow a symbol to optionally be \f[V]nil\f[R] by prefixing it with \f[V]?\f[R]. .PP Example: .IP .nf \f[C] (case mytable ;; not-nil, maybe-nil [a ?b] :maybe-one-maybe-two-values ;; maybe-nil == maybe-nil, both are nil or both are the same value [?a ?a] :maybe-none-maybe-two-same-values ;; maybe-nil, maybe-nil [?a ?b] :maybe-none-maybe-one-maybe-two-values) \f[R] .fi .PP Symbols prefixed by an \f[V]_\f[R] are ignored and may stand in as positional placeholders or markers for \[dq]any\[dq] value - including a \f[V]nil\f[R] value. A single \f[V]_\f[R] is also often used at the end of a \f[V]case\f[R] expression to define an \[dq]else\[dq] style fall-through value. .PP Example: .IP .nf \f[C] (case mytable ;; not-nil, anything [a _b] :maybe-one-maybe-two-values ;; anything, anything (different to the previous ?a example!) ;; note this is effectively the same as [] [_a _a] :maybe-none-maybe-one-maybe-two-values ;; anything, anything ;; this is identical to [_a _a] and in this example would never actually match. [_a _b] :maybe-none-maybe-one-maybe-two-values ;; when no other clause matched, in this case any non-table value _ :no-match) \f[R] .fi .PP Tables can be nested, and they may be either sequential (\f[V][]\f[R] style) or key/value (\f[V]{}\f[R] style) tables. Sequential tables will match if they have at least as many elements as the pattern. (To allow an element to be nil, see \f[V]?\f[R] and \f[V]_\f[R] as above.) Tables will \f[I]never\f[R] fail to match due to having too many elements - this means \f[V][]\f[R] matches \f[I]any\f[R] table, not an \f[I]empty\f[R] table. You can use \f[V]&\f[R] to capture all the remaining elements of a sequential table, just like \f[V]let\f[R]. .IP .nf \f[C] (case mytable {:subtable [a b ?c] :depth depth} (* b depth) _ :unknown) \f[R] .fi .PP You can also match against multiple return values using parentheses. (These cannot be nested, but they can contain tables.) This can be useful for error checking. .IP .nf \f[C] (case (io.open \[dq]/some/file\[dq]) (nil msg) (report-error msg) f (read-file f)) \f[R] .fi .SS Guard Clauses .PP Sometimes you need to match on something more general than a structure or specific value. In these cases you can use guard clauses: .IP .nf \f[C] (case [91 12 53] (where [a b c] (= 5 a)) :will-not-match (where [a b c] (= 0 (math.fmod (+ a b c) 2)) (= 91 a)) c) ; -> 53 \f[R] .fi .PP In this case the pattern should be wrapped in parentheses (like when matching against multiple values) but the first thing in the parentheses is the \f[V]where\f[R] symbol. Each form after the pattern is a condition; all the conditions must evaluate to true for that pattern to match. .PP If several patterns share the same body and guards, such patterns can be combined with \f[V]or\f[R] special in the \f[V]where\f[R] clause: .IP .nf \f[C] (case [5 1 2] (where (or [a 3 9] [a 1 2]) (= 5 a)) \[dq]Either [5 3 9] or [5 1 2]\[dq] _ \[dq]anything else\[dq]) \f[R] .fi .PP This is essentially equivalent to: .IP .nf \f[C] (case [5 1 2] (where [a 3 9] (= 5 a)) \[dq]Either [5 3 9] or [5 1 2]\[dq] (where [a 1 2] (= 5 a)) \[dq]Either [5 3 9] or [5 1 2]\[dq] _ \[dq]anything else\[dq]) \f[R] .fi .PP However, patterns which bind variables should not be combined with \f[V]or\f[R] if different variables are bound in different patterns or some variables are missing: .IP .nf \f[C] ;; bad (case [1 2 3] ;; Will throw an error because \[ga]b\[aq] is nil for the first ;; pattern but the guard still uses it. (where (or [a 1 2] [a b 3]) (< a 0) (< b 1)) :body) ;; ok (case [1 2 3] (where (or [a b 2] [a b 3]) (< a 0) (<= b 1)) :body) \f[R] .fi .SS Binding Pinning .PP Symbols bound inside a \f[V]case\f[R] pattern are independent from any existing symbols in the current scope, that is - names may be re-used without consequence. .PP Example: .IP .nf \f[C] (let [x 1] (case [:hello] ;; \[ga]x\[ga] is simply bound to the first value of [:hello] [x] x)) ; -> :hello \f[R] .fi .PP Sometimes it may be desirable to match against an existing value in the outer scope. To do this we can \[dq]pin\[dq] a binding inside the pattern with an existing outer binding with the unary \f[V](= binding-name)\f[R] form. The unary \f[V](= binding-name)\f[R] form is \f[I]only\f[R] valid in a \f[V]case\f[R] pattern and \f[I]must\f[R] be inside a \f[V](where)\f[R] guard. .PP Example: .IP .nf \f[C] (let [x 1] (case [:hello] ;; 1 != :hello (where [(= x)]) x _ :no-match)) ; -> no-match (let [x 1] (case [1] ;; 1 == 1 (where [(= x)]) x _ :no-match)) ; -> 1 (let [pass :hunter2] (case (user-input) (where (= pass)) :login _ :try-again!)) \f[R] .fi .PP Pinning is only required inside the pattern. Outer bindings are automatically available inside guards and bodies as long as the name has not been rebound in the pattern. .PP \f[B]Note:\f[R] The \f[V]case\f[R] macro can be used in place of the \f[V]if-let\f[R] macro from Clojure. The reason Fennel doesn\[aq]t have \f[V]if-let\f[R] is that \f[V]case\f[R] makes it redundant. .SS \f[V]match\f[R] pattern matching .PP \f[V]match\f[R] is conceptually equivalent to \f[V]case\f[R], except symbols in the patterns are always pinned with outer-scope symbols if they exist. .PP It supports all the same syntax as described in \f[V]case\f[R] except the pin (\f[V](= binding-name)\f[R]) expression, as it is always performed. .RS .PP Be careful when using \f[V]match\f[R] that your symbols are not accidentally the same as any existing symbols! If you know you don\[aq]t intend to pin any existing symbols you should use the \f[V]case\f[R] expression. .RE .IP .nf \f[C] (let [x 95] (match [52 85 95] [b a a] :no ; because a=85 and a=95 [x y z] :no ; because x=95 and x=52 [a b x] :yes)) ; a and b are fresh values while x=95 and x=95 \f[R] .fi .PP Unlike in \f[V]case\f[R], if an existing binding has the value \f[V]nil\f[R], the \f[V]?\f[R] prefix is not necessary - it would instead create a new un-pinned binding! .PP Example: .IP .nf \f[C] (let [name nil get-input (fn [] \[dq]Dave\[dq])] (match (get-input) ;; name already exists as nil, \[dq]Dave\[dq] != nil so this *wont* match name (.. \[dq]Hello \[dq] name) ?no-input (.. \[dq]Hello anonymous\[dq]))) ; -> \[dq]Hello anonymous\[dq] \f[R] .fi .PP \f[B]Note:\f[R] Prior to Fennel 0.9.0 the \f[V]match\f[R] macro used infix \f[V]?\f[R] operator to test patterns against the guards. While this syntax is still supported, \f[V]where\f[R] should be preferred instead: .IP .nf \f[C] (match [1 2 3] (where [a 2 3] (< 0 a)) \[dq]new guard syntax\[dq] ([a 2 3] ? (< 0 a)) \[dq]obsolete guard syntax\[dq]) \f[R] .fi .SS \f[V]case-try\f[R] for matching multiple steps .PP Evaluates a series of pattern matching steps. The value from the first expression is matched against the first pattern. If it matches, the first body is evaluated and its value is matched against the second pattern, etc. .PP If there is a \f[V](catch pat1 body1 pat2 body2 ...)\f[R] form at the end, any mismatch from the steps will be tried against these patterns in sequence as a fallback just like a normal \f[V]case\f[R]. If no \f[V]catch\f[R] pattern matches, nil is returned. .PP If there is no catch, the mismatched value will be returned as the value of the entire expression. .IP .nf \f[C] (fn handle [conn token] (case-try (conn:receive :*l) input (parse input) (command-name params (= token)) (commands.get command-name) command (pcall command (table.unpack params)) (catch (_ :timeout) nil (_ :closed) (pcall disconnect conn \[dq]connection closed\[dq]) (_ msg) (print \[dq]Error handling input\[dq] msg)))) \f[R] .fi .PP This is useful when you want to perform a series of steps, any of which could fail. The \f[V]catch\f[R] clause lets you keep all your error handling in one place. Note that there are two ways to indicate failure in Fennel and Lua: using the \f[V]assert\f[R]/\f[V]error\f[R] functions or returning nil followed by some data representing the failure. This form only works on the latter, but you can use \f[V]pcall\f[R] to transform \f[V]error\f[R] calls into values. .SS \f[V]match-try\f[R] for matching multiple steps .PP Equivalent to \f[V]case-try\f[R] but uses \f[V]match\f[R] internally. See \f[V]case\f[R] and \f[V]match\f[R] for details on the differences between these two forms. .PP Unlike \f[V]case-try\f[R], \f[V]match-try\f[R] will pin values in a given \f[V]catch\f[R] block with those in the original steps. .IP .nf \f[C] (fn handle [conn token] (match-try (conn:receive :*l) input (parse input) (command-name params token) (commands.get command-name) command (pcall command (table.unpack params)) (catch (_ :timeout) nil (_ :closed) (pcall disconnect conn \[dq]connection closed\[dq]) (_ msg) (print \[dq]Error handling input\[dq] msg)))) \f[R] .fi .SS \f[V]var\f[R] declare local variable .PP Introduces a new local inside an existing scope which may have its value changed. Identical to \f[V]local\f[R] apart from allowing \f[V]set\f[R] to work on it. .PP Example: .IP .nf \f[C] (var x 83) \f[R] .fi .PP Supports destructuring and multiple-value binding. .SS \f[V]set\f[R] set local variable or table field .PP Changes the value of a variable introduced with \f[V]var\f[R]. Will not work on globals or \f[V]let\f[R]/\f[V]local\f[R]-bound locals. Can also be used to change a field of a table, even if the table is bound with \f[V]let\f[R] or \f[V]local\f[R], provided the field is given at compile-time. .PP Example: .IP .nf \f[C] (set x (+ x 91)) \f[R] .fi .PP Example: .IP .nf \f[C] (let [t {:a 4 :b 8}] (set t.a 2) t) ; => {:a 2 :b 8} \f[R] .fi .PP Supports destructuring and multiple-value binding. .SS \f[V]tset\f[R] set table field .PP Sets the field of a given table to a new value. The field name does not need to be known at compile-time. Works on any table; the table does not have to be declared with \f[V]var\f[R] to change its fields. .PP Example: .IP .nf \f[C] (let [tbl {:d 32} field :d] (tset tbl field 19) tbl) ; => {:d 19} \f[R] .fi .PP You can provide multiple successive field names to perform nested sets. For example: .IP .nf \f[C] (let [tbl {:a {:b {}}} field :c] (tset tbl :a :b field \[dq]d\[dq]) tbl) ; => {:a {:b {:c \[dq]d\[dq]}}} \f[R] .fi .SS multiple value binding .PP In any of the above contexts where you can make a new binding, you can use multiple value binding. Otherwise you will only capture the first value. .PP Example: .IP .nf \f[C] (let [x (values 1 2 3)] x) ; => 1 \f[R] .fi .PP Example: .IP .nf \f[C] (let [(file-handle message code) (io.open \[dq]foo.blah\[dq])] message) ; => \[dq]foo.blah: No such file or directory\[dq] \f[R] .fi .PP Example: .IP .nf \f[C] (do (local (_ _ z) (unpack [:a :b :c :d :e])) z) => c \f[R] .fi .SS \f[V]with-open\f[R] bind and auto-close file handles .PP While Lua will automatically close an open file handle when it\[aq]s garbage collected, GC may not run right away; \f[V]with-open\f[R] ensures handles are closed immediately, error or no, without boilerplate. .PP The usage is similar to \f[V]let\f[R], except: .IP \[bu] 2 destructuring is disallowed (symbols only on the left-hand side) .IP \[bu] 2 every binding should be a file handle or other value with a \f[V]:close\f[R] method. .PP After executing the body, or upon encountering an error, \f[V]with-open\f[R] will invoke \f[V](value:close)\f[R] on every bound variable before returning the results. .PP The body is implicitly wrapped in a function and run with \f[V]xpcall\f[R] so that all bound handles are closed before it re-raises the error. .PP Example: .IP .nf \f[C] ;; Basic usage (with-open [fout (io.open :output.txt :w) fin (io.open :input.txt)] (fout:write \[dq]Here is some text!\[rs]n\[dq]) ((fin:lines))) ; => first line of input.txt ;; This demonstrates that the file will also be closed upon error. (var fh nil) (local (ok err) (pcall #(with-open [file (io.open :test.txt :w)] (set fh file) ; you would normally never do this (error :whoops!)))) (io.type fh) ; => \[dq]closed file\[dq] [ok err] ; => [false \[dq]\[dq]] \f[R] .fi .SS \f[V]pick-values\f[R] emit exactly n values .PP Discards all values after the first n when dealing with multi-values (\f[V]...\f[R]) and multiple returns. Useful for composing functions that return multiple values with variadic functions. Expands to a \f[V]let\f[R] expression that binds and re-emits exactly n values, e.g. .IP .nf \f[C] (pick-values 2 (func)) \f[R] .fi .PP expands to .IP .nf \f[C] (let [(_0_ _1_) (func)] (values _0_ _1_)) \f[R] .fi .PP Example: .IP .nf \f[C] (pick-values 0 :a :b :c :d :e) ; => nil [(pick-values 2 (table.unpack [:a :b :c]))] ;-> [\[dq]a\[dq] \[dq]b\[dq]] (fn add [x y ...] (let [sum (+ (or x 0) (or y 0))] (if (= (select :# ...) 0) sum (add sum ...)))) (add (pick-values 2 10 10 10 10)) ; => 20 (->> [1 2 3 4 5] (table.unpack) (pick-values 3) (add)) ; => 6 \f[R] .fi .PP \f[B]Note:\f[R] If n is greater than the number of values supplied, n values will still be emitted. This is reflected when using \f[V](select \[dq]#\[dq] ...)\f[R] to count varargs, but tables \f[V][...]\f[R] ignore trailing nils: .IP .nf \f[C] (select :# (pick-values 5 \[dq]one\[dq] \[dq]two\[dq])) ; => 5 [(pick-values 5 \[dq]one\[dq] \[dq]two\[dq])] ; => [\[dq]one\[dq] \[dq]two\[dq]] \f[R] .fi .SH FLOW CONTROL .SS \f[V]if\f[R] conditional .PP Checks a condition and evaluates a corresponding body. Accepts any number of condition/body pairs; if an odd number of arguments is given, the last value is treated as a catch-all \[dq]else\[dq]. Similar to \f[V]cond\f[R] in other lisps. .PP Example: .IP .nf \f[C] (let [x (math.random 64)] (if (= 0 (% x 10)) \[dq]multiple of ten\[dq] (= 0 (% x 2)) \[dq]even\[dq] \[dq]I dunno, something else\[dq])) \f[R] .fi .PP All values other than nil or false are treated as true. .SS \f[V]when\f[R] single side-effecting conditional .PP Takes a single condition and evaluates the rest as a body if it\[aq]s not nil or false. This is intended for side-effects. The last form in the body is used as the return value. .PP Example: .IP .nf \f[C] (when launch-missiles? (power-on) (open-doors) (fire)) \f[R] .fi .SS \f[V]each\f[R] general iteration .PP Runs the body once for each value provided by the iterator. Commonly used with \f[V]ipairs\f[R] (for sequential tables) or \f[V]pairs\f[R] (for any table in undefined order) but can be used with any iterator. Returns nil. .PP Example: .IP .nf \f[C] (each [key value (pairs mytbl)] (print \[dq]executing key\[dq]) (print (f value))) \f[R] .fi .PP Any loop can be terminated early by placing an \f[V]&until\f[R] clause at the end of the bindings: .IP .nf \f[C] (local out []) (each [_ value (pairs tbl) &until (< max-len (length out))] (table.insert out value)) \f[R] .fi .PP \f[B]Note:\f[R] prior to fennel version 1.2.0, \f[V]:until\f[R] was used instead of \f[V]&until\f[R]; the old syntax is still supported for backwards compatibility. .PP Most iterators return two values, but \f[V]each\f[R] will bind any number. See Programming in Lua (https://www.lua.org/pil/7.1.html) for details about how iterators work. .SS \f[V]for\f[R] numeric loop .PP Counts a number from a start to stop point (inclusive), evaluating the body once for each value. Accepts an optional step. Returns nil. .PP Example: .IP .nf \f[C] (for [i 1 10 2] (log-number i) (print i)) \f[R] .fi .PP This example will print all odd numbers under ten. .PP Like \f[V]each\f[R], loops using \f[V]for\f[R] can also be terminated early with an \f[V]&until\f[R] clause. The clause is checked before each iteration of the body; if it is true at the beginning then the body will not run at all. .IP .nf \f[C] (var x 0) (for [i 1 128 &until (maxed-out? x)] (set x (+ x i))) \f[R] .fi .SS \f[V]while\f[R] good old while loop .PP Loops over a body until a condition is met. Uses a native Lua \f[V]while\f[R] loop. Returns nil. .PP Example: .IP .nf \f[C] (var done? false) (while (not done?) (print :not-done) (when (< 0.95 (math.random)) (set done? true))) \f[R] .fi .SS \f[V]do\f[R] evaluate multiple forms returning last value .PP Accepts any number of forms and evaluates all of them in order, returning the last value. This is used for inserting side-effects into a form which accepts only a single value, such as in a body of an \f[V]if\f[R] when multiple clauses make it so you can\[aq]t use \f[V]when\f[R]. Some lisps call this \f[V]begin\f[R] or \f[V]progn\f[R]. .IP .nf \f[C] (if launch-missiles? (do (power-on) (open-doors) (fire)) false-alarm? (promote lt-petrov)) \f[R] .fi .PP Some other forms like \f[V]fn\f[R] and \f[V]let\f[R] have an implicit \f[V]do\f[R]. .SH DATA .SS operators .IP \[bu] 2 \f[V]and\f[R], \f[V]or\f[R], \f[V]not\f[R]: boolean .IP \[bu] 2 \f[V]+\f[R], \f[V]-\f[R], \f[V]*\f[R], \f[V]/\f[R], \f[V]//\f[R], \f[V]%\f[R], \f[V]\[ha]\f[R]: arithmetic .IP \[bu] 2 \f[V]>\f[R], \f[V]<\f[R], \f[V]>=\f[R], \f[V]<=\f[R], \f[V]=\f[R], \f[V]not=\f[R]: comparison .IP \[bu] 2 \f[V]lshift\f[R], \f[V]rshift\f[R], \f[V]band\f[R], \f[V]bor\f[R], \f[V]bxor\f[R], \f[V]bnot\f[R]: bitwise operations .PP These all work as you would expect, with a few caveats. The bitwise operators are only available in Lua 5.3+, unless you use the \f[V]--use-bit-lib\f[R] flag or the \f[V]useBitLib\f[R] flag in the options table, which lets them be used in LuaJIT. The integer division operator (\f[V]//\f[R]) is only available in Lua 5.3+. .PP They all take any number of arguments, as long as that number is fixed at compile-time. For instance, \f[V](= 2 2 (unpack [2 5]))\f[R] will evaluate to \f[V]true\f[R] because the compile-time number of values being compared is 3. Multiple values at runtime will not be taken into account. .PP Note that these are all special forms which cannot be used as higher-order functions. .SS \f[V]..\f[R] string concatenation .PP Concatenates its arguments into one string. Will coerce numbers into strings, but not other types. .PP Example: .IP .nf \f[C] (.. \[dq]Hello\[dq] \[dq] \[dq] \[dq]world\[dq] 7 \[dq]!!!\[dq]) ; => \[dq]Hello world7!!!\[dq] \f[R] .fi .PP String concatenation is subject to the same compile-time limit as the operators above; it is not aware of multiple values at runtime. .SS \f[V]length\f[R] string or table length .PP \f[I](Changed in 0.3.0: it was called \f[VI]#\f[I] before.)\f[R] .PP Returns the length of a string or table. Note that the length of a table with gaps (nils) in it is undefined; it can return a number corresponding to any of the table\[aq]s \[dq]boundary\[dq] positions between nil and non-nil values. If a table has nils and you want to know the last consecutive numeric index starting at 1, you must calculate it yourself with \f[V]ipairs\f[R]; if you want to know the maximum numeric key in a table with nils, you can use \f[V]table.maxn\f[R] on some versions of Lua. .PP Example: .IP .nf \f[C] (+ (length [1 2 3 nil 8]) (length \[dq]abc\[dq])) ; => 6 or 8 \f[R] .fi .SS \f[V].\f[R] table lookup .PP Looks up a given key in a table. Multiple arguments will perform nested lookup. .PP Example: .IP .nf \f[C] (. mytbl myfield) \f[R] .fi .PP Example: .IP .nf \f[C] (let [t {:a [2 3 4]}] (. t :a 2)) ; => 3 \f[R] .fi .PP Note that if the field name is a string known at compile time, you don\[aq]t need this and can just use \f[V]mytbl.field\f[R]. .SS Nil-safe \f[V]?.\f[R] table lookup .PP Looks up a given key in a table. Multiple arguments will perform nested lookup. If any of subsequent keys is not present, will short-circuit to \f[V]nil\f[R]. .PP Example: .IP .nf \f[C] (?. mytbl myfield) \f[R] .fi .PP Example: .IP .nf \f[C] (let [t {:a [2 3 4]}] (?. t :a 4 :b)) ; => nil (let [t {:a [2 3 4 {:b 42}]}] (?. t :a 4 :b)) ; => 42 \f[R] .fi .SS \f[V]icollect\f[R], \f[V]collect\f[R] table comprehension macros .PP \f[I](Since 0.8.0)\f[R] .PP The \f[V]icollect\f[R] macro takes a \[dq]iterator binding table\[dq] in the format that \f[V]each\f[R] takes, and returns a sequential table containing all the values produced by each iteration of the macro\[aq]s body. This is similar to how \f[V]map\f[R] works in several other languages, but it is a macro, not a function. .PP If the value is nil, it is omitted from the return table. This is analogous to \f[V]filter\f[R] in other languages. .IP .nf \f[C] (icollect [_ v (ipairs [1 2 3 4 5 6])] (if (< 2 v) (* v v))) ;; -> [9 16 25 36] ;; equivalent to: (let [tbl []] (each [_ v (ipairs [1 2 3 4 5 6])] (tset tbl (+ (length tbl) 1) (if (< 2 v) (* v v)))) tbl) \f[R] .fi .PP The \f[V]collect\f[R] macro is almost identical, except that the body should return two things: a key and a value. .IP .nf \f[C] (collect [k v (pairs {:apple \[dq]red\[dq] :orange \[dq]orange\[dq] :lemon \[dq]yellow\[dq]})] (if (not= v \[dq]yellow\[dq]) (values (.. \[dq]color-\[dq] v) k))) ;; -> {:color-orange \[dq]orange\[dq] :color-red \[dq]apple\[dq]} ;; equivalent to: (let [tbl {}] (each [k v (pairs {:apple \[dq]red\[dq] :orange \[dq]orange\[dq]})] (if (not= v \[dq]yellow\[dq]) (match (values (.. \[dq]color-\[dq] v) k) (key value) (tset tbl key value)))) tbl) \f[R] .fi .PP If the key and value are given directly in the body of \f[V]collect\f[R] and not nested in an outer form, then the \f[V]values\f[R] can be omitted for brevity: .IP .nf \f[C] (collect [k v (pairs {:a 85 :b 52 :c 621 :d 44})] k (* v 5)) \f[R] .fi .PP Like \f[V]each\f[R] and \f[V]for\f[R], the table comprehensions support an \f[V]&until\f[R] clause for early termination. .PP Both \f[V]icollect\f[R] and \f[V]collect\f[R] take an \f[V]&into\f[R] clause which allows you put your results into an existing table instead of starting with an empty one: .IP .nf \f[C] (icollect [_ x (ipairs [2 3]) &into [9]] (* x 11)) ;; -> [9 22 33] \f[R] .fi .PP \f[B]Note:\f[R] Prior to fennel version 1.2.0, \f[V]:into\f[R] was used instead of \f[V]&into\f[R]; the old syntax is still supported for backwards compatibility. .SS \f[V]accumulate\f[R] iterator accumulation .PP \f[I](Since 0.10.0)\f[R] .PP Runs through an iterator and performs accumulation, similar to \f[V]fold\f[R] and \f[V]reduce\f[R] commonly used in functional programming languages. Like \f[V]collect\f[R] and \f[V]icollect\f[R], it takes an iterator binding table and an expression as its arguments. The difference is that in \f[V]accumulate\f[R], the first two items in the binding table are used as an \[dq]accumulator\[dq] variable and its initial value. For each iteration step, it evaluates the given expression and its value becomes the next accumulator variable. \f[V]accumulate\f[R] returns the final value of the accumulator variable. .PP Example: .IP .nf \f[C] (accumulate [sum 0 i n (ipairs [10 20 30 40])] (+ sum n)) ; -> 100 \f[R] .fi .PP The \f[V]&until\f[R] clause is also supported here for early termination. .SS \f[V]faccumulate\f[R] range accumulation .PP \f[I](Since 1.3.0)\f[R] .PP Identical to accumulate, but instead of taking an iterator and the same bindings as \f[V]each\f[R], it accepts the same bindings as \f[V]for\f[R] and will iterate the numerical range. Accepts \f[V]&until\f[R] just like \f[V]for\f[R] and \f[V]accumulate\f[R]. .PP Example: .IP .nf \f[C] (faccumulate [n 0 i 1 5] (+ n i)) ; => 15 \f[R] .fi .SS \f[V]fcollect\f[R] range comprehension macro .PP \f[I](Since 1.1.1)\f[R] .PP Similarly to \f[V]icollect\f[R], \f[V]fcollect\f[R] provides a way of building a sequential table. Unlike \f[V]icollect\f[R], instead of an iterator it traverses a range, as accepted by the \f[V]for\f[R] special. The \f[V]&into\f[R] and \f[V]&until\f[R] clauses work the same as in \f[V]icollect\f[R]. .PP Example: .IP .nf \f[C] (fcollect [i 0 10 2] (if (> i 2) (* i i))) ;; -> [16 36 64 100] ;; equivalent to: (let [tbl {}] (for [i 0 10 2] (if (> i 2) (table.insert tbl (* i i)))) tbl) \f[R] .fi .SS \f[V]values\f[R] multi-valued return .PP Returns multiple values from a function. Usually used to signal failure by returning nil followed by a message. .PP Example: .IP .nf \f[C] (fn [filename] (if (valid-file-name? filename) (open-file filename) (values nil (.. \[dq]Invalid filename: \[dq] filename)))) \f[R] .fi .SH OTHER .SS \f[V]:\f[R] method call .PP Looks up a function in a table and calls it with the table as its first argument. This is a common idiom in many Lua APIs, including some built-in ones. .PP Just like Lua, you can perform a method call by calling a function name where \f[V]:\f[R] separates the table variable and method name. .PP Example: .IP .nf \f[C] (let [f (assert (io.open \[dq]hello\[dq] \[dq]w\[dq]))] (f:write \[dq]world\[dq]) (f:close)) \f[R] .fi .PP In the example above, \f[V]f:write\f[R] is a single multisym. If the name of the method or the table containing it isn\[aq]t fixed, you can use \f[V]:\f[R] followed by the table and then the method\[aq]s name to allow it to be a dynamic string instead: .PP Example: .IP .nf \f[C] (let [f (assert (io.open \[dq]hello\[dq] \[dq]w\[dq])) method1 :write method2 :close] (: f method1 \[dq]world\[dq]) (: f method2)) \f[R] .fi .PP Both of these examples are equivalent to the following: .IP .nf \f[C] (let [f (assert (io.open \[dq]hello\[dq] \[dq]w\[dq]))] (f.write f \[dq]world\[dq]) (f.close f)) \f[R] .fi .PP Unlike Lua, there\[aq]s nothing special about defining functions that get called this way; typically it is given an extra argument called \f[V]self\f[R] but this is just a convention; you can name it anything. .IP .nf \f[C] (local t {}) (fn t.enable [self] (set self.enabled? true)) (t:enable) \f[R] .fi .SS \f[V]->\f[R], \f[V]->>\f[R], \f[V]-?>\f[R] and \f[V]-?>>\f[R] threading macros .PP The \f[V]->\f[R] macro takes its first value and splices it into the second form as the first argument. The result of evaluating the second form gets spliced into the first argument of the third form, and so on. .PP Example: .IP .nf \f[C] (-> 52 (+ 91 2) ; (+ 52 91 2) (- 8) ; (- (+ 52 91 2) 8) (print \[dq]is the answer\[dq])) ; (print (- (+ 52 91 2) 8) \[dq]is the answer\[dq]) \f[R] .fi .PP The \f[V]->>\f[R] macro works the same, except it splices it into the last position of each form instead of the first. .PP \f[V]-?>\f[R] and \f[V]-?>>\f[R], the thread maybe macros, are similar to \f[V]->\f[R] & \f[V]->>\f[R] but they also do checking after the evaluation of each threaded form. If the result is false or nil then the threading stops and the result is returned. \f[V]-?>\f[R] splices the threaded value as the first argument, like \f[V]->\f[R], and \f[V]-?>>\f[R] splices it into the last position, like \f[V]->>\f[R]. .PP This example shows how to use them to avoid accidentally indexing a nil value: .IP .nf \f[C] (-?> {:a {:b {:c 42}}} (. :a) (. :missing) (. :c)) ; -> nil (-?>> :a (. {:a :b}) (. {:b :missing}) (. {:c 42})) ; -> nil \f[R] .fi .PP While \f[V]->\f[R] and \f[V]->>\f[R] pass multiple values thru without any trouble, the checks in \f[V]-?>\f[R] and \f[V]-?>>\f[R] prevent the same from happening there without performance overhead, so these pipelines are limited to a single value. .RS .PP Note that these have nothing to do with \[dq]threads\[dq] used for concurrency; they are named after the thread which is used in sewing. This is similar to the way that \f[V]|>\f[R] works in OCaml and Elixir. .RE .SS \f[V]doto\f[R] .PP Similarly, the \f[V]doto\f[R] macro splices the first value into subsequent forms. However, it keeps the same value and continually splices the same thing in rather than using the value from the previous form for the next form. .IP .nf \f[C] (doto (io.open \[dq]/tmp/err.log\[dq]) (: :write contents) (: :close)) ;; equivalent to: (let [x (io.open \[dq]/tmp/err.log\[dq])] (: x :write contents) (: x :close) x) \f[R] .fi .PP The first form becomes the return value for the whole expression, and subsequent forms are evaluated solely for side-effects. .SS \f[V]tail!\f[R] .PP Tail calls will be optimized automatically. However, the \f[V]tail!\f[R] form asserts that its argument is called in a tail position. You can use this when the code depends on tail call optimization; that way if the code is changed so that the recursive call is no longer in the tail position, it will cause a compile error instead of overflowing the stack later on large data sets. .IP .nf \f[C] (fn process-all [data i] (case (process (. data i)) :done (print \[dq]Process completed.\[dq]) :next (process-all data (+ i 1)) :skip (do (tail! (process-all data (+ i 2))) ;; \[ha]\[ha]\[ha]\[ha]\[ha] Compile error: Must be in tail position (print \[dq]Skipped\[dq] (+ i 1))))) \f[R] .fi .SS \f[V]include\f[R] .IP .nf \f[C] (include :my.embedded.module) \f[R] .fi .PP Loads Fennel/Lua module code at compile time and embeds it in the compiled output. The module name must resolve to a string literal during compilation. The bundled code will be wrapped in a function invocation in the emitted Lua and set on \f[V]package.preload[modulename]\f[R]; a normal \f[V]require\f[R] is then emitted where \f[V]include\f[R] was used to load it on demand as a normal module. .PP In most cases it\[aq]s better to use \f[V]require\f[R] in your code and use the \f[V]requireAsInclude\f[R] option in the API documentation and the \f[V]--require-as-include\f[R] CLI flag (\f[V]fennel --help\f[R]) to accomplish this. .PP The \f[V]require\f[R] function is not part of Fennel; it comes from Lua. However, it works to load Fennel code. See the Modules and multiple files section in the tutorial and Programming in Lua (https://www.lua.org/pil/8.1.html) for details about \f[V]require\f[R]. .PP Starting from version 0.10.0 \f[V]include\f[R] and hence \f[V]--require-as-include\f[R] support semi-dynamic compile-time resolution of module paths similarly to \f[V]import-macros\f[R]. See the relative require section in the tutorial for more information. .SS \f[V]assert-repl\f[R] .PP \f[I](Since 1.4.0)\f[R] .PP Sometimes it\[aq]s helpful for debugging purposes to drop a repl right into the middle of your code to see what\[aq]s really going on. You can use the \f[V]assert-repl\f[R] macro to do this: .IP .nf \f[C] (let [input (get-input) value []] (fn helper [x] (table.insert value (calculate x))) (assert-repl (transform helper value) \[dq]could not transform\[dq])) \f[R] .fi .PP This works as a drop-in replacement for the built-in \f[V]assert\f[R] function, but when the condition is false or nil, instead of an error, it drops into a repl which has access to all the locals that are in scope (\f[V]input\f[R], \f[V]value\f[R], and \f[V]helper\f[R] in the example above). .PP Note that this is meant for use in development and will not work with ahead-of-time compilation unless your build also includes Fennel as a library. .PP If you use the \f[V]--assert-as-repl\f[R] flag when running Fennel, calls to \f[V]assert\f[R] will be replaced with \f[V]assert-repl\f[R] automatically. .PP \f[B]Note:\f[R] In Fennel 1.4.0, \f[V]assert-repl\f[R] accepted an options table for \f[V]fennel.repl\f[R] as an optional third argument. This was removed as a bug in 1.4.1, as it broke compatibility with \f[V]assert\f[R]. .PP The REPL spawned by \f[V]assert-repl\f[R] applies the same default options as \f[V]fennel.repl\f[R], which as of Fennel 1.4.1 can be configured from the API. See the Fennel API reference for details. .SS Recovering from failed assertions .PP You can \f[V],return EXPRESSION\f[R] from the repl to replace the original failing condition with a different arbitrary value. Returning false or nil will trigger a regular \f[V]assert\f[R] failure. .PP \f[B]Note:\f[R] Currently, only a single value can be returned from the REPL this way. While \f[V],return\f[R] can be used to make a failed assertion recover, if the calling code expects multiple return values, it may cause unspecified behavior. .SH MACROS .PP All forms which introduce macros do so inside the current scope. This is usually the top level for a given file, but you can introduce macros into nested scopes as well. Note that macros are a compile-time construct; they do not exist at runtime. As such macros cannot be exported at the bottom of a module like functions and other values. .SS \f[V]import-macros\f[R] load macros from a separate module .PP Loads a module at compile-time and binds its functions as local macros. .PP A macro module exports any number of functions which take code forms as arguments at compile time and emit lists which are fed back into the compiler as code. The module calling \f[V]import-macros\f[R] gets whatever functions have been exported to use as macros. For instance, here is a macro module which implements \f[V]when2\f[R] in terms of \f[V]if\f[R] and \f[V]do\f[R]: .IP .nf \f[C] (fn when2 [condition body1 & rest-body] (assert body1 \[dq]expected body\[dq]) \[ga](if ,condition (do ,body1 ,(unpack rest-body)))) {:when2 when2} \f[R] .fi .PP For a full explanation of how this works see the macro guide. All forms in Fennel are normal tables you can use \f[V]table.insert\f[R], \f[V]ipairs\f[R], destructuring, etc on. The backtick on the third line creates a template list for the code emitted by the macro, and the comma serves as \[dq]unquote\[dq] which splices values into the template. .PP Assuming the code above is in the file \[dq]my-macros.fnl\[dq] then it turns this input: .IP .nf \f[C] (import-macros {: when2} :my-macros) (when2 (= 3 (+ 2 a)) (print \[dq]yes\[dq]) (finish-calculation)) \f[R] .fi .PP and transforms it into this code at compile time by splicing the arguments into the backtick template: .IP .nf \f[C] (if (= 3 (+ 2 a)) (do (print \[dq]yes\[dq]) (finish-calculation))) \f[R] .fi .PP The \f[V]import-macros\f[R] macro can take any number of binding/module-name pairs. It can also bind the entire macro module to a single name rather than destructuring it. In this case you can use a dot to call the individual macros inside the module: .IP .nf \f[C] (import-macros mine :my-macros) (mine.when2 (= 3 (+ 2 a)) (print \[dq]yes\[dq]) (finish-calculation)) \f[R] .fi .PP Note that all macro code runs at compile time, which happens before runtime. Locals which are in scope at runtime are not visible during compile-time. So this code will not work: .IP .nf \f[C] (local (module-name file-name) ...) (import-macros mymacros (.. module-name \[dq].macros\[dq])) \f[R] .fi .PP However, this code will work, provided the module in question exists: .IP .nf \f[C] (import-macros mymacros (.. ... \[dq].macros\[dq])) \f[R] .fi .PP See \[dq]Compiler API\[dq] below for details about additional functions visible inside compiler scope which macros run in. .SS Macro module searching .PP By default, Fennel will search for macro modules similarly to how it searches for normal runtime modules: by walking thru entries on \f[V]fennel.macro-path\f[R] and checking the filesystem for matches. However, in some cases this might not be suitable, for instance if your Fennel program is packaged in some kind of archive file and the modules do not exist as distinct files on disk. .PP To support this case you can add your own searcher function to the \f[V]fennel.macro-searchers\f[R] table. For example, assuming \f[V]find-in-archive\f[R] is a function which can look up strings from the archive given a path: .IP .nf \f[C] (local fennel (require :fennel)) (fn my-searcher [module-name] (let [filename (.. \[dq]src/\[dq] module-name \[dq].fnl\[dq])] (match (find-in-archive filename) code (values (partial fennel.eval code {:env :_COMPILER}) filename)))) (table.insert fennel.macro-searchers my-searcher) \f[R] .fi .PP The searcher function should take a module name as a string and return two values if it can find the macro module: a loader function which will return the macro table when called, and an optional filename. The loader function will receive the module name and the filename as arguments. .SS \f[V]macros\f[R] define several macros .PP Defines a table of macros. Note that inside the macro definitions, you cannot access variables and bindings from the surrounding code. The macros are essentially compiled in their own compiler environment. Again, see the \[dq]Compiler API\[dq] section for more details about the functions available here. .IP .nf \f[C] (macros {:my-max (fn [x y] \[ga](let [x# ,x y# ,y] (if (< x# y#) y# x#)))}) (print (my-max 10 20)) (print (my-max 20 10)) (print (my-max 20 20)) \f[R] .fi .SS \f[V]macro\f[R] define a single macro .IP .nf \f[C] (macro my-max [x y] \[ga](let [x# ,x y# ,y] (if (< x# y#) y# x#))) \f[R] .fi .PP If you are only defining a single macro, this is equivalent to the previous example. The syntax mimics \f[V]fn\f[R]. .SS \f[V]macrodebug\f[R] print the expansion of a macro .IP .nf \f[C] (macrodebug (-> abc (+ 99) (< 0) (when (os.exit)))) ; -> (if (< (+ abc 99) 0) (do (os.exit))) \f[R] .fi .PP Call the \f[V]macrodebug\f[R] macro with a form and it will repeatedly expand top-level macros in that form and print out the resulting form. Note that the resulting form will usually not be sensibly indented, so you might need to copy it and reformat it into something more readable. .PP Note that this prints at compile-time since \f[V]macrodebug\f[R] is a macro. .SS Macro gotchas .PP It\[aq]s easy to make macros which accidentally evaluate their arguments more than once. This is fine if they are passed literal values, but if they are passed a form which has side-effects, the result will be unexpected: .IP .nf \f[C] (var v 1) (macros {:my-max (fn [x y] \[ga](if (< ,x ,y) ,y ,x))}) (fn f [] (set v (+ v 1)) v) (print (my-max (f) 2)) ; -> 3 since (f) is called twice in the macro body above \f[R] .fi .PP In order to prevent accidental symbol capture (https://gist.github.com/nimaai/2f98cc421c9a51930e16#variable-capture), you may not bind a bare symbol inside a backtick as an identifier. Appending a \f[V]#\f[R] on the end of the identifier name as above invokes \[dq]auto gensym\[dq] which guarantees the local name is unique. .IP .nf \f[C] (macros {:my-max (fn [x y] \[ga](let [x2 ,x y2 ,y] (if (< x2 y2) y2 x2)))}) (print (my-max 10 20)) ; Compile error in \[aq]x2\[aq] unknown:?: macro tried to bind x2 without gensym; try x2# instead \f[R] .fi .PP \f[V]macros\f[R] is useful for one-off, quick macros, or even some more complicated macros, but be careful. It may be tempting to try and use some function you have previously defined, but if you need such functionality, you should probably use \f[V]import-macros\f[R]. .PP For example, this will not compile in strict mode! Even when it does allow the macro to be called, it will fail trying to call a global \f[V]my-fn\f[R] when the code is run: .IP .nf \f[C] (fn my-fn [] (print \[dq]hi!\[dq])) (macros {:my-max (fn [x y] (my-fn) \[ga](let [x# ,x y# ,y] (if (< x# y#) y# x#)))}) ; Compile error in \[aq]my-max\[aq]: attempt to call global \[aq]__fnl_global__my_2dfn\[aq] (a nil value) \f[R] .fi .SS \f[V]eval-compiler\f[R] .PP Evaluate a block of code during compile-time with access to compiler scope. This gives you a superset of the features you can get with macros, but you should use macros if you can. .PP Example: .IP .nf \f[C] (eval-compiler (each [name (pairs _G)] (print name))) \f[R] .fi .PP This prints all the functions available in compiler scope. .SS Compiler Environment .PP Inside \f[V]eval-compiler\f[R], \f[V]macros\f[R], or \f[V]macro\f[R] blocks, as well as \f[V]import-macros\f[R] modules, the functions listed below are visible to your code. .IP \[bu] 2 \f[V]list\f[R] - return a list, which is a special kind of table used for code. .IP \[bu] 2 \f[V]sym\f[R] - turn a string into a symbol. .IP \[bu] 2 \f[V]gensym\f[R] - generates a unique symbol for use in macros, accepts an optional prefix string. .IP \[bu] 2 \f[V]list?\f[R] - is the argument a list? Returns the argument or \f[V]false\f[R]. .IP \[bu] 2 \f[V]sym?\f[R] - is the argument a symbol? Returns the argument or \f[V]false\f[R]. .IP \[bu] 2 \f[V]table?\f[R] - is the argument a non-list table? Returns the argument or \f[V]false\f[R]. .IP \[bu] 2 \f[V]sequence?\f[R] - is the argument a non-list \f[I]sequential\f[R] table (created with \f[V][]\f[R], as opposed to \f[V]{}\f[R])? Returns the argument or \f[V]false\f[R]. .IP \[bu] 2 \f[V]varg?\f[R] - is this a \f[V]...\f[R] symbol which indicates var args? Returns a special table describing the type or \f[V]false\f[R]. .IP \[bu] 2 \f[V]multi-sym?\f[R] - a multi-sym is a dotted symbol which refers to a table\[aq]s field. Returns a table containing each separate symbol, or \f[V]false\f[R]. .IP \[bu] 2 \f[V]comment?\f[R] - is the argument a comment? Comments are only included when \f[V]opts.comments\f[R] is truthy. .IP \[bu] 2 \f[V]view\f[R] - \f[V]fennel.view\f[R] table serializer. .IP \[bu] 2 \f[V]get-scope\f[R] - return the scope table for the current macro call site. .IP \[bu] 2 \f[V]assert-compile\f[R] - works like \f[V]assert\f[R] but takes a list/symbol as its third argument in order to provide pinpointed error messages. .PP These functions can be used from within macros only, not from any \f[V]eval-compiler\f[R] call: .IP \[bu] 2 \f[V]in-scope?\f[R] - does the symbol refer to an in-scope local? Returns the symbol or \f[V]nil\f[R]. .IP \[bu] 2 \f[V]macroexpand\f[R] - performs macroexpansion on its argument form; returns an AST. .PP Note that lists are compile-time concepts that don\[aq]t exist at runtime; they are implemented as tables which have a special metatable to distinguish them from regular tables defined with square or curly brackets. Similarly symbols are tables with a string entry for their name and a marker metatable. You can use \f[V]tostring\f[R] to get the name of a symbol. .PP As of 1.0.0 the compiler will not allow access to the outside world (\f[V]os\f[R], \f[V]io\f[R], etc) from macros. The one exception is \f[V]print\f[R] which is included for debugging purposes. You can disable this by providing the command-line argument \f[V]--no-compiler-sandbox\f[R] or by passing \f[V]{:compiler-env _G}\f[R] in the options table when using the compiler API to get full access. .PP Please note that the sandbox is not suitable to be used as a robust security mechanism. It has not been audited and should not be relied upon to protect you from running untrusted code. .PP Note that other internals of the compiler exposed in compiler scope but not listed above are subject to change. .SH \f[V]lua\f[R] ESCAPE HATCH .PP There are some cases when you need to emit Lua output from Fennel in ways that don\[aq]t match Fennel\[aq]s semantics. For instance, if you are porting an algorithm from Lua that uses early returns, you may want to do the port as literally as possible first, and then come back to it later to make it idiomatic. You can use the \f[V]lua\f[R] special form to accomplish this: .IP .nf \f[C] (fn find [tbl pred] (each [key val (pairs tbl)] (when (pred val) (lua \[dq]return key\[dq])))) \f[R] .fi .PP Lua code inside the string can refer to locals which are in scope; however note that it must refer to the names after mangling has been done, because the identifiers must be valid Lua. The Fennel compiler will change \f[V]foo-bar\f[R] to \f[V]foo_bar\f[R] in the Lua output in order for it to be valid, as well as other transformations. When in doubt, inspect the compiler output to see what it looks like. For example the following Fennel code: .IP .nf \f[C] (local foo-bar 3) (let [foo-bar :hello] (lua \[dq]print(foo_bar0 .. \[rs]\[dq] world\[rs]\[dq])\[dq])) \f[R] .fi .PP will produce this Lua code: .IP .nf \f[C] local foo_bar = 3 local foo_bar0 = \[dq]hello\[dq] print(foo_bar0 .. \[dq] world\[dq]) return nil \f[R] .fi .PP Normally in these cases you would want to emit a statement, in which case you would pass a string of Lua code as the first argument. But you can also use it to emit an expression if you pass in a string as the second argument. .PP Note that this should only be used in exceptional circumstances, and if you are able to avoid it, you should. .SH DEPRECATED FORMS .PP The \f[V]#\f[R] form is a deprecated alias for \f[V]length\f[R], and \f[V]\[ti]=\f[R] is a deprecated alias for \f[V]not=\f[R], kept for backwards compatibility. .SS \f[V]require-macros\f[R] load macros with less flexibility .PP \f[I](Deprecated in 0.4.0)\f[R] .PP The \f[V]require-macros\f[R] form is like \f[V]import-macros\f[R], except it imports all macros without making it clear what new identifiers are brought into scope. It is strongly recommended to use \f[V]import-macros\f[R] instead. .SS \f[V]pick-args\f[R] create a function of fixed arity .PP \f[I](Deprecated 0.10.0)\f[R] .PP Like \f[V]pick-values\f[R], but takes an integer \f[V]n\f[R] and a function/operator \f[V]f\f[R], and creates a new function that applies exactly \f[V]n\f[R] arguments to \f[V]f\f[R]. .SS \f[V]global\f[R] set global variable .PP \f[I](Deprecated in 1.1.0)\f[R] .PP Sets a global variable to a new value. Note that there is no distinction between introducing a new global and changing the value of an existing one. This supports destructuring and multiple-value binding. .PP Example: .IP .nf \f[C] (global prettyprint (fn [x] (print (fennel.view x)))) \f[R] .fi .PP Using \f[V]global\f[R] adds the identifier in question to the list of allowed globals so that referring to it later on will not cause a compiler error. However, globals are also available in the \f[V]_G\f[R] table, and accessing them that way instead is recommended for clarity. .SS Rest destructuring metamethod .PP \f[I](Deprecated in 1.4.1)\f[R] .PP If a table implements \f[V]__fennelrest\f[R] metamethod it is used to capture the remainder of the table. It can be used with custom data structures implemented in terms of tables, which wish to provide custom rest destructuring. The metamethod receives the table as the first argument, and the amount of values it needs to drop from the beginning of the table, much like table.unpack .PP Example: .IP .nf \f[C] (local t [1 2 3 4 5 6]) (setmetatable t {:__fennelrest (fn [t k] (let [res {}] (for [i k (length t)] (tset res (tostring (. t i)) (. t i))) res))}) (let [[a b & c] t] c) ;; => {:3 3 :4 4 :5 5 :6 6} \f[R] .fi .SH AUTHORS Fennel Maintainers.