方案。递归?

时间:2010-04-24 14:43:50

标签: scheme tail-recursion

下面提到的伪代码的任何尾递归版本?谢谢!

(define (min list)
  (cond 
   ((null? list) '())
   ((null? (cdr list)) (car list))
   (#t (let ((a (car list))
             (b (min (cdr list))))
         (if (< b a) b a)))))

5 个答案:

答案 0 :(得分:2)

您应该阅读fold higher-order functions

答案 1 :(得分:1)

定义一个辅助函数,它接受一个列表和到目前为止找到的最小元素(让我们称之为b)。如果列表为空,则应返回b,否则如果列表的头部(a)小于b,则应返回(helper (cdr list) a),否则为(helper (cdr list) b)。现在我们可以将(min list)定义为(helper (cdr list) (car list))

答案 2 :(得分:1)

 (define (min list)
  (let imin ((l (cdr list))
         (m (car list)))
    (cond
     ((null? l) m)
     (else
      (let ((a (car l)))
        (imin (cdr l)
              (if (< a m) a m)))))))

答案 3 :(得分:0)

(define (min ns)
  (let loop ( (ns-left ns) (min-so-far maxint) )
    (if (null? ns-left)
      min-so-far
      (loop
        (cdr ns-left)
        (if (< (car ns-left) min-so-far)
          (car ns-left)
          min-so-far )))))

答案 4 :(得分:0)

(define (min list)
   (min-helper list #f))

(define (min-helper list min-so-far)
   (if (null? list) 
       min-so-far
       (let ((m (car list)))
            (if (eq? min-so-far #f)
                (set! min-so-far m))
            (if (< m min-so-far)
                (min-helper (cdr list) m)
                (min-helper (cdr list) min-so-far)))))