Bio is a Lisp dialect written in Zig. Features include macros, garbage collection, error handling, a module facility, a repl, and a small standard library.
NOTE: Bio is the result of a Let's-write-a-Lisp article and is currently not maintained beyond occasionally upgrading to new Zig versions. Currently targets Zig v.0.16.
Example:
(filter
(quicksort '(5 40 1 -3 2) <)
(lambda (x) (>= x 0)))
(1 2 5 40)
The core of Bio is lambda expressions, from which the standard library builds syntax like type and fun:
; Create a composite type. This is sugar for `(var Point (lambda (x y) ... (self)))`
(type Point (x y)
(fun area () (* x y)))
; Make an instance of Point
(var pt (Point 5 7))
; Call a member function. All this is just syntax sugar based on a lambda
; returning its own environment.
(print "Area:" (pt (area)) '\n)
Area: 35
Building and running
Clone the repository and cd to the project directory.
Build
zig build
Run the REPL:
zig-out/bin/bio
Run a Bio source file:
zig-out/bin/bio run examples/triangles.lisp
You can also use import to evaluate files from the REPL, e.g. (import "examples/albums.lisp")
Running tests
The test suite in test.lisp can be evaluated with zig test src/main.zig or ./bio run test.lisp
Language Reference
A Bio program consists of one or more s-expressions. An s-expression is recursively defined as being either
- an atom
- a list, which may contain lists and atoms
An atom is either a 64-bit floating point number, or a symbol. A symbol is any sequence of utf8 code points that is not a valid number. Symbols serve as strings when the symbol is enclosed in double-quotes, such as "This is a symbol". Bio does not have a separate string type; the term string is simply used to denote a symbol serving as a string.
Naming conventions
- Predicates have a question mark suffix, such as
atom?
- Destructive actions have an exclamation point suffix, such as
set!
- Sentinels are prefixed with an ampersand, such as
&rest
- Symbols with special meaning are prefixed
#, such as #t
- Identifiers are kebab-case, while composite types such as modules are PascalCase
Intrinsics
Intrinsics are built-in functions, macros, and symbols implemented by the interpreter. They are building blocks for the standard library and user programs.
nil
A symbol representing the absence of a value. Note that nil and '() are considered equal.
#t and #f
Symbols representing true and false, respectively. Note that nil coerces to #f.
#?
A symbol representing the last top-level expression evaluation.
Example:
(+ 2 3)
(* 2 #?)
10
#! and #value
The #value symbol contains the value returned by a tried expression. This usually removes the need to use a temporary variable when you need to both check for errors and use the result.
The #! symbol contains the error after a try expression. If no error occurs, this is set to nil.
(try (math.safe-div (io.read-number) (io.read-number))
(print "The doubled result is: " (* 2 #value))
(print "Failed: " #!))
typename
The 'typename' functions returns a string representation of the type. The most specific classification is returned, so (typename #t) is "bool", even though #t is also a symbol.
(typename 'a)
"symbol"
(typename math.pi)
"number"
(typename #t)
"bool"
(typename '(a b c))
"list"
(typename +)
"function"
number? symbol? list? bool? callable? error?
Predicates to determine expression types. There's also an atom? predicate in the standard library.
These all return #t
(number? -5.7)
(number? x)
(symbol? 'x)
(symbol? #t)
(bool? #t)
(bool? #f)
(list? '(abc))
(callable? +)
(error? (math.safe-div 4 0))
var and define
'var' creates a variable binding in the current environment. The binding will fail if it already exists in the current environment. The define function is just an alias to var
Variable names can be any utf8 sequence that doesn't start with a number, " and '. Variable names are case-sensitive.
(var x 5)
(define y 5)
(var name (io.read-line))
(var double (lambda (val) (* 2 val)))
(var 😀 "Smiley")
(print 😀)
"Smiley"
Local variables:
(var x 2)
(var y 2)
(var z 2)
(var some-function (lambda (x)
; Allowed, y is not in the local scope
(var y 10)
; Not allowed, x is a formal in the same scope
; (var x 10)
(print x y z)
))
> (some-function 3)
3 10 2
vars
A list can be destructured into variables using vars
(var stuff '(1 2 3))
(vars a b c stuff)
(assert (= a 1))
(assert (= b 2))
(assert (= c 3))
set! and unset!
Changes the value of an existing binding (values themselves are immutable). The binding is searched from current to root scope.
; Define x, then update it
(var x 5)
(set! x 10)
; Be evil and redefine + to mean -
(set! + -)
(+ 10 2)
8
; Remove binding, allowing it to be defined again
(unset! x)
(var x 'hey)
You can optionally pass a specific environment for the binding being set as the first argument:
(type Point (x y)
(fun area () (* x y)))
(var pt (Point 5 7))
(print "Area:" (pt (area)) '\n)
Area: 35
; Change x by passing the pt environment to set!
(set! pt x 6)
(print "Area:" (pt (area)) '\n)
Area: 42
arithmetic functions
The arithmetic functions work on floating-point numbers. Unlike infix notation, any number of arguments can be given.
(+ -3 5)
2
(/ 2 (* 10 (+ math.pi 2 3 (- 2 3))))
0.028004957675577865
; pi symbol is same as math.pi (tip: this is available with Option+P if you're on a mac)
(define circumference (λ (x) (* 2 π x)))
Additional math functions are available in the standard library.
equality
The = and ~= functions check for exact and approximate equality. The approximate case is only for numeric operands and accepts a third argument to override the tolerance (epsilon is by default 1e-7)
(= x 5)
(= '(1 2 3 4) nums)
(= '(1 3) (odd-items nums))
(~= a b 0.0005)
Exact equality is implemented in terms of the order function, allowing nested lists to be compared.
order
The order function returns 0, -1, 1 do indicate if the first argument is equal, less than or greater than the second argument. All expression types are supported.
Lists are recursively compared. If list lengths differ, the shorter one is considered smaller. Empty lists and nil are considered equal, otherwise nil is always considered smaller.
(order 100 200)
-1
(order 'def 'abc)
1
(order '(1 2 3) '(0 1 2))
1
(order '(1 2) '(0 1 2))
-1
(order 6 (* 2 3))
0
Standard library functions such as < are implemented in terms of order.
env
print-env prints the content of the current environment.
> (print-env)
Environment for global: Env@10db4b000
import = <function>, env *Env@0
exit = <function>, env *Env@0
gc = <function>, env *Env@0
#f = #f, env *Env@0
#t = #t, env *Env@0
#? = #t, env *Env@0
nil = nil, env *Env@0
...
The garbage collector runs periodically, though the criteria and extent are intentionally left undefined by this language reference.
fun, lambda and λ
Creating functions in Bio can be done either with fun or lambda. The fun function is just a convenience macro that expands to a lambda definition.
> (fun square (x) (* x x))
> (square 5)
25
Below is the equivalent lambda definition:
> (var square (lambda (x) (* x x)))
> (square 5)
25
Direct application without binding to a variable:
> ((lambda (x) (* x x)) 5)
25
The lambda symbol can be used in place of the lambda identifier
(var doubler (λ (x) (* 2 x)))
A lambda invocation has its own environment, and the parent environment is the one that existed when the lambda was defined. In other words, Bio is lexically scoped.
type
A type expression is syntax sugar for functions returning their own environment. This is useful when making composite types.
(type Point (x y)
(fun area () (* x y))
)
(var pt (Point 5 7))
(print "Area:" (pt (area)) '\n)
; Change x by passing the pt environment to set!
(set! pt x 6)
(print "Area:" (pt (area)) '\n)
Composite types can contain local variables and other functions, just like regular lambda expression.
macro
This function creates a macro.
Unlike lambdas, arguments are not evaluated when the macro is invoked. Instead, they're evaluated if and when the body does so. Note
that eager evaluation of macro arguments can be forced by placed &eval in front of the formal parameter.
When the macro is invoked, the body is evaluated. The returned expression (which represents Bio code) is then evaluated as the final result.
(var print-with-label (macro (label &rest values)
`(print label ": " ,@values)
))
(print-with-label Primes 2 3 5 7)
Primes: 2 3 5 7
A macro invocation has its own environment, and the parent environment is the current one. This is different from lambdas whose parent environment is the one in which the lambda was defined.
macroexpand
You can stop the evaluation of the code returned from a macro by wrapping it in macroexpand
Consider a typical swap macro:
(var swap (macro (a b)
`(let ((temp ,a))
(set! ,a ,b)
(set! ,b temp))))
Here's a typical usage example:
(let ((x 3) (y 7))
(swap x y)
(print "Swapped:" x y "\n")
)
Swapped: 7 3
But now we wanna see how the macro is expanded as code instead:
(let ((x 5) (y 8))
(print "Macro expansion:" (macroexpand (swap x y)) "\n")
)
Macro expansion: (let ((temp x)) (set! x y) (set! y temp))
Of course, you can store away the expansion for later invocation, or just evaluate the expansion directly:
(let ((x 5) (y 8))
(eval (macroexpand (swap x y)))
(print "Swapped:" x y "\n")
)
Swapped: 8 5
self and environment lookups
The self function returns the current environment as an expression. This can then be used as a function to perform lookups in that environment. This enables composite data types with their own functions, as well as modules. The distinction is purely conceptual.
A top-level (self) call will return the root environment as an expression:
> (self)
<env>
> ((self) +)
<function>
> ((self) (+ 1 2))
3
> (((self) +) 1 2)
3
As you can see, when an environment is placed in the first position of a list, it changes which environment the following argument is looked up in.
The argument can either be a symbol, or a list which will be interpreted in the context of the new environment.
Use cases of self include modules, composite data types, polymorphic behavior, and enabling duck-typed interfaces/protocols.
See Modules for more information and an example.
&rest
A sentinel symbol causing the rest of the arguments to be delivered as a single list argument. This enables variadic functions and macros.
quote
The quote function and the ' shorthand returns the argument unevaluated.
> (quote a)
a
> 'a
a
> '(a b 1 2)
(a b 1 2)
quasiquote
The quasiquote function and the ` shorthand returns the argument unevaluated. Unlike quote, however, it allows arguments to be selectively evaluated using unquote and unquote-splicing
; Evaluate one of the list items
> (quasiquote (1 2 (unquote (+ 1 2)) 4))
(1 2 3 4)
; Same thing using shorthand notation
> `(1 2 ,(+ 1 2) 4)
(1 2 3 4)
; Use unquote-splicing to make a larger list of primes:
> (var primes '(2 3 5 7 11 13))
> `(,@primes 17 19 23)
(2 3 5 7 11 13 17 19 23)
Quasi quotation is commonly used to make templates in macros, but it has uses in regular functions as well.
unquote
In the context of a quasiquote, evaluate the argument. The shorthand version is ,
unquote-splicing
In the context of a quasiquote, evaluate the elements of the list and place the result in the enclosing list. The shorthand version is ,@
eval
Evaluates all arguments, leaving the last evaluation as the result. If quote and quasiquote expressions are encountered, these are unquoted before evaluation.
(eval '(+ 1 2))
3
(var expr '(* 2 3))
apply
Evaluates the given function with the given argument list. The last argument must be a list argument. Any preceding arguments are prepended to that list. This means that (apply + 1 '(2 3)) is equivalent to (apply + '(1 2 3)).
> (apply + 5 2 1 '(10 20))
38
> (var list-of-numbers '(1 2 3 4))
> (apply * list-of-numbers)
24
> +
<function>
> (apply #? '(5 2))
7
Using apply is mostly useful when arguments are given as a list and the function at hand expects arguments to be passed individually.
gensym
Generates a unique symbol.
> (gensym)
gensym_1
> (gensym)
gensym_2
if
The if expression evaluates the first argument. If true, then the second argument is evaluated, otherwise the third (optional) argument is evaluated. Each branch can have multiple expressions using constructs such as begin or let.
(if (< x 10) 'Yes 'No)
(var res (if (math.odd? x) 'Odd 'Even))
Here's a list of if expressions from examples/fizzbuzz-if.lisp, none of which have an else branch:
(if (= 0 x) (print "Fizz"))
(if (= 0 y) (print "Buzz"))
(if (and (!= 0 x) (!= 0 y)) (print i))
cond
The cond