Scroll to navigation

Array.fold(3kaya) Kaya module reference Array.fold(3kaya)

NAME

Array::fold - Fold an array.

SYNOPSIS

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

ARGUMENTS

f The function to use
xs The array
acc The initial value for folding.

DESCRIPTION

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
}

AUTHORS

Kaya standard library by Edwin Brady, Chris Morris and others (kaya@kayalang.org). For further information see http://kayalang.org/

LICENSE

The Kaya standard library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (version 2.1 or any later version) as published by the Free Software Foundation.

RELATED

Array.map (3kaya)
October 2012 Kaya