1Array.fold(3kaya) Kaya module reference Array.fold(3kaya)
2
3
4
6 Array::fold - Fold an array.
7
9 b fold( b(a, b) f, [a] xs, b acc )
10
12 f The function to use
13
14 xs The array
15
16 acc The initial value for folding.
17
19 Applies a function across an array. For example, given a function sum
20 which adds two integers:
21
22
23 total = fold(sum,[1,2,3,4,5],0);
24 putStrLn(String(total));
25
26 This prints the sum of the values in the array [1,2,3,4,5]
27 The following example uses fold to calculate the final direction.
28
29
30 data Direction = North | East | South | West;
31 data Turn = Left | Right;
32 Direction doTurn(Turn turn, Direction current) {
33 case turn of {
34 Left -> case current of {
35 North -> new = West;
36 | West -> new = South;
37 | South -> new = East;
38 | East -> new = North;
39 }
40 | Right -> case current of {
41 North -> new = East;
42 | West -> new = North;
43 | South -> new = West;
44 | East -> new = South;
45 }
46 }
47 return new;
48 }
49
50 Void main() {
51 turns = [Left,Left,Left,Right,Right,Left,Right,Left,Left];
52 original = West;
53 final = fold(doTurn,turns,original);
54 // final = North
55 }
56
58 Kaya standard library by Edwin Brady, Chris Morris and others
59 (kaya@kayalang.org). For further information see http://kayalang.org/
60
62 The Kaya standard library is free software; you can redistribute it
63 and/or modify it under the terms of the GNU Lesser General Public
64 License (version 2.1 or any later version) as published by the Free
65 Software Foundation.
66
68 Array.map (3kaya)
69
70
71
72Kaya December 2010 Array.fold(3kaya)