class Node:
def __init__(self, head, tail):
self.head = head
self.tail = tail
self.isEmpty = False
class Empty:
def __init__(self):
self.isEmpty = True
def fold(ls,f,z):
if ls.isEmpty:
return z
else:
return f(ls.head,fold(ls.tail,f,z))
print(fold(Node(4,Node(3,Node(2,Node(1,e)))),lambda x,y:x+y,0)) ## Sum
print(fold(Node(3,Node(2,Node(1,e))),lambda x,y:x*y,1)) ## Multiply
print(fold(Node(3,Node(2,Node(1,e))),lambda x,y:x-y,0)) ## Minus
Everything works fine,except the minus print with lambda. What am I doing wrong here?
The result should be "0"(3-2-1) in this example list.
A hint to get you started: fold comes in two forms: left and right, corresponding to left and right associativity. If you examine your implementation of
fold, you should discover which one it is. Expand the "Minus" expression to see the full affect.