# Python函数式编程系列010：惰性列表之动手实现List

English

``````def cons(head, tail):
def helper():
return helper``````

``````head = lambda cons_list: cons_list()[0]
tail = lambda cons_list: cons_list()[1]``````

``````def cons_apply(*args):
if len(args) == 0:
return empty_list_base
else:
return cons(args[0], cons_apply(*args[1:]))``````

``>>> cons_apply(1, 2, 3) # 返回cons(1, cos(2, cos(3, ())))``

``````def equal_cons(this: ListBase[S], that: ) -> bool:
if this == empty_list_base and that != empty_list_base:
return False
elif this != empty_list_base and that == empty_list_base:
return False
elif this == empty_list_base and that == empty_list_base:
return True
else:

``>>> assert equal_cons(cons_apply(1, 2, 3), cons(1, cons(2, cons(3, ()))))``

`map`的作用是将函数`f`带入到列表的每一个值，即我们带入`f`到列表的头之后，再把`map`应用到`tail`中，即：

``````def map_cons(f, cons_list):
if cons_list == ():
return empty_list_base
else:

``````def filter_cons(f, cons_list):
if cons_list == ():
return empty_list_base
else:
if f(hd):
return cons(hd, filter_cons(f, tl))
else:
return tl

def fold_left_cons(f, init, cons_list):
if cons_list == ():
return init
else:

``````>>> res = fold_left_cons(lambda x, y: x + y, 0,
>>>    filter_cons(lambda x: x % 2 == 0,
>>>        map_cons(lambda x: x + 1,
>>>            cons_apply(1, 2, 3, 4, 5)
>>>    )))
>>> res == 12``````

``````map_cons_curry = lambda f: lambda cons_list: map_cons(f, cons_list)
filter_cons_curry = lambda f: lambda cons_list: filter_cons(f, cons_list)
fold_left_cons_curry = lambda f: lambda init: lambda cons_list: fold_left_cons(f, init, cons_list)``````

``````>>> f = and_then(
>>>    map_cons_curry(lambda x: x + 1),
>>>    filter_cons_curry(lambda x: x % 2 == 0),
>>>    fold_left_cons_curry(lambda x, y: x + y)(0),
>>> )
>>>
>>> assert f(cons_apply(1, 2, 3, 4, 5)) == 12``````

``````from fppy.base import F_, I

F_(I)\
.and_then(map_cons_curry(lambda x: x + 1))\
.and_then(filter_cons_curry(lambda x: x % 2 == 0))\
.and_then(fold_left_cons_curry(lambda x, y: x + y)(0))\
.apply(cons_apply(1, 2, 3, 4, 5)) # 返回12``````

0 条评论