Second-order functions versus currying in python

March 11, 2008 at 10:40 pm Leave a comment

Which code sample seems better:

Sample one:

def g(x):
    def f(y):
        return x + y
    return f

a = g(1)

Sample 2

def f(x,y):
    return x  + y

a = lambda x: f(x,1)

I’d argue that the second was simpler because:

  • It is shorter
  • Understanding functions of two arguments is easier than understanding functions that return functions
  • The level of indirection to the code that actual does things is reduced by one.

Would you ever see the first example written? It probably depends how trendy the people you hang around with are. But if you are the kind of person who might feel inclined write this sort of thing, I think the second way is a better than the first.


Afterthougts:
In case you want the title to make sense, I’d refer to the first example as using a second-order function and the first as using a type of currying. (Though the word currying tends to have a more precise meaning)

Also it is debatable whether such changes will make a large difference to the quality of code as compared to other changes.

Advertisements

Entry filed under: Uncategorized. Tags: , , .

How to stop the bell ringing in bash Fixing catastrophic mistakes with apt-get

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: