defrange_link(start,end):"""Return a Link list of 0, 1, 2, ..., n-1. >>> range_link(3,6) Link(3, Link(4, Link(5))) """ifstart>=end:returnLink.emptyreturnLink(start,range_link(start+1,end))
defmap_link(fn,s):"""Return a Link that contains f(x) for each x in Link s. >>> s = range_link(3, 6) >>> s Link(3, Link(4, Link(5))) >>> map_link(lambda x: x*x, s) Link(9, Link(16, Link(25))) """ifsisLink.empty:returnLink.emptyreturnLink(fn(s.first),map_link(fn,s.rest))
deffilter_link(fn,s):"""Return a Link containing only elements of Link s for which fn returns True. >>> s = range_link(3, 6) >>> s Link(3, Link(4, Link(5))) >>> filter_link(lambda x: x % 2 == 1, s) Link(3, Link(5)) """ifsisLink.empty:returnLink.empty#如果s是空的,直接返回空.fliter_rest=filter_link(fn,s.rest)#递归调用iffn(s.first):returnLink(s.first,fliter_rest)#如果fn通过,把这个值加入Link,并且继续递归else:returnfliter_rest#如果fn不通过,这个值跳过,直接返回剩下的部分继续递归
defadd(s,v):"""Add a value to an ordered s with no repeats,returning modified s."""assertsisLink.emptyifs.first>v:s.first,s.rest=v,Link(s.first,s.rest)elifs.first<vands.restisLink.empty:s.rest=Link(v)elifs.first<v:s.rest=add(s.rest,v)returns