Skip to content

Commit

Permalink
Update documents for accumulate macro
Browse files Browse the repository at this point in the history
  • Loading branch information
mnacamura authored and technomancy committed Jul 6, 2021
1 parent 5ad4705 commit 1fe2966
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 5 deletions.
1 change: 1 addition & 0 deletions changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ Backwards-incompatible changes are **marked in bold**.
* Make macro tables shadow runtime tables more consistently
* Add `,complete foo` repl command
* Add `fennel.syntax` function describing built-ins
* Add `accumulate` macro

## 0.9.2 / 2021-05-02

Expand Down
22 changes: 22 additions & 0 deletions reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -812,6 +812,28 @@ value into a table is a no-op.
Like `each` and `for`, the table comprehensions support an `:until`
clause for early termination.

### `accumulate` iterator accumulation

Run through an iterator and performs accumulation, similar to `fold`
and `reduce` commonly used in functional programming languages.
Like `collect` and `icollect`, it takes an iterator binding table
and an expression as its arguments. The difference is that in
`accumulate`, the first two items in the binding table are used as
an "accumulator" variable and its initial value.
For each iteration step, it evaluates the given expression and
the returned value becomes the next accumulator variable.
`accumulate` returns the final value of the accumulator variable.

Example:

```fennel
(accumulate [avg 0
i n (ipairs [1 2 3 4])]
(let [/i (/ i)]
(+ (* avg (- 1 /i)) (* n /i))))
;; -> 2.5
```

### `values` multi-valued return

Returns multiple values from a function. Usually used to signal
Expand Down
9 changes: 4 additions & 5 deletions src/fennel/macros.fnl
Original file line number Diff line number Diff line change
Expand Up @@ -151,14 +151,13 @@ returns

(fn accumulate* [iter-tbl accum-expr ...]
"Accumulation macro.
Similar to `collect` and `icollect`, it takes a binding table and an
expression as its arguments.
It takes a binding table and an expression as its arguments.
In the binding table, the first symbol is bound to the second value, being an
initial accumulating variable. The rest are an iterator binding table in the
initial accumulator variable. The rest are an iterator binding table in the
format `each` takes.
It runs through the iterator in each step of which the given expression is
evaluated, and its returned value updates the accumulating variable.
It eventually returns the final value of the accumulating variable.
evaluated, and its returned value updates the accumulator variable.
It eventually returns the final value of the accumulator variable.
For example,
(accumulate [total 0
Expand Down

0 comments on commit 1fe2966

Please sign in to comment.