#!/usr/bin/python

#   Copyright (C) 2003 Yannick Gingras <ygingras@ygingras.net>
#   Copyright (C) 2003 Vincent Barbin <vbarbin@openbeatbox.org>

#   This file is part of Open Beat Box.

#   Open Beat Box is free software; you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation; either version 2 of the License, or
#   (at your option) any later version.

#   Open Beat Box is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.

#   You should have received a copy of the GNU General Public License
#   along with Open Beat Box; if not, write to the Free Software
#   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

class MultiFunct:
    """ MultiFunct : a fonction composition class

                     __call__ is overloaded to pass it's argument to
                     the 1st function in the list and to pass the
                     result to the second one and so on."""
    
    def __init__(self):
        self.subFunctions = []

    def prefix(self, funct):
        """ set the f of f(g(a)) """
        self.subFunctions.insert(0, funct)

    def compose(self, funct):
        """ set the g of f(g(a)) """
        self.subFunctions.append(funct)

    def __call__(self, arg):
        result = arg
        functs = self.subFunctions[:]
        functs.reverse()
        for funct in functs:
            result = funct(result)
        return result

if __name__ == '__main__':
    mFuct = MultiFunct()
    mFuct.compose(lambda a:a+2)
    mFuct.compose(lambda a:a*2)
    mFuct.prefix(lambda a:a+42)

    print mFuct(1)
    
