GovLisp is the source language of GOVERNMENT. This guide shows the language in order, from numbers to modules and IO. Each example is a program that you can run. The specification is the full and exact reference.
Put this text in a file named hello.gov.lisp:
(println "hello, world")
Run it with govlisp:
govlisp hello.gov.lisp
It prints hello, world. Without a file, govlisp starts a REPL, where you can type one form at a time.
govlisp evaluates each top-level form in order. It prints the value of each form that is not a definition. In this guide, ; => shows the value that a form prints:
(+ 1 2) ; => 3
A comment starts with ; and continues to the end of the line.
; This comment is about the next form. (* 6 7) ; => 42
A comment has no effect on the program.
There are two kinds of number: 64-bit integers and 64-bit floats. A float always has a digit on each side of its decimal point.
42 ; => 42 -7 ; => -7 3.25 ; => 3.25 1.0e3 ; => 1000.0
A call is a list: the function first, then the arguments.
(+ 1 2 3) ; => 6 (- 10 4) ; => 6 (* 2 3 4) ; => 24 (/ 7 2) ; => 3 (/ 7.0 2.0) ; => 3.5 (% 7 3) ; => 1 (max 3 9 4) ; => 9
Integer division truncates toward zero. Integers and floats do not mix, except that an integer literal can be a float:
(+ 1 2.5) ; => 3.5 (float 3) ; => 3.0 (int 2.9) ; => 2
Overflow and division by zero stop the program with E-ARITH.
The booleans are T and F. They are the only values that a test accepts. 0, "" and () are not true or false.
(< 1 2) ; => T (== "a" "a") ; => T (<> 1 2) ; => T (not T) ; => F (and T F) ; => F (or F T) ; => T
== compares any two values of one type, except functions, actions and fds.
if always has a test, a "then" branch and an "else" branch:
(if (> 3 2) "yes" "no") ; => "yes"
cond tests each clause in order. Its last clause must have the test T, so a cond always has a value:
(def n 0)
(cond ((< n 0) "negative")
((== n 0) "zero")
(T "positive")) ; => "zero"
and stops at the first F, and or stops at the first T.
A string is a sequence of Unicode characters between " characters.
"hello" ; => "hello"
($cat "sun" "flow" "er") ; => "sunflower"
($len "héllo") ; => 5
($spl "a,b,c" ",") ; => ("a" "b" "c")
($join '("a" "b") "-") ; => "a-b"
($trim " hi ") ; => "hi"
$ changes any value into a string, and $f formats values:
($ 42) ; => "42" ($f "%s has %d votes" "ada" 12) ; => "ada has 12 votes" ($f "%.2f" 3.14159) ; => "3.14" ($f "[%5s]" "ab") ; => "[ ab]"
A symbol is a name. A ' stops evaluation, so 'red is the symbol red:
'red ; => red (sym? 'red) ; => T (== 'a 'a) ; => T
A byte string is a sequence of bytes, written #"...". \xHH writes any byte. # changes a string into its UTF-8 bytes, and $# changes bytes into a string:
#"GET /\x0d\x0a" ; => #"GET /\x0d\x0a" (# "hi") ; => #"hi" (#len (# "é")) ; => 2
A quoted list is data. list makes a list from values. All the elements of a list have one type.
'(1 2 3) ; => (1 2 3) (list 1 (+ 1 1) 3) ; => (1 2 3) (cons 0 '(1 2)) ; => (0 1 2) (head '(1 2 3)) ; => 1 (tail '(1 2 3)) ; => (2 3) (len '(a b c)) ; => 3 (cat '(1 2) '(3)) ; => (1 2 3) (rev '(1 2 3)) ; => (3 2 1) (range 5) ; => (0 1 2 3 4) (has? 2 '(1 2 3)) ; => T (nil? ()) ; => T
() is the empty list. head and tail of () stop the program, so test with nil? first, or use a match (see Pattern matching).
def binds a name to a value. A name cannot change after its definition.
(def rate 7) (* rate 3) ; => 21
A second def of the same name in one scope is an error. Each value in GovLisp is immutable: no operation changes a value. Operations make new values.
let binds names for one expression. Each step can use the names before it:
(let (= x 2)
(= y (* x 10))
(+ x y)) ; => 22
Each name that a let binds must be used. An unused name is an error, and so is a name that no scope defines.
fn makes a function. def with a list makes a named function:
(def square (fn (n) (* n n))) (square 12) ; => 144 (def (add a b) (+ a b)) (add 2 3) ; => 5
A function body can start with definitions. Then come one or more expressions. The function returns the value of the last expression.
(def (hyp a b) (def (sq x) (* x x)) (+ (sq a) (sq b))) (hyp 3 4) ; => 25
Functions are values. You can pass them, return them and keep them in lists:
(def (twice f x) (f (f x))) (twice square 3) ; => 81 (def (adder n) (fn (x) (+ x n))) ((adder 10) 5) ; => 15
A function can call itself. A call in the last position of a function does not use more stack, so a loop is a recursion in that position:
(def (sum-to n acc) (if (== n 0) acc (sum-to (- n 1) (+ acc n)))) (sum-to 100000 0) ; => 5000050000
A recursion that is not in a last position can nest at most 100000 deep. A deeper recursion stops the program with E-DEPTH.
_ in a call makes a function with one parameter for each _, in order:
(map (* 2 _) '(1 2 3)) ; => (2 4 6) (sort (> _ _) '(3 1 2)) ; => (3 2 1)
A _ belongs to the list that contains it. For a _ deeper in an expression, wrap the expression in (fn ...) with one operand:
(map (fn (+ 1 (* 2 _))) '(1 2 3)) ; => (3 5 7)
map, filter, fold and sort take a function and a list:
(map square '(1 2 3)) ; => (1 4 9) (filter (> _ 1) '(1 2 3)) ; => (2 3) (fold + 0 '(1 2 3 4)) ; => 10 (fold (fn (acc x) (cons x acc)) () '(1 2 3)) ; => (3 2 1) (sort < '(3 1 2)) ; => (1 2 3) (fmap (fn (x) (list x x)) '(1 2)) ; => (1 1 2 2)
fold calls the function with the value so far and the next element, from left to right.
An operation that can fail on valid input returns a result. A success is (Ok value). An error is (Err message).
($int "42") ; => [Ok 42] ($int "4x2") ; => [Err "not an integer: \"4x2\""] (@ '(a b c) 1) ; => [Ok b] (@ '(a b c) 5) ; => [Err "index 5 is past the end of a list of length 3"]
A result is not a number, so (+ 1 ($int "2")) is a type error. There are four ways to get the value:
(?! ($int "42")) ; => 42 (?or ($int "x") 0) ; => 0
?! stops the program with E-PANIC if the result is an error. ?or returns a default instead.
In a let, a ?= step binds the value of a success. At an error, the let stops and returns the error:
(def (add-strings a b)
(let (?= x ($int a))
(?= y ($int b))
(Ok (+ x y))))
(add-strings "40" "2") ; => [Ok 42]
(add-strings "40" "x") ; => [Err "not an integer: \"x\""]
The fourth way is match, in the next section.
match compares a value with each pattern in order, and evaluates the body of the first clause that matches. A pattern can bind names to parts of the value.
(def (describe r)
(match r
((Ok 0) "zero")
((Ok n) ($f "the number %d" n))
((Err e) ($cat "failed: " e))))
(describe ($int "7")) ; => "the number 7"
(describe ($int "x")) ; => "failed: not an integer: \"x\""
List patterns take lists apart. (x . rest) matches a list with a head x and a tail rest:
(def (total xs)
(match xs
(() 0)
((x . rest) (+ x (total rest)))))
(total '(1 2 3)) ; => 6
(def (pair-up xs)
(match xs
((list a b) ($f "%s and %s" a b))
(_ "not two")))
(pair-up '("salt" "pepper")) ; => "salt and pepper"
_ matches any value. A match must have a clause for each possible value. If it does not, the program does not run:
(def (sign n) (match n (0 "zero"))) ; E-TYPE: match on a number needs a last clause for any value, as (_ ...)
GovLisp checks the type of each expression before the program runs. You do not need to write types. The type check finds them from the code:
(def (second xs) (head (tail xs))) ; a function of a (List 'a) that returns an 'a
(second '(1 2)) ; => 2
(second '("a" "b")) ; => "b"
'a is a type variable: any type. A program with a type error does not run:
(+ 1 "a") ; E-TYPE: + needs a number, and "a" is a String
typ declares a type. The declaration documents the code, and the type check makes sure that the code agrees:
(typ parse-age (-> String (Result Int String))) (def (parse-age s) ($int s)) (parse-age "30") ; => [Ok 30]
(-> String (Result Int String)) is the type of a function of a String that returns a (Result Int String). The other types are Int, Float, String, Symbol, Bool, Bytes, Fd, (List t) and (Action t), and the types that a program defines.
defrec defines a record type. Each field has a name and a default:
(defrec person (name "") (age 0)) (person "ada" 36) ; => [person (name "ada") (age 36)] (person "bob") ; => [person (name "bob") (age 0)] (person (= age 20)) ; => [person (name "") (age 20)]
A record of a record type is a typed record. A field path reads a field:
(def ada (person "ada" 36)) ada.name ; => "ada" (morph ada 'age 37) ; => [person (name "ada") (age 37)]
morph returns a changed copy. ada does not change.
A field can have a type and no default. Then each record must have a value for it:
(defrec point (x Int _) (y Int _)) (point 3 4) ; => [point (x 3) (y 4)]
A record type can have type parameters:
(defrec (box 'a) (value 'a _)) (box 5) ; => [box (value 5)] (box "five") ; => [box (value "five")]
A record pattern in a match checks the record type, and can match the fields:
(def (where p)
(match p
((point 0 0) "origin")
((point (= y 0)) "on the x axis")
(_ "elsewhere")))
(where (point 5 0)) ; => "on the x axis"
rec makes an untyped record: named fields without a record type.
(def mark (rec 'name "mark" 'role "mayor")) mark.role ; => "mayor" (morph mark 'age 50) ; => [(name "mark") (role "mayor") (age 50)] (del mark 'role) ; => [(name "mark")]
morph can add a field to an untyped record, and del can remove one.
A record type whose fields are all _ has fields without names. Its records are named tuples. Only a pattern reads their fields:
(defrec span (_ Int) (_ Int)) (def s (span 3 7)) s ; => [span 3 7] (match s ((span lo hi) (- hi lo))) ; => 4
Ok and Err are named tuples.
defsum defines a sum type: a type whose values are the records of a set of record types, its members.
(defsum Shape
(circle (r 1.0))
(rect (w 1.0) (h 1.0)))
(typ area (-> Shape Float))
(def (area s)
(match s
((circle r) (* 3.0 r r))
((rect w h) (* w h))))
(area (circle 2.0)) ; => 12.0
(map area (list (circle) (rect 2.0 3.0))) ; => (3.0 6.0)
The match has one clause for each member, so it needs no _ clause.
A member can have no fields. Such a sum type is an enumeration:
(defsum Color (Red) (Yellow) (Blue)) (def (warm? c) (match c ((Red) T) ((Yellow) T) ((Blue) F))) (warm? (Yellow)) ; => T
is? tests the record type of a value. After the test, the code can read the fields of that member:
(def (radius s) (if (is? circle s) s.r 0.0)) (radius (circle 5.0)) ; => 5.0
A sum type can have type parameters, and its members can refer to the sum type:
(defsum (Tree 'k)
(Leaf)
(Node (key 'k _) (left (Tree 'k) (Leaf)) (right (Tree 'k) (Leaf))))
(typ insert (-> (Tree Int) Int (Tree Int)))
(def (insert t k)
(match t
((Leaf) (Node k))
((Node key left right)
(cond ((< k key) (Node key (insert left k) right))
((> k key) (Node key left (insert right k)))
(T t)))))
(typ keys (-> (Tree Int) (List Int)))
(def (keys t)
(match t
((Leaf) ())
((Node key left right) (cat (keys left) (list key) (keys right)))))
(keys (fold insert (Leaf) '(5 2 8 1))) ; => (1 2 5 8)
deftyp defines an interface: a set of fields with types. Each typed record, untyped record and module that has those fields is a value of the interface.
(deftyp Named (name String)) (typ greet (-> Named String)) (def (greet x) ($cat "hello, " x.name)) (defrec dog (name "rex") (legs 4)) (greet (dog)) ; => "hello, rex" (greet (person "ada" 36)) ; => "hello, ada" (greet (rec 'name "mark")) ; => "hello, mark"
A record type belongs to at most one sum type, but it can be a value of many interfaces.
A list of records of different record types needs a typ with an interface:
(typ pets (List Named))
(def pets (list (dog) (person "ada" 36)))
(map greet pets) ; => ("hello, rex" "hello, ada")
is? and match narrow a value of an interface to a record type:
(typ legs (-> Named Int)) (def (legs x) (if (is? dog x) x.legs 2)) (map legs pets) ; => (4 2)
module groups definitions. The names that start with an uppercase letter are the fields of the module. The other names are private to it.
(module geo (def (sq x) (* x x)) (def (Dist a b) (+ (sq (- a.x b.x)) (sq (- a.y b.y)))) (defrec Pt (x 0) (y 0))) (geo.Dist (geo.Pt 0 0) (geo.Pt 3 4)) ; => 25
A module can come from a file: (module geo "geo.gov.lisp"). The file's definitions are the module. Its other top-level forms run only when the file runs as a program.
Evaluation never does IO. An IO function returns an action, which describes the IO. govlisp runs the action when it is the value of a top-level form:
(println "hi")
This prints hi. An action is a value, so you can keep it and run it later. Each time that an action runs, it does its IO again.
A let with <- steps runs actions in order. (<- x a) runs the action a and binds x to its value. The body must return an action, which runs last:
(let (<- (println "one"))
(<- (println "two"))
(pure ()))
pure makes an action that does no IO and returns its argument.
IO can fail, so most actions return results. ?<- is to <- as ?= is to =: at an error, the let stops and returns the error.
(def (copy-file from to)
(let (?<- in (open from 'read))
(?<- bytes (read in 65536))
(?<- (close in))
(?<- out (open to 'write))
(<- written (write out bytes))
(?<- (close out))
(pure written)))
(then (copy-file "/etc/hostname" "/tmp/hostname.copy")
(fn (r) (println r)))
then runs an action, then calls a function with its value. The function returns the next action.
An fd stays open until a close runs, or the program ends. In copy-file, the write uses <-, not ?<-. Thus (close out) runs also if the write fails, and copy-file returns the result of the write.
Some other actions:
(print$f "%s has %d votes\n" "grace" 16) (when (> 2 1) (println "two is more"))
connect, listen and accept work with TCP and Unix sockets in the same way. The specification describes each IO function, and gives the language in full.