Friday, December 18, 2009

My maximum and minimum procedure in scheme

Scheme comes with two built-in procedures to get the maximum and minimum of a given set of numbers. The documentation explains the procedures as below:


(max x ...+) → real?
x : real?
Returns the largest of the xs, or +nan.0 if any x is +nan.0. If any x is inexact, the result is coerced to inexact.

Examples:
> (max 1 3 2)

3
> (max 1 3 2.0)

3.0
(min x ...+) → real?
x : real?
Returns the smallest of the xs, or +nan.0 if any x is +nan.0. If any x is inexact, the result is coerced to inexact.

Examples:
> (min 1 3 2)

1
> (min 1 3 2.0)

1.0

My own implementations of max and min also work in the same way, including that fact that (max 1) will return 1 instead of an error that only one number is given. The code for max and min are the same except for the signs.

(define (mymin x . lst)
(define (myleast lst6 last)
(if (null? (cdr (if (pair? lst6) lst6 (list lst6)))) last
(if (<> last (car(cdr lst6))) (myleast (cdr lst6) last) (myleast (cdr lst6) (car (cdr lst6))))))
(myleast lst x))

(mymax 2 3 4 5 6 1)

These procedure demonstrate the simple concept of sending 1 or more arguments to a scheme procedure. The arguments come into the procedure in the form of a list. The operator "." does the trick.

No comments: