Lesson 2.2 · II The language
Language design
What it's about: A language is a collection of decisions. This lesson first shows the whole language on one page and the places where it differs from what you know from other languages. Then it goes through the decisions: what the language can do, why it does it that way and what is deliberately missing. Where the ideas come from is at the end, as a deeper look.
1. The language on one page
// comment /* block comment */
param name = 150 in 40..500 "Description" // slider; also true/false
let x = expr
let (a, b) = p let {w, h} = r // with a pattern
fn f(a, b = 2) = expr where c = …, d = … // default value, helper values
fn f(0) = 1 // several equations …
fn f(n) | n > 0 = n * f(n - 1) // … with a condition (guard)
export expr color "green" // result, colour for the picture and 3MF
let lib = import name // library: a record of its pub names
pub fn g(x) = … // (in a library) visible outside
1.5 "Text" true (x, y) (x, y, z) (1, "a") // (x, y) is (x, y, 0)
[1, 2, 3] [0 .. 10] [0, 0.5 .. 2] a ++ b xs[0]
{w: 3, h} {...r, h: 5} r.w p.x {"road-type": 2} r["road-type"]
[f(x) | x <- xs, y <- ys, condition]
x => x * 2 (a, b) => a + b ((r, z)) => r
(* 2) (2 ^) (+) f(_, 30) f >> g
a |> f(b) is f(a, b) a.f(b) is f(a, b) r.f(x) calls the field f
f(r: 3) // named argument: a colon
if condition then a else b
match v { pattern => a, pattern | condition => b, _ => c }
+ - * / % ^ == != < <= > >= and or not
Characters that occur:
( ) [ ] { } , : . .. ... => <- |> >> | + - * / % ^ ++ == != < <= > >= =,
_ (placeholder), \ (only in text strings:
\", \\, \n, \r,
\t) as well as // and /* */. All
of them are on a US keyboard without any detour.
2. What differs from elsewhere
If you know Python, JavaScript or Haskell, these are the places where you are most likely to trip. Each of them gives a message with a hint, never silently a different result (Lesson 2.3):
- Angles in degrees:
sin(90)is 1,atan2(y, x)gives degrees. - No broadcasting:
[1, 2] * 2is an error; that is whatmapand comprehensions are for (Lesson 2.1). - Strict, not lazy: every value is computed right
away; there are no infinite lists. A guard computes the
wherevalues it needs first. Lesson 4.3 explains why. wherebelongs to an equation, not to a lambda inside it: a lambda's parameter is not visible inwhere.- A comprehension needs a generator:
if c then [x] else []instead of[x | c]. - Lists:
zipneeds lists of equal length. Indices start at 0; there are no negative ones: the last element isxs[len(xs) - 1]. - A name has one value in the whole model; a
letcan only use what stands above it, functions may stand anywhere (section 7). Values never change; you build new ones:{...r, width: 5}. - Named arguments with a colon:
circle(r: 3), notcircle(r = 3). - The pipe binds weaker than arithmetic:
(xs |> len) - 1. - Few text functions:
++,text,split,trim,join,number,lines. No network; files only throughread(Lesson 2.5).
3. Guiding principles
Five rules shape every decision:
- Reading comes before writing. A model is read more often than it is written – including by yourself, three months from now. Better one more word than a cryptic symbol.
- Easy to type. ASCII characters only, all reachable
on a US keyboard without contortions. No
λ, no∈, no→. - Explicit rather than magic. What happens to a list is written down (Lesson 2.1). No rule that applies differently depending on the situation.
- Values never change. There are no variables that get overwritten and no loops that count something up. Everything is an expression that has a value.
- Errors early and understandable. Every message shows the line, the column and the spot – and, where possible, how to get it right.
4. Higher-order functions and closures
A higher-order function takes functions as arguments
or returns one. map, filter, fold
and sort(…, key: …) are such functions. Without them you
would be stuck with loops – and loops need mutable counters, which don't
exist here.
Closures (functions that remember their environment,
Lesson 2.1) are needed for this, otherwise a function passed to
map couldn't see the model's parameters. In many languages
closures have a bad reputation, because they hold on to mutable
variables that later change without anyone noticing. Here nothing
changes – so closures are simply useful.
Three small tools make higher-order functions pleasant, even though there is no currying (Lesson 2.1, section 7 explains why not):
| Tool | Example | means | Borrowed from |
|---|---|---|---|
| Section | (* 2), (2 ^), (+) |
x => x * 2, x => 2 ^ x,
(a, b) => a + b |
Haskell |
| Placeholder | rotate(_, 30) |
x => rotate(x, 30) |
Scala |
| Composition | f >> g |
x => g(f(x)) |
F# |
Together they make small, readable building blocks:
let tilt = rotate(_, 15, axis: (1, 0, 0)) >> move(_, z: 40)
let parts = [tilt(sphere(r)) | r <- [5, 8, 13]]
With the pipe, the placeholder gets a second meaning:
x |> f(a, _) puts x exactly where the
_ is. Without _, x goes first as
usual.
5. Patterns everywhere
Pattern matching (Lesson 2.1) works everywhere a name is introduced:
let (x, y) = p // let
fn area({w, h}) = w * h // function parameter
[r + z | (r, z) <- zip(radii, heights)] // generator
zip(a, b).map((x, y) => x + y) // lambda
f(p) where (x, y) = p // where
Then there is match, for choosing
between cases in the middle of an expression:
fn label(p) = match p {
(0, 0) => "origin",
(x, 0) | x > 0 => "on the axis, to the right",
_ => "somewhere"
}
There is a small design question in this: in
(x, y) | x > y => … the parser could read
y => … as a lambda. Scala has exactly the same problem
with case x if x > y => … and solves it the same way
knotflow does: inside a condition before => there are no
bare lambdas; in parentheses there are.
A second convenience: if a function that needs at least two arguments
receives a single tuple or point, it unpacks it. That is why
zip(a, b).map((x, y) => x + y) works without double
parentheses, with built-in functions too
(zip(a, b).map(max)). The rule is unambiguous, because such
a call would otherwise be an error. Only the parameters without a
default value count. A rule "n parameters, a tuple of n parts" would
unpack a point for fn f(p, size = 1), even though
f((1, 2)) works as it is (Lesson 2.3). Built-in functions
follow the same rule, and a point counts as three-dimensional:
(1, 2) and (1, 2, 0) unpack the same way.
6. Records instead of classes
A record is a value with named fields:
let rim = {height: 8, width: 3}
let wide = {...rim, width: 5} // copy with one field changed
let {height, width} = wide // pattern
rim.height // read a field
{origin, x, y: up, z} // short for {origin: origin, …}
Records bundle what belongs together: a frame (frame_on
returns {origin, x, y, z}), a group of parameters such as
"rim", or several results of a function (voronoi_sphere
returns {sites, vertices, edges, links, cells}). Since
values never change, you "change" a record by making a copy with
....
Scala's case classes have a second half: variants
such as Shape = Circle(r) | Polygon(n, r). They only pay
off once a type checker reports that a case was forgotten. So they are
missing as long as there are no static types.
7. Names and scope
- A name in the model gets a value once. That keeps the node graph (Lesson 2.1) honest.
- Built-in names may be shadowed.
param length = 220is allowed, even though there is a functionlength. Forbidding it would be a design mistake: every new built-in function could then break old models. To make this safe, the built-in functions and the prelude live in an outer environment; the prelude keeps using the reallength, no matter what the model does with the name. - In
where, order doesn't matter, as in Haskell: the important part first, the details below. The language sorts the helper values by their dependencies; if two depend on each other in a cycle, it says so. (An example is the Voronoi lattice: the structural part logically comes before the weaving but stands further down in the text.) - Functions are looked up when called, values right
away. So a function may use a function defined further down
(which is also how functions that call each other work), but a
letmay only use values that are already above it. - A name means the same thing throughout the model.
All functions exist before the first line is computed. If you use a
value that only comes further down, you get "x is defined further down,
in line 12" – and not, silently, the built-in function of the same name.
Otherwise
picould be the number π in line 2 and, from line 5 on, a parameterpi– the same name, two meanings in one model (Lesson 2.3).
8. Errors with a call path
In recursive models it isn't enough to know where an error
happens – you want to know how you got there. So every message
shows the path of calls, with repeated calls from the same place merged.
Here, in the tree-support roof, the branch radius was deliberately
computed wrongly (r - 2 instead of r * 0.68),
so that it turns negative at the third level:
error: cylinder: pipe: r must be > 0
--> tree.kf:29:27
|
29 | fn limb(p, q, l, s, r) = [cylinder(p, q, r), sphere(r * 1.05) |> translate(q)]
| ^^^^^^^^^^^^^^^^^
= in limb, called at tree.kf:24:36
= in crown_at, called at tree.kf:30:6
= in limb, called at tree.kf:24:36
= in crown_at, called at tree.kf:30:6
= in limb, called at tree.kf:24:36
= in crown_at, called at tree.kf:33:6
= in tree, called at tree.kf:40:9
Read from bottom to top: tree → crown_at →
limb → … three times down, until cylinder is
called with a negative radius. If the error is in a prelude function,
the message points to the call in your own model
(sphere: arc: r must be a number, got a text) – after all,
the prelude lines aren't in your file.
9. The prelude: the language written in itself
A good test for a language is whether you can write its own library
in it. So the basic solids sphere, cylinder,
cone, box and torus, the points
on the sphere (fibonacci_sphere,
random_sphere), frames (frame_at,
spin, grid_on), building blocks such as
thicken (a band from a curve), rounded_box,
rounded_extrude, boss, inset and
letters (text as a solid), the conditions for
solve (on_line, touches,
apart, …) and the joints for assemblies
(revolute, slider, ball_joint, …,
Lesson 3.11) are not Rust; they live in
crates/lang/src/prelude.kf:
// cone standing on the origin: radius r1 at the bottom, r2 at the top (0: a tip)
fn cone(r1, 0, h) = revolve(polyline([(0, 0), (r1, 0), (0, h)]))
fn cone(r1, r2, h) = revolve(polyline([(0, 0), (r1, 0), (r2, h), (0, h)]))
// point i of n spread evenly over the unit sphere (Fibonacci lattice)
fn fibonacci_point(i, n) = (s * cos(a), s * sin(a), z)
where z = 1 - (2 * i + 1) / n, s = sqrt(1 - z * z), a = i * 137.50776405003785
kf help lists them with the comment above the function.
Only what has to be fast or belongs to the geometry core stays in Rust:
NURBS, tessellation, offsets, booleans, Voronoi. The same rule holds for
new geometry: first the missing building blocks in Rust, what is put
together from them in the language. More libraries written in the
language live in lib/ and are loaded with
import (Lesson 2.4).
10. Groups of shapes
A list of shapes is a group:
move(group, z: 5) moves all of them. This is not
broadcasting through the back door – the other arguments stay single
values, and there are no combination rules. It is simply a compound
shape, as in any CAD program. Without it, the romanesco in Lesson 3.14
would be hard to write: it moves, turns and scales whole subtrees.
11. What is deliberately missing
| What | Why not |
|---|---|
| automatic processing of lists | ambiguous, second-class citizens (Lesson 2.1) |
| currying | doesn't get along with named and optional arguments; hard to debug without type checking |
| custom operators | other people's models become unreadable |
| mutable variables, loops | comprehensions, fold and recursion are enough; without
mutation the node graph is always correct |
do notation, monads |
see section 12 |
| significant indentation (like Haskell, Python) | free formatting is more robust when copying; where
separates with commas |
units (10mm, 45deg) |
everything is mm and degrees – units would only mean more typing |
| lazy evaluation | hard to predict when what gets computed; brings little for geometry (Lesson 4.3) |
Not there are static types with type inference (Hindley–Milner) – errors before anything runs, and variants along with them.
Because all functions are pure (same input, same result, no side
effects), there are modules instead (import name, Lesson
2.4) and a cache that computes again only what changed (Lesson 4.2).
12. A deeper look: models and monads
Most of the language's ideas come from other languages:
| Idea | Model |
|---|---|
comprehensions, equations with patterns, sections,
where |
Haskell |
placeholder _, a condition in a match
arm |
Scala |
composition >> |
F# |
pipe |> and how strongly it binds |
Elixir |
| equations without static types | Erlang, Elixir |
| angles in degrees | OpenSCAD |
That leaves the question everyone who knows Haskell asks: and what about monads? The honest answer: knotflow doesn't need any – but only because it does their three classic jobs differently.
| Job | Monad in Haskell | here |
|---|---|---|
| several results | list | comprehensions – they are the list monad |
| a computation can fail | Maybe |
errors stop with a clear message; assert and equations
check beforehand |
| hidden state | State |
randomness without state: rand(seed, i) |
The first row is more than an analogy. The comprehension
[f(x, y) | x <- xs, y <- g(x)]
is, in Haskell, just another way of writing
xs >>= \x -> g x >>= \y -> return (f x y)
– and that is the list monad. So knotflow already has the most useful
monad, just without the word.
The third row is a neat trick. Normally a random number generator has
a state that changes with every number, and in a language without
mutation you would have to pass that state laboriously through every
function (which is exactly what the State monad does).
knotflow does what modern graphics cards do: the random number is a pure
function of the seed and an index – rand(7, 0),
rand(7, 1), … –, with a good mixer inside (SplitMix64).
Same call, same number, and every number is independent of all the
others. That makes models reproducible: the Voronoi sphere looks the
same tomorrow as it does today.
Exercises
- Write
fn total(xs)withfoldand a section, in one line. - Use
>>to build a functionplace_on_ring(r)that moves a shape outwards byrand then turns it by 45°, and use it to set eight spheres in a circle. - Give the star a record as its parameter:
fn star({points, outer, inner}). - Something to think about: why would
rand()without arguments be impossible in this language?