如何返回列表的第一个 n
元素?这是我所拥有的:
(define returns(lambda (list n)
(cond ((null? list) '())
(((!= (0) n) (- n 1)) (car list) (cons (car list) (returns (cdr list) n)))
(else '()))))
例子:
(returns '(5 4 5 2 1) 2)
(5 4)
(returns '(5 4 5 2 1) 3)
(5 4 5)
最佳答案
你要求 take
过程:
(define returns take)
(returns '(5 4 5 2 1) 2)
=> (5 4)
(returns '(5 4 5 2 1) 3)
=> (5 4 5)
这看起来像家庭作业,所以我想你必须从头开始实现它。一些提示,填空:
(define returns
(lambda (lst n)
(if <???> ; if n is zero
<???> ; return the empty list
(cons <???> ; otherwise cons the first element of the list
(returns <???> ; advance the recursion over the list
<???>))))) ; subtract 1 from n
不要忘记测试它!
关于list - 返回列表的前 n 个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14489520/