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

StackOverflow https://stackoverflow.com/questions/19215111

  •  30-06-2022
  •  | 
  •  

Question

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)  
Était-ce utile?

La 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
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top