Multik 0.3.0 Help

reduce

Accumulates a value by applying the operation to each element from left to right, using the first element as the initial accumulator. Throws on empty arrays; use reduceOrNull for a safe variant.

Signatures

inline fun <S, D : Dimension, T : S> MultiArray<T, D>.reduce( operation: (acc: S, T) -> S ): S inline fun <S, T : S> MultiArray<T, D1>.reduceIndexed( operation: (index: Int, acc: S, T) -> S ): S inline fun <S, D : Dimension, T : S> MultiArray<T, D>.reduceMultiIndexed( operation: (index: IntArray, acc: S, T) -> S ): S inline fun <S, D : Dimension, T : S> MultiArray<T, D>.reduceOrNull( operation: (acc: S, T) -> S ): S?

Parameters

Parameter

Type

Description

operation

(acc: S, T) -> S

Combines the accumulator with each element.

operation

(index: Int, acc: S, T) -> S

With flat index (1D arrays only).

operation

(index: IntArray, acc: S, T) -> S

With multi-dimensional index.

Returns: The final accumulated value. reduce throws UnsupportedOperationException on empty arrays; reduceOrNull returns null.

Example

val a = mk.ndarray(mk[1, 2, 3, 4]) a.reduce { acc, v -> acc + v } // 10 a.reduce { acc, v -> acc * v } // 24 a.reduceIndexed { i, acc, v -> acc + i * v } // 1 + 1*2 + 2*3 + 3*4 = 21
28 February 2026