functional programming and default parameters

Duncan Booth duncan at NOSPAMrcp.co.uk
Fri Jun 29 04:12:40 EDT 2001


"Nick Perkins" <nperkins7 at home.com> wrote in
news:aBV_6.367752$eK2.75191451 at news4.rdc1.on.home.com: 

> ..suppose i want to create a list of functions with no parameters,
> such that:
> 
> fns[0]() -> 0
> fns[1]() -> 1
> fns[2]() -> 2
> etc.
> 
> this does not work:
> 
<snip>
> 
> Can this be done without using default parameters?

Of course it can, but you might be better off using a functional language
if you want to do this kind of thing: 

----- begin ----
from __future__ import nested_scopes

def create_f(x):
    def f(): return x
    return f
fnlist = [ create_f(i) for i in range(10) ]
print fnlist[0](), fnlist[1]()
print fnlist[2](99)
---- end ----

Prints:
0 1
Traceback (most recent call last):
  File "D:\temp\fn.py", line 8, in ?
    print fnlist[2](99)
TypeError: f() takes no arguments (1 given)

You could also get the same effect by making the 'functions' callable
class instances (left as an exercise for the reader). 

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?



More information about the Python-list mailing list