[英]python high order function FOLD on lists
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. 一切正常,除了带有lambda的减号之外。 What am I doing wrong here? 我在这里做错了什么?
The result should be "0"(3-2-1) in this example list. 在此示例列表中,结果应为“ 0”(3-2-1)。
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. 如果检查fold
的实现,则应该发现它是哪个。 Expand the "Minus" expression to see the full affect. 展开“减号”表达式以查看全部影响。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.