开发者

In a simple script to return the minimum of a list in scheme only the first value of the list is being returned by my solution. What's the bug?

开发者 https://www.devze.com 2023-03-10 09:14 出处:网络
(define (minim lst) (COND ((NULL? (CDR lst)) 开发者_C百科(CAR lst)) (< (CAR lst) (minim (CDR lst)) (CAR lst))
(define (minim lst)
  (COND
   ((NULL? (CDR lst)) 开发者_C百科(CAR lst))
   (< (CAR lst) (minim (CDR lst)) (CAR lst))
  (ELSE (minim (CDR lst))))
  )

(minim '(3 4 2 9 3 8)) 3

I've figured out that it is the second line that is being evaluated and returning the (CAR of any list). What am I missing?


You are missing parenthesis in the second condition. This makes the "<" operator operate over three elements rather than two. The correct code looks like:

(define (minim lst)
    (cond ((null? (cdr lst)) (car lst))
          ((< (car lst) (minim (cdr lst))) (car lst))
          (else (minim (cdr lst)))) )


(minim '(3 4 2 9 3 8)) 

One note though: This code is not tail recursive. It goes all the way to the end of the list and starts comparing from there (i.e., the last element is compared with the one before that and so on).

A more efficient implementation would compare the first element to the current minimum, then proceed forward processing a shorter list every time. If you go this way, you will need an additional function argument holding the current minimum (this is equivalent to a left fold rather than the right fold you have implemented).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号