returns the first n of list

半腔热情 提交于 2019-12-10 17:10:05

问题


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 '()))))

Examples:

(returns '(5 4 5 2 1) 2)
(5 4)

(returns '(5 4 5 2 1) 3)
(5 4 5)

回答1:


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

Don't forget to test it!



来源:https://stackoverflow.com/questions/14489520/returns-the-first-n-of-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!