Home:ALL Converter>(Scheme) Using custom map and reduce, find minimum value in a list

(Scheme) Using custom map and reduce, find minimum value in a list

Ask Time:2015-11-15T10:59:01         Author:Vylic

Json Formatter

I need to use the 2 functions below to find out the minimum value in a list after squaring every element.

For example: (minSquare '(10 -2 5 9 -11) should print out 4.


map and reduce code:

(define map
  (lambda (f l)
    (if (null? l)
        '()
        (cons (f (car l)) (map f (cdr l))))))

(define reduce
  (lambda (op l id)
    (if (null? l)
        id
        (op (car l) (reduce op (cdr l) id)))))

I tried this:

(define minSquare
  (lambda (x)
    (cond [(null? x) '()]
          [else (map minSquare (reduce * x (car x))) (minSquare (cdr x))])))

But that passes all the numbers in the list multiplied by their squares to map then crashes giving a contract violation. I'm not sure how to use those two functions.

If someone can guide me through it (not give the answer), I would greatly appreciate it!

NOTE: I can't modify map or reduce.

Author:Vylic,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/33715920/scheme-using-custom-map-and-reduce-find-minimum-value-in-a-list
yy