你会如何使用'accumulate'来编写'last'函数?

时间:2013-01-29 19:02:44

标签: scheme

我一直在研究sicp并尝试使用accumulate编写'last'函数

(define (accumulate f x xs)
  (if (null? xs)
      x
      (f (car xs)
         (accumulate f x (cdr xs)))))

 (last '(1 2 3 4 5)) ;;=> (5)

我尝试了这个,但它不起作用

 (define (last seq)
   (accumulate (lambda (x y) x)
               '()
               seq))

1 个答案:

答案 0 :(得分:2)

试试这个:

(define (last lst)
  (accumulate (lambda (x y)
                (if (null? y)
                    (cons x y)
                    y))
              '() lst))
相关问题