import Code from "@/components/Code.astro";

Array.fold

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

Signature

<Code thpcode={fun fold[A, B]( self[A], B init, (B acc, A next) -> (B) transform_function, ) -> B} />

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:

<Code thpcode={val digits = [1, 9, 9, 5]} />

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

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

digits.fold("", f) // "1985" `} />


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:

<Code thpcode={val digits = [1, 9, 8, 5] digits.fold(0, fun(acc, next) = acc + next) // 23} />

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:

<Code thpcode={` val digits = [1, 9, 8, 5] val builder = ThingBuilder()

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

val result = builder.build() `} />

Or anything.