2.1. First-Class Functions

In the Orc programming language, functions are first-class values. This means that a function is treated like any other value; it may be published, passed as an argument to a call, incorporated into a data structure, and so on.

Defining a function creates a special value called a closure. The name of the function is a variable and its bound value is the closure. For example, these function declarations create two closures, bound to the variables a and b, from which we subsequently create a tuple called funs:

def a(x) = x-3
def b(y) = y*4
val funs = (a,b)

A closure can be passed as an argument to another function. A function which accepts functions as arguments is called a higher-order function. Here's an example:

def diff(f) = f(1) - f(0)
def triple(x) = x * 3

diff(triple) {-  equivalent to triple(1) - triple(0)  -}

The use of higher-order functions is common in functional programming. Here is the Orc version of the classic 'map' function:

def map(f, []) = []
def map(f, h:t) = f(h):map(f,t)

Sometimes one would like to create a closure directly, without bothering to give it a name. There is a special keyword lambda for this purpose. By writing a function definition without the keyword def and replacing the function name with the keyword lambda, that definition becomes an expression which evaluates to a closure.

def diff(f) = f(1) - f(0)


diff( lambda(x) = x * 3 )
{- 
  this is identical to:
  
  def triple(x) = x * 3
  diff(triple)
-}