更新时间:2023-12-03 08:28:28
考虑如何实现 append
(或者,更一般地说,考虑如何实现右折叠).现在,如果您将一个列表附加到包含要添加的元素的单例列表中,那么您基本上已经附加了您的元素.
Think about how you would implement append
(or, more generally, think about how you would implement a right-fold). Now, if you append a list to a singleton list containing your element-to-add, you've basically appended your element.
(显然,这是 O(n),所以不要这样单独添加元素.)
(Obviously, this is O(n), so don't add elements individually this way.)
这是使用右折叠的解决方案:
Here's a solution using a right-fold:
(define (append-element lst elem)
(foldr cons (list elem) lst))
和使用 append
的解决方案:
and a solution using append
:
(define (append-element lst elem)
(append lst (list elem)))
因此,如果您可以自己实现 foldr
或 append
,使用您列出的操作(很简单!尝试一下),那么您就可以开始了.
So if you can implement either foldr
or append
yourself, using the operations you've listed (it's easy! try it), you're good to go.
附言实际上,您可以使用右折叠实现 append
:
P.S. In fact, you can implement append
using a right-fold:
(define (append lst1 lst2)
(foldr cons lst2 lst1))
但这仍然让您自己实现 foldr
.;-)(提示:这很容易.查看我对左折叠的实现以获取开始的想法.)
but that still leaves you to implement foldr
yourself. ;-) (Hint: it's easy. Look at my implementation of left-fold for starting ideas.)