make clean

December 1, 2007

Functional Programming and automatic type inference

Filed under: Uncategorized — pharaoh @ 12:28 pm
Tags: , ,

The power of functional programming combined with type inference is amazing. Consider for example this code snippet, written in Scala, and taken from here:

class Knapsack extends jiva.ProbDefiner {
     def gaProblem = buildBooleanProb {buildr =>
        buildr name "Knapsack"
     }
 }

It’s an amazingly compact piece of code which does a lot of things under the hood.

  • It defines a function “gaProblem”. The return type is automatically inferred to be the return type of the function buildBooleanProb() which is defined in ProbDefiner.
  • The function buildBooleanProb() takes another function as it’s argument. This is the hallmark of functional programming languages. They support “first-classed functions”, which means that functions are like any other objects, and can be passed around as values!
  • The => notation creates an anonymous function automatically. Let’s give it a name, say “monkey_1”
  • The monkey_1 function takes as argument an object called “buildr”, and calls some functions on it. Note that the type of “buildr” has not been declared. The syntax ‘buildr name “Knapsack” ‘ is translated in Scala to ‘buildr.name(“Knapsack”)’

Note that Scala is a strongly type language, and yet for all the above objects not a single type definition has been specified. It is all inferred by the compiler. The benefits of this are, less boiler-plate code to type, which means it is suitable for RAD*, and type-checking at compile time, which prevents common errors.

For example, if the programmer types “buildr xyz” and xyz is not defined in that class, Scala will complain at compile time.

*Although type inference might be suitable for RAD, the functional programming paradigm itself may not be suitable for RAD if programmers are not comfortable/familiar with it.

Blog at WordPress.com.