Ink by Example — Loops

Ink by Example: Loops

Instead of a for loop construct, we use tail recursion. The standard library contains utility functions — like std.each, std.map, and std.reduce — that can be used in place of a for loop.

std := load('../vendor/std')
log := std.log
reduce := std.reduce
each := std.each
map := std.map


numbers := [0, 1, 2, 3, 4, 5, 6]

We can loop over a list with std.each, which accepts a list and a function as arguments.

logger := num => log(num)
each(numbers, logger)

Let's create a new list with the squares of these numbers with std.map.

squares := map(numbers, num => num * num)
log(squares)

We can get the sum of these squares by using std.reduce.

sum := reduce(squares, (acc, num) => acc + num, 0)
log(sum)

$ ink loops.ink
0
1
2
3
4
5
6
{3: 9, 4: 16, 5: 25, 6: 36, 0: 0, 1: 1, 2: 4}
91

Next example: Control Flow.