Posts tagged ‘assumes knowledge’

Second-order functions versus currying in python

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.

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


April 2024
M T W T F S S
1234567
891011121314
15161718192021
22232425262728
2930