reduce
On this page

reduce()

Function in Authoring

Fold a value over a C-style loop: the value-returning spelling of the var acc = init; for (...) { acc = f(acc, i) } accumulator.

import { reduce } from 'typeshade'

The signature, the description and the examples come from the compiler's own source at commit 26de7be8.

Syntax

function reduce<K extends string, J extends string>(
init: ReadonlyNode<K>,
loopInit: ReadonlyNode<J>,
cond: (i: Node<J>) => ReadonlyNode<'bool'>,
body: (acc: Node<K>, i: Node<J>) => ReadonlyNode<K>,
step?: ReadonlyNode<ScalarKey> | number,
): Node<K>

Parameters

init ReadonlyNode<K>

the accumulator’s initial value, which also fixes its type.

loopInit ReadonlyNode<J>

the counter’s initial value.

cond (i: Node<J>) => ReadonlyNode<'bool'>

the continue test, receiving the counter.

body (acc: Node<K>, i: Node<J>) => ReadonlyNode<K>

receives the accumulator and the counter, and returns the next accumulator.

stepoptional ReadonlyNode<ScalarKey> | number

the per-iteration increment. Defaults to +1.

Return value

Node<K>

a node reading the accumulator after the loop.

Description

The body returns the next accumulator value, so the call site declares no Var and writes no assign; reduce materialises the variable, the loop and the assignment internally, and the emitted statements are the same as the hand-written form. Returns the accumulator node for use after the loop.

Examples

Example

import { reduce, toF32, f32, u32 } from 'typeshade'
const sum = reduce(f32(0), u32(0), (i) => i.lt(u32(8)), (acc, i) => acc.add(toF32(i)))

In the guide

See also

Source

src/core/ir/builder.ts, line 1943, at commit 26de7be8

Edit this page Report a problem