Chapter 3
The language in brief
A knotflow model is a sequence of statements. Each one begins with a keyword:
| Statement | what for |
|---|---|
param |
a number (or yes/no) that can be changed from outside: a slider |
let |
a value with a name |
fn |
a function |
export |
what belongs to the model and goes into the file |
report |
messages for the person using the model |
Comments may stand in between: // to
the end of the line, /* … */ also over several lines
(nesting allowed). knotflow skips them.
This chapter goes through the language once, as far as you need it for modelling. If you already program, the language tour has a translation table from JavaScript and Haskell; every rule in detail is in the grammar.
Looking at values
Many examples in this chapter only compute values and export nothing. You still see the values:
- in the browser on the right under Values,
- on the command line with
kf render file.kf(without-o): it lists everyletvalue and says "the model exports nothing" at the end. Here that is not a mistake in the model, even thoughkfends with exit code 1.
Values
let count = 6 // number
let wall = 1.6 // decimals with a point
let tiny = 2.5e-3 // 0.0025
let p = (10, 20) // point in the plane
let q = (1, 2, 3) // point in space
let name = "cup" // text
let sizes = [10, 20, 30] // list
let cup = {height: 90, radius: 40} // record: values with names
let tall = cup.height > 50 // truth value: true or false
- Numbers are always floating point;
7and7.0are the same. A calculation that gives no number (1 / 0) is an error, not "infinity". - Points calculate like vectors:
(10, 20) + (1, 2, 3)is(11, 22, 3),2 * qis(2, 4, 6). A point in the plane has z = 0. Read the coordinates withp.x,p.y,p.z. - Texts stand in double quotes.
++joins texts,text(x)turns a value into a text:name ++ " " ++ text(cup.height) ++ " mm". A quote inside a text is written\", a backslash\\, a line break\n, a tab\t. - Lists count from 0:
sizes[0]is 10,len(sizes)is 3,sizes ++ [40]is a new, longer list. The last element issizes[len(sizes) - 1]; there are no negative indices. - Records hold values that belong together:
cup.height. A copy with one field changed:{...cup, radius: 45}. - Truth values are combined with
and,or,not.
Curves, surfaces and solids are values too. You can put them in lists, keep them in records and pass them to functions just like numbers.
Values never change. {...cup, radius: 45} does not
change cup; it builds a new record.
Sequences of numbers
let steps = [0 .. 4] // [0, 1, 2, 3, 4] – with the end
let py = range(4) // [0, 1, 2, 3] – without the end, as in Python
let even = range(0, 10, step: 2) // [0, 2, 4, 6, 8]
let lin = linspace(0, 1, 5) // [0, 0.25, 0.5, 0.75, 1] – 5 values, both ends included
linspace is the one you need most when modelling: "eight
sections from the bottom to the top".
Taking values apart
let cup = {height: 90, radius: 40}
let {height, radius} = cup // height = 90, radius = 40
let (x, y) = (10, 20) // x = 10, y = 20
Names: let
let name = expression gives a value a name. Two
rules:
- A name has exactly one value in the whole model. A
second
let xis an error. - A
letonly sees what stands above it. Functions, on the other hand, may stand anywhere, even below the line that uses them.
Built-in names such as pi or circle may be
hidden by your own let or fn; yours then holds
in the whole model.
Sliders: param
param height = 120 in 40..300 "height [mm]"
param wall = 1.6 in 0.8..5 "wall thickness [mm]"
param handle = true "with a handle"
export cylinder((0, 0, 0), (0, 0, height), 30)
A param has a name, a default value, a range for the
slider and a description. A param with true or
false becomes a checkbox. On the command line, set it with
-D height=200.
Tip: make every size you may want to change later a
param right away, with a range in which the model still
makes sense.
Functions: fn
fn area(r) = pi * r ^ 2
fn ring(r, wall = 2) = area(r) - area(r - wall)
let a = ring(10) // wall is 2
let b = ring(10, wall: 3) // named
let c = ring(r: 10, wall: 1) // all named
fn name(parameters) = expression: the expression on the right is the result. There is noreturn.wall = 2is a default value: whoever leaves outwallgets 2.- In a call, arguments can be named, with a colon:
ring(10, wall: 3). With the built-in functions this often reads better:move(shape, z: 10). ^is the power:r ^ 2.
Short functions without a name are called lambdas:
x => x * 2, (a, b) => a + b. You hand
them to other functions, see map below.
Helper values: where
fn volume(r, h) = base * h
where base = pi * r ^ 2
export cylinder((0, 0, 0), (0, 0, h), r) color "sage"
where r = 20, h = 2 * r
After where come helper values that hold only in this
one equation, separated by commas, in any order. export and
let can have a where too.
Choosing: if and
match
fn size(n) = if n < 10 then "small" else "large"
let s = size(4)
An if always has both branches; it is
an expression with a value, like ?: in other languages.
match compares a value with patterns,
one after another; the first branch that fits holds:
fn describe(xs) = match xs {
[] => "empty",
[x] => "only " ++ text(x),
[x, ...rest] | x > 100 => "starts large",
[x, ...rest] => text(x) ++ " and " ++ text(len(rest)) ++ " more",
}
let d = describe([4, 5, 6]) // "4 and 2 more"
[]fits the empty list,[x]a list with exactly one element.[x, ...rest]takes the first element and the rest.| x > 100is a guard: the branch holds only if it is true._fits anything.
Equations with guards
A function may consist of several equations standing directly one below the other. The first whose patterns and guard fit holds:
fn sign(0) = 0
fn sign(x) | x < 0 = -1
fn sign(_) = 1
let s = [sign(x) | x <- [-3, 0, 5]] // [-1, 0, 1]
Each equation has at most one guard and its own where.
If the equations do not stand directly one below the other, knotflow
says "f is already defined".
Records can be taken apart in the parameters too:
fn area({w, h}) = w * h.
Building lists: comprehensions
A list comprehension builds a list from another one, the way it is written in mathematics: "x² for all x from 1 to 5".
let squares = [x ^ 2 | x <- [1 .. 5]] // [1, 4, 9, 16, 25]
let odd = [x | x <- [1 .. 9], x % 2 == 1] // only those for which the condition holds
let pairs = [(x, y) | x <- [1, 2], y <- [10, 20]] // all pairs
let sums = [a + b | (a, b) <- pairs] // a pattern left of the arrow
export [sphere(3) |> move(x: 10 * i) | i <- range(5)] // five balls
Left of the | stands what goes into the new list; on the
right the generators (x <- list) and
conditions. Several generators give all combinations.
In knotflow, comprehensions take the place of the for
loop: every row of equal parts, every set of sections for
loft, every row of holes is one.
map, filter,
fold
let tens = map([1, 2, 3], x => x * 10) // [10, 20, 30]
let big = filter([4, 12, 7, 30], x => x > 10) // [12, 30]
let total = fold([1, 2, 3, 4], 0, (a, b) => a + b) // 10
let same = [1, 2, 3].map(x => x * 10) // written with a dot
map(list, f)applies f to every element.filter(list, f)keeps the elements for which f givestrue.fold(list, start, f)combines all elements into one value: firstf(start, first), thenf(that, second)and so on.
When modelling, fold is useful for joining many solids
one after another: fold(drills, plate, difference) drills
every hole of the list into the plate (chapter 7).
xs.map(f) is the same as map(xs, f): the
value before the dot becomes the first argument.
More list functions: len, sum,
reverse, sort, zip,
product, enumerate, take,
drop, flatten, minimum,
maximum; kf help explains them all, chapter 4
shows sort and buckets in more detail.
Repeating: iterate
and history
Some things come about step by step: a value to which the same rule is applied again and again. There are two functions for this:
fn step(p) = {n: p.n + 1, x: p.x * 1.5}
let grown = iterate({n: 0, x: 2}, 5, step) // {n: 5, x: 15.1875}
let sizes = history(64, 4, x => x / 2) // [64, 32, 16, 8, 4]
iterate(start, n, f)applies f n times and gives the end:f(f(…f(start))).history(start, n, f)gives all n + 1 states as a list, the start included. That is handy when every step is to become a shape of its own, such as the rings of a tower that get smaller towards the top.
The state may be a record; then a step carries several values on. An
L-system that lets plants grow shows this in the example
tour_2_lsystem.
Short forms: sections,
placeholders, >>
knotflow has no currying (a function always gets its arguments all at once). For the frequent small lambdas there are short forms:
let halves = map([2, 4, 6], (/ 2)) // section: x => x / 2
let total = fold([1, 2, 3], 0, (+)) // (a, b) => a + b
let capped = map([-5, 3, 80], clamp(_, 0, 50)) // placeholder: x => clamp(x, 0, 50)
let both = (x => x * 2) >> clamp(_, 0, 50) // first double, then clamp
let e = both(30) // 50
- Section: an operator in parentheses, with or
without one side:
(* 2),(2 ^),(+). - A placeholder
_as an argument turns a call into a function of the missing argument. - Composition
f >> gis "first f, then g".
Pipes: |>
let pipe = [1 .. 10] |> filter(x => x % 2 == 0) |> map(x => x * x) |> sum // 220
export box(20, 10, 4) |> rotate(30) |> move(z: 2)
a |> f(b) is f(a, b): the value on the
left becomes the first argument. This way a chain of steps reads from
left to right, instead of move(rotate(box(…), 30), z: 2)
from the inside out. For shapes it is the usual way of writing.
Careful: |> binds more weakly than arithmetic.
xs |> len - 1 is xs |> (len - 1); what
is meant is (xs |> len) - 1.
Recursion and limits
A function may call itself:
fn gcd(a, 0) = a
fn gcd(a, b) = gcd(b, a % b)
fn count_up(0, acc) = acc
fn count_up(n, acc) = count_up(n - 1, acc + n)
let g = gcd(12, 18) // 6
let million = count_up(1000000, 0) // a million calls, no problem
If the call is the last thing in a branch (in the
body, in an if branch, in a match branch, also
through |>), it is a tail call: it
needs no stack and may go on for up to 5 million calls in a row (but not
after and/or or in a composition
f >> g). If the function still computes with the
result, like 1 + f(n - 1), it stops after 1000 nested calls
(in the browser after 250; a built-in that calls back, like
map, counts as a call too), with the message "too many
nested calls". The remedy: pass the intermediate result along as an
extra parameter, like acc above – or use fold,
iterate or history right away.
More limits, so that no model brings the computer to a halt: at most 10 million calls per run, lists up to 10 million elements, sizes up to 10⁹ mm.
export and colours
export torus(20, 3) color "terracotta"
export [sphere(4) |> move(x: x, z: 10) | x <- [-15, 0, 15]] color "plum"
export box(60, 20, 2) |> move(z: -4) color (0.9, 0.8, 0.2)
- Every
exportis a part of the model. A list of shapes is a group: one part made of several pieces. colorafter the value gives the part a colour:terracotta,sage,blue,ochre,plum,teal,green,white,gray,glassor(r, g, b)with values from 0 to 1. Withoutcolor, everyexportgets a colour of its own.(r, g, b, a)makes a part see-through:agoes from 0 (invisible) to 1 (opaque, the same as leaving it out). Handy for looking into a model:export sleeve color (0.6, 0.75, 0.8, 0.3)shows the bolt inside it.- The 3MF file keeps the parts and colours, the STL file does not.
Checking: assert
param radius = 30 in 10..80 "radius [mm]"
param wall = 2 in 0.8..20 "wall thickness [mm]"
let ok = assert(wall < radius / 2, "the wall must be thinner than half the radius")
export revolve(polyline([(radius - wall, 0), (radius, 0), (radius, 40), (radius - wall, 40)], closed: true))
assert(condition, text) stops with the text if the
condition is false. That way the model says itself which combinations of
parameters do not work, instead of delivering a broken shape.
Messages: report
Sometimes the model should go on computing, but say what it changed on the way:
param height = 60 in 20..200 "height [mm]"
param wall = 1 in 0.4..5 "wall thickness [mm]"
let w = max(wall, 1.2)
report if w == wall then [] else [{name: "wall", given: wall, used: w}]
export revolve(polyline([(30 - w, 0), (30, 0), (30, height), (30 - w, height)], closed: true))
report takes a text, a record or a list of them;
[] reports nothing. The messages appear next to the
warnings: in the browser above them (a click shows the line), with
kf render under reports:, a record as
name: wall, given: 1, used: 1.2. Like export,
report stands only at the top level: a function cannot
report anything or read the messages, it stays a function of its
arguments. Anywhere else report is an ordinary name.
Libraries: import and
pub
What you need in several models goes into a file of its own, a
library. It contains only fn and
let; what others should see gets pub in
front:
// parts.kf
pub fn peg(r, h) = cylinder((0, 0, 0), (0, 0, h), r)
pub let standard = 4
fn helper(x) = x * 2 // private: visible only in parts.kf
// model.kf, in the same folder
let parts = import parts // a record with peg and standard
let {peg} = import parts // or taken apart right away
export [parts.peg(parts.standard, 20), peg(3, 10) |> move(x: 15)]
import name looks for name.kf next to the
model, then in the standard library. In the browser, +
in the file bar creates a library in the project; the large examples
(differential, golden_gate, v12)
bring their libraries along. More in lesson 2.4, on the browser in
lesson 4.1.
Prelude and standard library
Some of the built-in functions are written in knotflow itself, in the
prelude. It is always there, without
import: box, cylinder,
sphere, cone, torus,
rectangle, rounded_rectangle,
rounded_box, thicken, inset,
between, boss, grid_on,
sized, spin and the conditions for
constructing (chapter 9). For the model it makes no difference:
kf help lists them with the other functions. A name of your
own may hide a built-in one; a fn box(…) in the model then
counts instead of the built-in.
The standard library is fetched with
import. It has two libraries:
let knots = import knots
let sweeps = import sweeps
export knots.knot(knots.fitted(knots.torus_knot(2, 3), 60), 3) color "teal"
export sweeps.closed(circle(40), rectangle(6, 3), twist: 1) |> move(x: 100) color "ochre"
knotsfor knots. A knot there is a path: a function that gives a point for an angle t from 0 to 360.- Paths:
torus_knot(p, q),turks_head(leads, bights),lissajous(…),figure_eightandcatalog, a list of eight well-known knots. - Changing paths:
fitted(brought to a diameter),scaled,moved,tilted,squashed;reachmeasures the largest distance from the centre. - Solids from them:
knot(a tube around the path),rope(a rope with strands),carrick_bend(two interlaced ropes);curve_ofgives the path as a curve.
- Paths:
sweepsfor profiles along closed paths:closed(path, profile, twist)takes a flat profile once around, as a ring, tube or rope, and turns ittwisttimes on the way (whole turns only, otherwise the end would not fit the start).frames(path, n)gives the n frames along the path on which the profile sits.
Examples: knots with the whole catalogue and the Carrick
bend; sweep_in_language builds a closed sweep itself, step
by step (in the browser under Model). How the libraries
are built is explained in lesson
3.2.
Common mistakes
knotflow knows the habits from Python, JavaScript and OpenSCAD and says how it is written here:
| written | message | right |
|---|---|---|
x = 5 |
a value is defined with let | let x = 5 |
2 ** 3 |
powers are written with ^ | 2 ^ 3 |
f(x = 2) |
named arguments use ':' | f(x: 2) |
a && b |
write 'and' instead of && | a and b |
!a |
write 'not' instead of ! (and != for 'not equal') | not a |
c ? a : b |
a choice is written if c then a else b | if c then a else b |
x -> x + 1 |
a function is written with => | x => x + 1 |
'a' |
texts are written in double quotes | "a" |
"a" + "b" |
to join them write a ++ b | "a" ++ "b" |
[1, 2] * 2 |
for every element of a list use map | [x * 2 | x <- [1, 2]] |
1 < x < 3 |
comparisons do not chain | 1 < x and x < 3 |
xs[-1] |
from the end: xs[len(xs) - 1] | xs[len(xs) - 1] |
[x | x > 1] |
a comprehension needs at least one 'x <- list' | if x > 1 then [x] else [] |
let a = b + 1 before let b |
b is defined further down | swap the order |
export circle(10) |
a curve has no area yet | extrude, revolve, loft |
color "red" |
unknown colour red; there are: … | one of the colours named |
Three things that work differently from what you may be used to:
- Angles are degrees.
sin(90)is 1.sin(pi)is the sine of 3.14 degrees, about 0.055. range(a, b)stops before b,[a .. b]includes b.zipwants lists of equal length and reports an error otherwise, instead of silently shortening.
What comes next
Chapter 4 computes with numbers, points and curves, chapter 5 uses
all of this for shapes: curves, surfaces, moving and turning. The
example models tour_1_basics to
tour_4_recursion (in the browser under
Model) show the language at work, each with
comments.