Welcome to the second part of my series on Functional ActionScript. Part I was a brief introduction to some concepts of functional programming in ActionScript. In this second part, I will present you some examples to ActionScript's built-in functional APIs on Array. However, first I would like to introduce you to a neat little trick that will save us some typing and make our code more clear.
Foreplay
If you take a look at the documentation of the following methods that we will discuss later (every, some, filter, forEach, and map) you will notice that they all take a callback that, apart from the return type maybe, has a signature that looks like this:
Array.forEach is pretty much the same as Array.map with a subtle but important difference: forEach executes a function on each element in an Array but unlike map has not the purpose to modify the elements. Therefore forEach returns void and map returns an Array. This may or may not sound confusing. However, the following examples will make the difference clear…
Example: Hello
Let's say hello to all elements in list:
varlist:Array=[1,2,3,4,5,6,7,8,9]functionsayHello(element:*,index:int,array:Array):void{trace("Hello, Number",element)}list.forEach(sayHello)//? Hello, Number 1//? Hello, Number 2//? Hello, Number 3//? Hello, Number 4//? Hello, Number 5//? Hello, Number 6//? Hello, Number 7//? Hello, Number 8//? Hello, Number 9
In this example I purposely didn't use my carefully crafted wrap function from above to show you how ugly the callback function can end up (line 3–6).
Old Friend: map
We've already met map in the first part on Functional ActionScript but I allow myself to introduce her here once again. Array.map takes a function, applies it to all elements in an Array and returns an Array with all modified elements.
When I'm talking about friends, I actually mean friends. Not only will the functions above be nice to you but they also get along very well with each other. Let's see how…
Example: Rendez-Vous
Let's look at this real-world scenario: If any of the elements in list is odd, you want to pick out the even elements, square them and then say hello to them. No sooner said than done:
varlist:Array=[1,2,3,4,5,6,7,8,9]if(list.some(wrap(odd))){list.filter(wrap(even)).map(wrap(square)).forEach(sayHello)}//? Hello, Number 4//? Hello, Number 16//? Hello, Number 36//? Hello, Number 64
Isn't the expressivess of this code just beautiful?
Finding a more useless example is left as an exercise to the reader.
Doggy Bag (a.k.a Source Code)
Like what you saw? Have look at it, download it, and play with it!