Currying, state and higher-order functions

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

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.

Advertisements

Entry filed under: Uncategorized. Tags: , , , .

A python caching decorator for referential transparent functions Emacs – select entire buffer macro

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Trackback this post  |  Subscribe to the comments via RSS Feed


March 2008
M T W T F S S
« Feb   Apr »
 12
3456789
10111213141516
17181920212223
24252627282930
31  

%d bloggers like this: