Array.fold

Reduces the elements of this array into a single value by calling a function on each element, starting from the left.

Signature

fun fold[A, B](
    self[A],
    B init,
    (B acc, A next) -> (B) transform_function,
) -> Bthp

Parameters

Return value

Description

Fold allows you to transform an array of A into a single B, following an arbitraty function.

For example, let’s say that you have an array of numbers:

val digits = [1, 9, 9, 5]thp

And you want to join all digits into a String like "1985". You can achieve this with a fold.

val digits = [1, 9, 8, 5]
val init = ""
fun f(String acc, Int next) = acc ++ next

digits.fold("", f) // "1985"thp

A sort of visualization is the following:

[1, 9, 8, 5].fold("", f) =
    f( f( f( f("", 1), 9), 8), 5)
    f( f( f(    "1"  , 9), 8), 5)
    f( f(          "19"  , 8), 5)
    f(                "198"  , 5)
                         "1985"

Hopefully now you understand how a fold works, and we can continue using the abstraction.


The transform_function can be any function, and can operate over any type.

For example, you could sum all numbers instead of concatenating like this:

val digits = [1, 9, 8, 5]
digits.fold(0, fun(acc, next) = acc + next)	// 23thp
Compilation error: lexical error 65537
f( f( f( f(0, 1), 9), 8), 5)
f( f( f(    1   , 9), 8), 5)
f( f(          10   , 8), 5)
f(                 18   , 5)
                       23

Or you could pass the digits to a builder class:

val digits = [1, 9, 8, 5]
val builder = ThingBuilder()

digits.fold(builder, fun(acc, next) = acc.addNumber(next))

val result = builder.build()thp

Or anything.