more functional programming

Andrae Muys amuys at shortech.com.au
Mon Mar 4 21:38:18 EST 2002


Giorgi Lekishvili <gleki at gol.ge> wrote in message news:<3C83EF44.A44E595C at gol.ge>...
> Hi all!
> 
> Please, accept my appologies for this naive question.
> 
> I have taken a careful look on the operator module docs. The module
> enables one to make procedures as lists. That's too good.
> 
> However, is there already something like scheme's "define" abstractor?
> This'd be used as the first element of such list, yielding the result of
> the procedure...
> 
> Is this, or anything similar, already present in Python? If not, does
> someone of the Python gurus plan to do so?
> 

I may be corrected, but afaik the answers no.  OTOH, you can easily
write a class that can wrap a list of functions and call them in
sequence.  In fact it's also relatively trivial to emulate a moduleish
interface to a set of such functions

ie.

class FakeModule:
    def __init__(self):
        self.funcs = {}

    def define(self, flist):
        self.funcs[flist[0]] = flist[1:]

    def __getattr__(self, name):
        return FakeFunction(self.funcs[name])

class FakeFunction:
    def __init__(self, flist):
        self.flist = flist

    def __call__(self, *args):
        for f in self.flist:
            if args == None:
                args = ()
            args = apply(f, args)


Note that FakeFunction will do what you wanted with define.  The
FakeModule provides a namespace for such functions to live in.  I
would be inclined to pass the function name seperately from the
function list, but that would be a further departure from the define
semantics.  eg.

def define(self, fname, flist):
        self.funcs[fname] = flist

An example of use (including arg chaining):

>>> def f1():
	print 'f1 called'
	return ('f1',)

>>> def f2(arg):
	print 'f2 called after',arg
	return (arg,'f2')

>>> def f3(arg1, arg2):
	print 'f3 called after',arg1,'and',arg2
	return (arg1, arg2, 'f3')

>>> mod = FakeModule()
>>> flist = ['f123', f1, f2, f3]
>>> mod.define(flist)
>>> mod.f123()
f1 called
f2 called after f1
f3 called after f1 and f2

Andrae

ps. It would be nice if apply() interpreted args=None as args=(), but
it's only a minor annoyance, and the if statement covers it.



More information about the Python-list mailing list