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) + '>'请把deep_map函数写在Link外
时间: 2023-12-26 17:05:31 浏览: 156
以下是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, f):
if self.rest is Link.empty:
return Link(f(self.first))
else:
return Link(f(self.first), self.rest.deep_map(f))
```
在这个实现中,我们使用了递归来遍历Link实例中的所有元素,并将函数f应用于它们。如果Link实例的rest属性是空的,我们返回一个只包含f应用于第一个元素的Link实例。否则,我们返回一个新的Link实例,其中包含f应用于第一个元素,并递归应用于rest属性的deep_map方法的返回值。
阅读全文