Prev | Current Page 206 | Next

L. McColl-Sylvester and F. Ponticelli

"Professional haXe and Neko"


class FunctionMapping
{
public static function main()
{
var strLst : List < String > = new List();
strLst.add(???Bob???);
strLst.add(???Burt???);
strLst.add(???James???);
strLst.add(???Rupert???);
var intLst : List < Int > ;
var fun : String - > Int = function( x : String ) : Int
{
return x.length;
}
intLst = strLst.map( fun );
(continued)
Chapter 4: Controlling the Flow of Information
95
// Outputs: {3, 4, 5, 6}
trace(intLst);
}
}
The List strLst was initialized and filled with a number of string values. You then constructed a local
function, which received a value of type String and returned the length of the string as type Int . This
function was passed to the Lists map method, which created a new List of type Int and, while iterating
through the original List, applied the local function to each of the contained items and passed them to
the new List. If the type being returned matched the type of the contained items in the original List, it
would have made sense to assign the returned List to the original Lists variable, which would have
provided the appearance that the values contained were directly affected.


Pages:
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218