:::: MENU ::::

Higher order functions – simplifying loops – part 2 of ??

This is the 2nd part of my series on everyday functional programming.

Filtering

Suppose you have a collection of items and need to grab just a subset that match a certain criteria. Programming C# in an imperative style, you could use a for or foreach loop as follows:

Functional programming recognises this common scenario as a higher order function known as a Filter [3]; where you want to create a new list for every element that evaluates to true when a predicate function is applied to it.

In C#, filter is implemented as the LINQ Where(Func)) extension method, allowing one to write the following:

Apart from the obvious reduction in number of lines; notice how much clearer the intent of the filter is, and the many opportunities for error we have eliminated.

In Javascript we use the filter function:

Mapping

In many instances you find yourself wanting to perform the same operation on every item in an existing collection. In Javascript in an imperative style we might want to do the following

In functional programming this is know as the higher order function: Map [4] and in Javascript can be applied using a single statement map()

In C#, map is implemented by the LINQ Select(Func) extension method:

[1] – http://railspikes.com/2008/7/29/functional-loops-in-ruby-each-map-inject-select-and-for
[2] – http://msdn.microsoft.com/en-us/library/system.linq.enumerable.aspx
[3] – http://en.wikipedia.org/wiki/Filter_(higher-order_function)
[4] – http://en.wikipedia.org/wiki/Map_(higher-order_function)


One Comment

So, what do you think ?