Closes #4021 Allows array ranges (e.g., `[0..10]`) to take expression instead of just numeric literals as their start and end values. Both expressions are required (we don't support `[0..]`, etc.). I've created a new kind of expression in the AST. The alternative was to represent the internals of an array as some kind of pattern which could initially be fully explicit or ranges. I figured the chosen version was simpler and easier to extend to open ranges, whereas the latter would be easier to extend to mixed ranges or other patterns. I chose simpler, it'll be easy enough to refactor if necessary. Parsing is tested implicitly by the tests of execution and unparsing. --------- Signed-off-by: Nick Cameron <nrc@ncameron.org> Co-authored-by: Adam Chalmers <adam.chalmers@zoo.dev>
70 lines
90 KiB
Markdown
70 lines
90 KiB
Markdown
---
|
|
title: "reduce"
|
|
excerpt: "Take a starting value. Then, for each element of an array, calculate the next value,"
|
|
layout: manual
|
|
---
|
|
|
|
Take a starting value. Then, for each element of an array, calculate the next value,
|
|
|
|
using the previous value and the element.
|
|
|
|
```js
|
|
reduce(array: [KclValue], start: KclValue, reduce_fn: FunctionParam) -> KclValue
|
|
```
|
|
|
|
|
|
### Arguments
|
|
|
|
| Name | Type | Description | Required |
|
|
|----------|------|-------------|----------|
|
|
| `array` | [`[KclValue]`](/docs/kcl/types/KclValue) | | Yes |
|
|
| `start` | [`KclValue`](/docs/kcl/types/KclValue) | Any KCL value. | Yes |
|
|
| `reduce_fn` | `FunctionParam` | | Yes |
|
|
|
|
### Returns
|
|
|
|
[`KclValue`](/docs/kcl/types/KclValue) - Any KCL value.
|
|
|
|
|
|
### Examples
|
|
|
|
```js
|
|
fn decagon = (radius) => {
|
|
step = 1 / 10 * tau()
|
|
sketch001 = startSketchAt([cos(0) * radius, sin(0) * radius])
|
|
return reduce([1..10], sketch001, (i, sg) => {
|
|
x = cos(step * i) * radius
|
|
y = sin(step * i) * radius
|
|
return lineTo([x, y], sg)
|
|
})
|
|
}
|
|
decagon(5.0)
|
|
|> close(%)
|
|
```
|
|
|
|

|
|
|
|
```js
|
|
array = [1, 2, 3]
|
|
sum = reduce(array, 0, (i, result_so_far) => {
|
|
return i + result_so_far
|
|
})
|
|
assertEqual(sum, 6, 0.00001, "1 + 2 + 3 summed is 6")
|
|
```
|
|
|
|

|
|
|
|
```js
|
|
fn add = (a, b) => {
|
|
return a + b
|
|
}
|
|
fn sum = (array) => {
|
|
return reduce(array, 0, add)
|
|
}
|
|
assertEqual(sum([1, 2, 3]), 6, 0.00001, "1 + 2 + 3 summed is 6")
|
|
```
|
|
|
|

|
|
|
|
|