Lesson 16
map, filter and fold as words
A dictionary can hold words as well as rules. This one makes map, filter and fold out of kernel tokens and CALL.
The lesson
A word is a line name => tokens. The dictionary also defines input, the whole input as a list, and num, a number as decimal text. None of them is built in.
list [ code ] map runs the code on every character. list [ test ] filter keeps those where the test is not 0. list start [ code ] fold combines them.
The kernel reference in the Docs lists every instruction. The example's Step button runs it in the Studio one instruction at a time.
Example
Output
Exercise 1
With map, print every input byte plus one.
Run tries your program on the input below. Check runs it on every test.
| Input | Expected output |
|---|---|
HAL | IBM |
hello | ifmmp |
abc | bcd |
~ | \x7f! |
Output
A hint
The code gets one byte on the stack and leaves the new byte.
One answer
Answer: With map, print every input byte plus one.
Expected output
IBM
| Input | Expected output |
|---|---|
HAL | IBM |
hello | ifmmp |
abc | bcd |
~ | \x7f! |
Output
Exercise 2
With filter, print only the digits of the input.
Run tries your program on the input below. Check runs it on every test.
| Input | Expected output |
|---|---|
a1b2c3 | 123 |
year 2026! | 2026 |
none | (nothing) |
/09: | 09 |
Output
A hint
A digit is above 47 and below 58.
One answer
Answer: With filter, print only the digits of the input.
Expected output
123
| Input | Expected output |
|---|---|
a1b2c3 | 123 |
year 2026! | 2026 |
none | (nothing) |
/09: | 09 |
Output
Exercise 3
With fold, print the sum of the input digits in decimal.
Run tries your program on the input below. Check runs it on every test.
| Input | Expected output |
|---|---|
123 | 6 |
999 | 27 |
0 | 0 |
4815162342 | 36 |
Output
A hint
Start from 0; the code gets the running total and a byte.
One answer
Answer: With fold, print the sum of the input digits in decimal.
Expected output
6
| Input | Expected output |
|---|---|
123 | 6 |
999 | 27 |
0 | 0 |
4815162342 | 36 |
Output