Learn R Programming

kriens (version 0.1)

compose: Continuation Passing Style Function Composition

Description

It allows to compose two functions of the form f(x, ret) and g(x, ret) returning a function h(x,ret) which is the composition $f . g$. It implements the composition operator of the Continuation category.

The the composition has the following properties:

  1. Associativity: $h . (f . g) = ( h . g) . f$
  2. Unity: $f . identity2 = f = identity2 . f$

In order for these relations to hold, the function f and g must not deal with global mutable states.

Usage

compose(f, g)

Arguments

f
The first function that must be composed
g
The first function that must be composed

Value

Rerturns the composite function of f and g

See Also

forget

Examples

Run this code
# Example 1

# define an arrow in the Continuation category.
# this function applies the continuation to the
# increment of its argument and then decrements it.
one <- function(x, ret) {
    return(ret(x+1) - 1)
}

# define another arrow in the Continuation category.
# this function doubles its argument.
two <- function(x, ret) {
    return(ret(2*x))
}

# create the composition
# this is exactly the same as one %.% two
composite <- compose(one, two)

# build the function (forget the continuation)
execute1 <- forget(composite)
execute1(1)
# returns 3

# Example 2
# compose the function further to loop over an array of elements
# lapply and sapply are already arrow in the Continuation category
loop <- compose(lapply, composite)

# build the function
execute2 <- forget(loop)
execute2(1:10)

Run the code above in your browser using DataLab