If you're interested in functional programming, you might also want to checkout my second blog which i'm actively working on!!

Friday, November 27, 2009

SCALA: using higher order functions

The creators of scala did a hell of a job to design the core library with control abstractions. Each collection class uses the trait Iterable which implements an exists() method.

Let's take a look at how Iterator.scala implements this higher order function exists().

The big advantage is that it now becomes easy to define generic functions to handle certain collection types. Let's see how easy it becomes to write a method that checks if a collection of numbers contains a negative number

As you can see we don't have to write all the boiler plate code of iterating anymore. We just specify the function literal which checks our condition.
Let's test our code with an Array and List, both containing integers.

numbers contains negative number = true
numbers2 contains negative number = false

No comments:

Post a Comment