Search code examples
functional-programmingschememit-scheme

Scheme parentheses


Could anyone help me spot what is wrong in the following way of finding a min and a max in a list and returning them as a list? It should be working logically. I suppose there's something wrong with the parentheses.

(define (find-min-and-max my-list)
    (find-min-max-rec (car my-list) (car my-list) my-list)
)

(define (find-min-max-rec smallest largest ls)
    (if (null? ls)
        (list smallest largest)
    )
    (cond 
        ((and (< smallest (car ls)) (> largest (car ls)) ) (find-min-max-rec (car ls) (car ls) (cdr ls)))
        ((< smallest (car ls)) (find-min-max-rec (car ls) largest (cdr ls)))
        ((> largest (car ls)) (find-min-max-rec smallest (car ls) (cdr ls)))
        (else (find-min-max-rec smallest largest (cdr ls)))
    )
)

(display (find-min-and-max '(1 2 3 4)))

Console output

*** ERROR: pair required, but got ()
    While loading "./jdoodle.sc" at line 17
Stack Trace:
_______________________________________
  0  (car ls)
        at "./jdoodle.sc":10
  1  (find-min-and-max '(1 2 3 4))
        at "./jdoodle.sc":17
Command exited with non-zero status 70

Expected

(1 4)

In addition, is there any debugging tool that you would recommend using?

Note: I have been running my code in here: https://www.jdoodle.com/execute-scheme-online


Solution

  • Yep, actually you're right. There's something wrong with the parentheses.

    Here's a clue: What does this evaluate to?

    (define (f x)
      (if (< x 5) 10)
      12)
    
    (f 3)
    

    Why?