Files
modeling-app/docs/kcl/reduce.md
Adam Chalmers b745cec079 KCL docs: Better docs for KclValue (#4096)
* KCL docs: Better docs for KclValue

* Update docs

---------

Co-authored-by: Jonathan Tran <jonnytran@gmail.com>
2024-10-09 03:56:38 +00:00

90 KiB

title, excerpt, layout
title excerpt layout
reduce Take a starting value. Then, for each element of an array, calculate the next value, manual

Take a starting value. Then, for each element of an array, calculate the next value,

using the previous value and the element.

reduce(array: [KclValue], start: KclValue, reduce_fn: FunctionParam) -> KclValue

Arguments

Name Type Description Required
array [KclValue] Yes
start KclValue Any KCL value. Yes
reduce_fn FunctionParam Yes

Returns

KclValue - Any KCL value.

Examples

fn decagon = (radius) => {
  step = 1 / 10 * tau()
  sketch001 = startSketchAt([cos(0) * radius, sin(0) * radius])
  return reduce([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], sketch001, (i, sg) => {
  x = cos(step * i) * radius
  y = sin(step * i) * radius
  return lineTo([x, y], sg)
})
}
decagon(5.0)
  |> close(%)

Rendered example of reduce 0

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")

Rendered example of reduce 1

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")

Rendered example of reduce 2