Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

Tags:

list

scheme

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

like image 958
Noob Avatar asked Feb 23 '23 23:02

Noob


1 Answers

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).

like image 80
nimrodm Avatar answered Apr 30 '23 10:04

nimrodm