Whisker Language Reference

A quick reference of Whisker’s words, operators, types and syntax. The specification is spec.md; the builtins, the tests and the Go packages are in stdlib.md.

Reserved Words

These eleven words cannot be used as names.

WordMeaningExample
letBind a namelet x = 42
fnFunction, method or lambdafn add(a int, b int) int { a + b }
returnReturn a valuereturn x + 1
ifConditional branchif x > 0 { ... }
elseElse branch} else { ... }
forLoop (condition, range, list, dict, or forever)for i in 1..10 { ... }
breakLeave the loopif found { break }
continueOn to the next turnif empty { continue }
matchBranch on a value (pattern match)match v { 0 => "zero", _ => "other" }
typeDeclare a typetype Point struct { x int, y int }
importImport a Go packageimport go "net/http"

Contextual Keywords

Ordinary names everywhere except where this table says.

WordMeaning thereExample
structAfter type Name: a struct or sum typetype User struct { name string }
interfaceAfter type Name: an interfacetype Showable interface { show() string }
pureBefore fn: a pure functionpure fn square(x int) int { x * x }
inIn for: the loop’s subjectfor x in xs { ... }
goAfter import: a Go packageimport go "strings"

Predeclared Names

Bound before the program starts, and bindable again.

NameMeaning
true, falseBooleans
nilNo value
print, fail, map, filter, reduce, …Built-in functions
int, uint8, string, list, …Types

Types

TypeMeaningExample
int64-bit signed integer, the defaultlet x int = 42
int8 int16 int32 int64Signed integerslet t int8 = -5
uint uint8 uint16 uint32 uint64Unsigned integers (uint is 64-bit)let b uint8 = 255
byteSame type as uint8let c byte = 65
runeSame type as int32let r rune = 97
float, float6464-bit floating pointlet pi float = 3.14
float3232-bit floating pointlet f float32 = 1.5
stringUTF-8 stringlet name string = "Hoge"
boolBooleanlet ok bool = true
errorError valuefn(err error) { ... }
listList of valueslet nums list = [1, 2, 3]
dictMap from string keys to valueslet ages dict = {"hoge": 3}
fn(T, ...) RFunctionlet f fn(int) int = fn(x) { x * 2 }

Annotations are optional on bindings and lambda parameters. A named function’s parameters need a type, and so does its result when it returns a value. fn add(a, b int) gives both parameters int. A function with a result type whose body is one expression returns it without return.

Integers

let x uint8 = 255
print(x + 1)            // 0 — overflow wraps around
let big = 300
print(uint8(big))       // 44 — a conversion keeps the low bits
let z uint = 0
print(recover(1 / z, 0)) // 0 — division by zero can be caught

Two different integer types never meet in one operation: convert one of them. A literal that does not fit its type is a compile error.

Conversions

A conversion is the target type’s name, called with the value:

print(string(42) + "!")   // 42!
print(int("42") + 1)      // 43
print(float(2))           // 2
print(int(3.9))           // 3
print(recover(int("cat"), 0)) // 0 — text that is not a number is an error

Operators

OperatorMeaning
+ - * / %Arithmetic (+ also joins strings)
== != < > <= >=Comparison
&& || !Logic
|>Pipe: x |> f(y) is f(x, y)
..Inclusive range in for and in patterns
=>Match arm
.Member access

Precedence, loosest first: ||, &&, == !=, < > <= >=, |>, + -, * / %, unary ! -, then calls, indexes and members.

Comments

// A line comment
/* A block comment,
   which may span lines */

Syntax Examples

Bindings

let x = 42
let name string = "Hoge"
y = 3                   // without let: the same as let y = 3

A binding cannot be rebound.

Functions and Lambdas

fn greet(name string) string {
  return "Hello, " + name + "!"
}
fn square(x int) int { x * x }            // one expression: return may be left out

let double = fn(x) { x * 2 }
let add = fn(a int, b int) { a + b }
let add5 = add(5)                         // partial application
print(add5(3), double(4))                 // 8 8

Conditionals

let n = 9
if n % 15 == 0 {
  print("FizzBuzz")
} else if n % 3 == 0 {
  print("Fizz")           // printed: 9 is a multiple of 3
} else {
  print(n)
}

