diff options
| author | s-ol <s-ol@users.noreply.github.com> | 2020-08-21 13:51:38 +0000 |
|---|---|---|
| committer | s-ol <s+removethis@s-ol.nu> | 2025-03-02 14:24:49 +0000 |
| commit | 8179d54b3be4e2595e7c87462e818c6c37e6a45f (patch) | |
| tree | c122c2ad39db67114c0723d83c0f780520a2eefd /docs/reference | |
| parent | fix if, add when (diff) | |
| download | alive-8179d54b3be4e2595e7c87462e818c6c37e6a45f.tar.gz alive-8179d54b3be4e2595e7c87462e818c6c37e6a45f.zip | |
add reference/loops
Diffstat (limited to 'docs/reference')
| -rw-r--r-- | docs/reference/03-5_loops.md | 37 | ||||
| -rw-r--r-- | docs/reference/index.md | 2 |
2 files changed, 38 insertions, 1 deletions
diff --git a/docs/reference/03-5_loops.md b/docs/reference/03-5_loops.md new file mode 100644 index 0000000..aedc4ab --- /dev/null +++ b/docs/reference/03-5_loops.md @@ -0,0 +1,37 @@ +Loops are an evaltime construct that allows dealing with repetetive code and +lists of varying data, among other things. + +The [loop][] and [recur][] ops are the basic building block of loops: [loop][] +begins a recursive loop, and [recur][] is used to restart it: + + (import* math logic string) + + (loop (n 5) + (when (!= n 0) + (print (str "hello #" n)) + (recur (- n 1)))) + +In this example, the `(when …)` expression is the body of the loop, i.e. the +code that is repeated multiple times. In the head of the loop, loop definitions +can be introduced in a key-value syntax like with [def][]. Loop definitions are +valid only within the loop body and can be changed for each iteration of the +loop. Here a single symbol `n` is defined to its starting value of `5`. + +The loop body then starts being evaluated. Once it reaches the `(recur …)` +expression, the loop is restarted from the top, with the new value for `n` +given as the parameter. In this case, every new iteration of the loop has its +`n` decremented by one, until `n` is zero and therefore the `(recur …)` +expression is no longer reached. + +Behind the scenes, [loop][] defines a new function for the dynamic symbol +`*recur*` and immediately invokes it with the default values, and [recur][] +simply calls this function. The example above could be equivalently rewritten +as follows: + + (import* math logic string) + + (defn loop-fn (n) + (when (!= n 0) + (print (str "hello #" n)) + (loop-fn (- n 1)))) + (loop-fn 5) diff --git a/docs/reference/index.md b/docs/reference/index.md index cfa8fdc..5012d0f 100644 --- a/docs/reference/index.md +++ b/docs/reference/index.md @@ -17,7 +17,7 @@ own module or contributing to alive, check out the 2. if and switch 3. [functions](03-3_functions.html) 4. dynamic symbols - 5. loops + 5. [loops](03-5_loops.html) 6. modules and loading 4. runtime 1. result kinds |
