In: Computer Science
you are required to use only the functional features of Scheme; functions with an exclamation point in their names (e.g., set!) and input/output mechanisms other than load and the regular read-eval-print loop are not allowed. (You may find imperative features useful for debugging. That’s ok, but get them out of your code before you hand anything in.)
Write a function minMax that, given a list of integers, returns a tuple containing the smallest and largest element in the list. Just return (0 0) for the empty list. > (minMax (5 4 3 2 1)) (1 5)
using the programming language scheme
Code:
(define (minMax list)
(cond ((null? list) '(0 0)) ;;if list is empty returns (0 0)
(else (cons (min list) (cons (max list) '()))))) ;;else returns
list of min and max element
(define (min list) ;;Helper_Function returns minimum of a
list
(cond ((null? list) 0) ;;if list is empty returns 0
((null? (cdr list)) (car list)) ;;if list contains only one element
return that element
((> (car list) (cadr list)) (min (cdr list))) ;;if first element
is greater than second than check in rest of the list
(else (min (cons (car list) (cddr list)))))) ;;else check in the
list leaving second element and continue
(define (max list) ;;Helper_Function returns maximum of a
list
(cond ((null? list) 0) ;;if list is empty returns 0
((null? (cdr list)) (car list)) ;;if list contains only one element
return that element
((< (car list) (cadr list)) (max (cdr list))) ;;if first element
is less than second than check in rest of the list
(else (max (cons (car list) (cddr list)))))) ;;else check in the
list leaving second element and continue
Snapshot of Code and Output: