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 21:06:01 浏览: 72
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, f):
if self.rest is Link.empty:
return Link(f(self.first))
else:
return Link(f(self.first), self.rest.deep_map(f))
```
使用示例:
```python
def add_one(x):
return x + 1
a = Link(1, Link(2, Link(3, Link(4))))
b = Link(Link(1), Link(Link(2), Link(3)))
print(a.deep_map(add_one)) # Link(2, Link(3, Link(4, Link(5))))
print(b.deep_map(str)) # Link('<1>', Link('<2>', Link('3')))
```
阅读全文