Krin
Krin

Reputation: 51

How to compare three arguments in Racket?

I know that you can compare two arguments in Racket using (> 3 2) something like that. But how about three number sets? can you use something like

(define smallest-of-three
  (lambda (a b c)
   (cond (and (> a b) (> a c))a)))

For example?

Thank you

Upvotes: 4

Views: 674

Answers (2)

eestrada
eestrada

Reputation: 1603

As a more general solution, you could instead use foldl, like this:

(foldl (lambda (a b)        ;; our comparison function
         (if (< a b) a b))
       a                    ;; our initial value
       (list b c))          ;; the rest of our values

Now we can do much more complicated comparisons, since we can use any procedure that takes two arguments and only returns one of them.

Using a higher order function, we can generalize this even further:

(define (compare-multiple comp-func)
  (lambda (first . rest)
    (foldl comp-func    ;; our comparison function
           first        ;; our initial value
           rest)))      ;; the rest of our values

 ;; I want to make my own min function
 (define my-min (compare-multiple (lambda (a b) (if (< a b) a b)))

 ;; result is 1
 (my-min 42 1 45)

Upvotes: 0

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 236004

If you want to find the minimum of three numbers do this:

(min a b c)

Upvotes: 4

Related Questions