Posts tagged ‘higher-order functions’

Currying, state and higher-order functions

Take any higher order-function that returns a single function. It will always take the following form (upto some minor very minor changes):

def f(x):
     s = STATE(x)
     def g(y):
          return CODE(s,y)

g = f(arg)

This can immediately be converted to:

def f(x, y):
     s = STATE(x)
     return CODE(s,y)

g = lambda y: f(x, y)

This means that if we are working in a referentially transparent code with no side-effects, every higher-order function returning a function can be thought of as a function in several variables.

Its return value can be thought of as the function obtained by setting the values of some the variables in a multivariate function to constants. This means that, in a way, higher-order functions are just a mechanism for storing data together with a function. This is very much like what objects do in object-oriented programming, and in fact it is possible to replace any higher-order function with an equivalent class (I’ll talk about this in another post).

The only difference between the two function calls is that in the second STATE(arg) will get evaluated whenever g gets called, whereas in the first STATE(arg) will only ever get called once.

March 12, 2008 at 10:25 pm Leave a comment


May 2024
M T W T F S S
 12345
6789101112
13141516171819
20212223242526
2728293031