Nefton
Nefton

Reputation: 25

How do you compare 3 arguments or more in racket?

I know that in Racket to compare for example two numbers you will have something like this.

  (define (myMax x y)
           (if (< x y) y x))

My question is how do you compare for a function with 3 arguments or more. For example to get the highest number from the arguments.

(define (myMax x y z)

Upvotes: 1

Views: 277

Answers (1)

Robert
Robert

Reputation: 2812

If you want to process an undefined number of elements, you need to work with list.

The idiomatic way is to use recursion to process the elements. Each function call need to process one element (car) and the rest of the list cdr.

You can find an implementation on a another post: https://stackoverflow.com/a/42463097/10953006

EDIT 1: EXAMPLE

(define (maximum L)
     (if (null? (cdr L)) 
         (car L) 
         (if (< (car L) (maximum (cdr L)))  
             (maximum (cdr L)) 
             (car L))))

(maximum '( 1 2 3 ))
(maximum '( 1 2 3 4))
(maximum '( 1 2 3 4 5))

Give the results:

3
4
5

EDIT 2: if the real question is about variable number of arguments in Racket, you could use the following notation:

(define (test-function . L)
  (printf "~S~%" L)) ;; Here: L is the list (1 2 3)

(test-function 1 2 3)

Which will display (printf):

(1 2 3)

Upvotes: 2

Related Questions