返回列表的前n个

时间:2013-01-23 21:15:09

标签: list scheme

如何返回列表的第一个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)

1 个答案:

答案 0 :(得分:9)

您要求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

不要忘记测试它!