schememaxcdr

How do I use a pair to find which of two functions will evaluate the largest value? Scheme


Basically there is a pair made up of two functions and the code has to take the pair input x to find the highest evaluation for x and print that evaluation.
I receive the error:

car: contract violation expected: pair? given: 4

define (max x)
   (lambda (x)     ;I wanted lambda to be the highest suitable function
 (if (> (car x) (cdr x))
        (car x)
        (cdr x))))

 (define one-function (lambda (x) (+ x 1)))
 (define second-function (lambda (x) (+ (* 2 x) 1)))  ;my two functions

((max (cons one-function second-function)) 4)  

Solution

  • And where are the functions being called? And you have two parameters called x, they must have different names. Try this:

    (define (max f)                     ; you must use a different parameter name
      (lambda (x)
        (if (> ((car f) x) ((cdr f) x)) ; actually call the functions
            ((car f) x)
            ((cdr f) x))))
    

    Now it'll work as expected:

    ((max (cons one-function second-function)) 4)
    => 9