list( myArr );
// Recreates the Array from the List
myArr = Lambda.array( myLst );
fold()
The fold function is very useful, as it will allow you to produce a value from an iterator by applying a
function that accepts each element in turn and returns a value based on a calculation with a given
starting value. This value is then carried to the next calculation involving the next value in the iterator.
For example, you could pass the fold function an iterator containing a list of integers, a starting integer
value, and a function that takes two integers and adds them together. The result would then be the sum
of all the items in the iterator plus the starting integer value:
class FoldList
{
public static function main()
{
var arr : Array < Int > = [1,2,3,4,5];
var fun : Int - > Int - > Int = function( a : Int, b : Int ) : Int
{
return a + b;
}
var initialValue : Int = 22;
// Outputs: 37
trace(Lambda.fold(arr, fun, initialValue));
}
}
(continued)
Chapter 4: Controlling the Flow of Information
99
Summary
You now know much about program structure, data control, and the flexibility of functions in the haXe
language.
Pages:
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224