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.

Add comment March 11, 2008


Meta

Facets

abstruse Add new tag AOP apt aspect oriented programming assumes knowledge autiobiographical bash scripts bell books clarity code samples configuration console emacs for the benefit of google functional programming graphical design hacks higher-order functions howtos intention revealing programming keyboard links linux note to self opinions parsing patterns philosophising philosophizing programming python random ideas refactoring removing packages short stories succinct svn systems stuff theoretical philosophizing typing work ethic you probably don't want to read this

Archives

Pages

 

November 2009
M T W T F S S
« Aug    
 1
2345678
9101112131415
16171819202122
23242526272829
30