Implement deep_map, which takes a function f and a link. It returns a new linked list with the same structure as link, but with f applied to any element within link or any Link instance contained in link. The deep_map function should recursively apply fn to each of that Link's elements rather than to that Link itself.其中class Link: empty = () def init(self, first, rest=empty): assert rest is Link.empty or isinstance(rest, Link) self.first = first self.rest = rest def repr(self): if self.rest is not Link.empty: rest_repr = ', ' + repr(self.rest) else: rest_repr = '' return 'Link(' + repr(self.first) + rest_repr + ')' def str(self): string = '<' while self.rest is not Link.empty: string += str(self.first) + ' ' self = self.rest return string + str(self.first) + '>'
时间: 2023-12-26 09:06:01 浏览: 130
depthmap basics
下面是实现 deep_map 函数的代码:
```python
class Link:
empty = ()
def __init__(self, first, rest=empty):
assert rest is Link.empty or isinstance(rest, Link)
self.first = first
self.rest = rest
def __repr__(self):
if self.rest is not Link.empty:
rest_repr = ', ' + repr(self.rest)
else:
rest_repr = ''
return 'Link(' + repr(self.first) + rest_repr + ')'
def __str__(self):
string = '<'
while self.rest is not Link.empty:
string += str(self.first) + ' '
self = self.rest
return string + str(self.first) + '>'
def deep_map(self, fn):
new_first = fn(self.first)
if isinstance(self.first, Link):
new_first = self.first.deep_map(fn)
if self.rest is Link.empty:
return Link(new_first)
else:
return Link(new_first, self.rest.deep_map(fn))
```
以上代码中,我们在 Link 类中定义了 deep_map 方法。该方法接受一个函数 fn,然后应用该函数到链表中的每个元素并返回一个新的链表。在 deep_map 方法中,我们首先对第一个元素应用 fn 函数,如果第一个元素是一个 Link 实例,那么我们需要递归地对其应用 deep_map 方法。然后,我们检查链表的 rest 属性是否为空,如果不为空,我们需要对 rest 属性递归地应用 deep_map 方法,并将新的第一个元素和新的 rest 属性传递给 Link 构造函数来构造一个新的链表。最后返回这个新的链表。
阅读全文