4

如何返回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)
4

1 回答 1

12

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

不要忘记测试它!

于 2013-01-23T21:21:50.397 回答