Files
modeling-app/docs/kcl/map.md
Adam Chalmers 6aa588f09f Bug: KCL formatter removes 'fn' from closures: (#4718)
# 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`.
2024-12-09 19:13:49 -06:00

91 KiB

title, excerpt, layout
title excerpt layout
map Apply a function to every element of a list. 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)]

map(array: [KclValue], map_fn: FunctionParam) -> [KclValue]

Arguments

Name Type Description Required
array [KclValue] Yes
map_fn FunctionParam Yes

Returns

[KclValue]

Examples

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)

Rendered example of map 0

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 }, %)
})

Rendered example of map 1