Loops

for i in 5 { print(i) }                  // 0, 1, 2, 3, 4
for i in 1..5 { print(i) }               // 1 to 5
for w in ["a", "b"] { print(w) }         // each element
for i, w in ["a", "b"] { print(i, w) }   // index and element
for k, v in {"a": 1} { print(k, v) }     // key and value
let ready = true
for ready { break }                      // while ready holds
for { break }                            // until break

Pattern Matching

let size = fn(n) {
  match n {
    0 => "zero",
    1..9 => "small",
    _ if n < 0 => "negative",
    _ => "large"
  }
}
print(size(5), size(-3), size(42))   // small negative large

Error Handling

recover(x, fallback) is x, or fallback when x fails. A function as the fallback receives the error. It reads well at the end of a pipe too: x |> recover(fallback).

fn divide(a int, b int) int {
  if b == 0 {
    fail("division by zero")
  }
  return a / b
}

let safe = recover(divide(10, 0), 0)                        // 0
let handled = recover(divide(10, 0), fn(err error) { 42 })  // 42
let piped = divide(10, 0) |> recover(-1)                    // -1
let result = try(fn() { divide(10, 0) })
if is_error(result) { print("caught:", result) }

Lists and the Pipe

let nums = [1, 2, 3, 4]
let total = nums
  |> filter(fn(x) { x % 2 == 0 })
  |> map(fn(x) { x * x })
  |> reduce(0, fn(acc, x) { acc + x })
print(total)   // 20

Types

type Nickname = string            // alias: the same type as string
type UserId int                   // new type: distinct from int
let id = UserId(42)
print(id.value)                   // 42

type Point struct {
  x int
  y int
}
let p = Point(3, 4)
print(p.x)                        // 3

type Shape struct {               // a sum type: one of the variants
  Circle(radius float)
  Rect(w float, h float)
  Dot
}

type Showable interface {
  show() string
}

Methods

type User struct { name string, age int }

fn (u User) show() string { u.name + " (age " + string(u.age) + ")" }

print(User("Hoge", 3).show())

Imports

import go "strings"               // a Go package
import go "net/http"              // reached as http
import go yml "gopkg.in/yaml.v3"  // renamed

Contracts

A named function or method may say what it needs (requires) and what it promises (ensures) between its signature and its body. Inside an ensures, result is the value returned. Every clause is checked each time the function runs, and a violation is an error that recover catches:

pure fn abs(x int) int
  requires x > -9223372036854775807
  ensures result >= 0
{
  if x < 0 { return -x }
  return x
}

whisker test tries the contract of each pure fn in the file under test on generated inputs, and whisker verify proves it with z3. whisker export lean writes the pure functions as Lean definitions and each ensures as a theorem with sorry for its proof, to be proved there (see the specification). A function that is not pure is reported on standard error as skipped: f (not pure), and a method as skipped: T.m (a method), along with any pure fn that cannot be written, in the order they appear in the file; none of them changes the exit status.

Tests

A file named foo_test.wsk is run by whisker test, with foo.wsk read alongside it. Functions named test_* are tests; catwalk_* functions compare what they print with the // Output: comment at their end. Functions named prop_* are properties: whisker test runs each on 100 generated inputs (-prop-count <n>; -seed <n> fixes the inputs) and shrinks a failing input. Their parameters need type annotations: int, float, bool, string or list.

fn test_add() {
  assert_eq(add(1, 2), 3)
}

fn catwalk_hello() {
  print("Hello!")
  // Output:
  // Hello!
}

Command Line

CommandMeaning
whisker run <file.wsk> [args...]Run a program
whisker build <file.wsk> [-o name]Build a binary
whisker transpile <file.wsk>Show the generated Go
whisker test [files...]Run _test.wsk files
whisker fmt [-w] <files...>Format source
whisker lint [files/patterns...]Static analysis
whisker verify [-timeout d] [files/patterns...]Prove the contracts of pure fns with z3
whisker export lean <file> [-o out.lean]Write pure fns and their contracts as Lean 4
whisker versionVersion
whisker <file.wsk>Same as whisker run