Kaya 0.5.2 reference for Array::fold

List of functions and data types in Array

b fold(b(a, b) f, [a] xs, b acc)

Arguments

Usage

Applies a function across an array. For example, given a function sum which adds two integers:

total = fold(sum,[1,2,3,4,5],0);
putStrLn(String(total));

This prints the sum of the values in the array [1,2,3,4,5]. The following example uses fold to calculate the final direction.

data Direction = North | East | South | West;
data Turn = Left | Right;
Direction doTurn(Turn turn, Direction current) {
    case turn of {
        Left -> case current of {
            North -> new = West;
            | West -> new = South;
            | South -> new = East;
            | East -> new = North;
        }
        | Right -> case current of {
            North -> new = East;
            | West -> new = North;
            | South -> new = West;
            | East -> new = South;
        } 
    }
    return new;
}

Void main() {
    turns = [Left,Left,Left,Right,Right,Left,Right,Left,Left];
    original = West;
    final = fold(doTurn,turns,original);
    // final = North
}

Related

kaya@kayalang.org | Last modified 29 November 2011 | Supported by Durham CompSoc | Powered by Kaya