jweinst1
11/23/2016 - 7:42 AM

funcgen.py

#Practice for Streams and functions

#FunctionStream
#Problem 1


#In python, __call__ is used to make an instance of a class into a callable function,
# # where u can use it directly with parenthesis, such as inst(4)
""">>> a = FuncStream(1, 5, lambda a, b: a - b)
#>>> a()
-4
#>>> a.nextresult
-5
#>>> a.nextresult
-6
#>>> a.nextresult
-7
#>>> a.nextresult
#-8"""
class FuncStream:

    def __init__(self, arg, operand, fn):
        #fn must be a lambda or function that takes tw arguments
        self.arg = arg
        self.operand = operand
        self.fn = fn
        self.last = None

    def __call__(self):
        return self.fn(self.arg, self.operand)

#stream property
    @property
    def nextresult(self):
        self.operand += 1
        self.last = self()
        return self.last



#returns a lambda with a captured value which changes its output.
#This allows you to essentially to make a lambda on the fly

"""
>>> b = FuncGen([0], lambda lst, ad: lst + ad, [0])
>>> c = next(b)
>>> c([1])
[0, 1]
>>> c([1])
[0, 1]
>>> c = next(b)
>>> c([1])
[0, 0, 1]
>>> c = next(b)
>>> c([1])
[0, 0, 0, 1]"""
def make_lambda(a, fn):
    return lambda b: fn(a, b)


#implement FuncGen, which is a generator that continuously genrates new functions with an incremently
#higher output
def FuncGen(start, fn, inc):
    pass