How to compare three arguments in Racket?

I know that you can compare two arguments in a Racket using (> 3 2)something like this. But what about three sets of numbers? you can use something like

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

For example?

thanks

+4
source share
2 answers

If you want to find a minimum of three numbers, do the following:

(min a b c)
+4
source

As a more general solution, you can use instead foldl, for example:

(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 make much more complex comparisons, since we can use any procedure that takes two arguments and returns only one of them.

Using a function of a higher order, we can generalize it even more:

(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)
0
source

Source: https://habr.com/ru/post/1626096/


All Articles