# Problem Before this PR, our formatter reformats ``` squares_out = reduce(arr, 0, fn (i, squares) { return 1 }) ``` to ``` squares_out = reduce(arr, 0, (i, squares) { return 1 }) ``` i.e. it removes the `fn` keyword from the closure. This keyword is required, so, our formatter turned working code into invalid code. # Cause When this closure parameter is formatted, the ExprContext is ::Decl, so `Expr::recast` skips adding the `fn` keyword. The reason it's ::Decl is because the `squares_out = ` declaration sets it, and no subsequent call sets the context to something else. # Solution When recasting a call expression, set the context for every argument to `ExprContext::Other`.
57 lines
91 KiB
Markdown
57 lines
91 KiB
Markdown
---
|
|
title: "map"
|
|
excerpt: "Apply a function to every element of a list."
|
|
layout: manual
|
|
---
|
|
|
|
Apply a function to every element of a list.
|
|
|
|
Given a list like `[a, b, c]`, and a function like `f`, returns `[f(a), f(b), f(c)]`
|
|
|
|
```js
|
|
map(array: [KclValue], map_fn: FunctionParam) -> [KclValue]
|
|
```
|
|
|
|
|
|
### Arguments
|
|
|
|
| Name | Type | Description | Required |
|
|
|----------|------|-------------|----------|
|
|
| `array` | [`[KclValue]`](/docs/kcl/types/KclValue) | | Yes |
|
|
| `map_fn` | `FunctionParam` | | Yes |
|
|
|
|
### Returns
|
|
|
|
[`[KclValue]`](/docs/kcl/types/KclValue)
|
|
|
|
|
|
### Examples
|
|
|
|
```js
|
|
r = 10 // radius
|
|
fn drawCircle(id) {
|
|
return startSketchOn("XY")
|
|
|> circle({ center = [id * 2 * r, 0], radius = r }, %)
|
|
}
|
|
|
|
// Call `drawCircle`, passing in each element of the array.
|
|
// The outputs from each `drawCircle` form a new array,
|
|
// which is the return value from `map`.
|
|
circles = map([1..3], drawCircle)
|
|
```
|
|
|
|

|
|
|
|
```js
|
|
r = 10 // radius
|
|
// Call `map`, using an anonymous function instead of a named one.
|
|
circles = map([1..3], fn(id) {
|
|
return startSketchOn("XY")
|
|
|> circle({ center = [id * 2 * r, 0], radius = r }, %)
|
|
})
|
|
```
|
|
|
|

|
|
|
|
|