上述问题要单独写一个def函数,不能把deep_map写在Link类中
时间: 2024-03-03 07:50:37 浏览: 18
好的,以下是将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(f, link):
if link.rest is Link.empty:
return Link(f(link.first))
else:
return Link(f(link.first), deep_map(f, link.rest))
```
在这个实现中,我们定义了一个名为deep_map的函数。它接受一个函数f和一个Link实例link作为参数,并返回一个新的Link实例,其中f应用于link中的所有元素。我们使用递归来遍历Link实例中的所有元素,并将函数f应用于它们。如果Link实例的rest属性是空的,我们返回一个只包含f应用于第一个元素的Link实例。否则,我们返回一个新的Link实例,其中包含f应用于第一个元素,并递归应用于rest属性的deep_map函数的返回值。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)