返回列表的前n个 [英] returns the first n of list
本文介绍了返回列表的前n个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何返回列表的前n
个元素?这就是我所拥有的:
How to return the first n
elements of a list? Here's what I have:
(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)
推荐答案
You're asking for the take
procedure:
(define returns take)
(returns '(5 4 5 2 1) 2)
=> (5 4)
(returns '(5 4 5 2 1) 3)
=> (5 4 5)
这看起来像作业,所以我想您必须从头开始实施它.一些提示,请填写空白:
This looks like homework, so I guess you have to implement it from scratch. Some hints, fill-in the blanks:
(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
别忘了测试!
这篇关于返回列表的前n个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文