Search code examples
functionschememap-functiondeviation

Map Function practice in Scheme


I am having trouble using a map function to return a list of the square of the deviation of a given set of numbers. I wrote my square-of-deviation function as follows, but I don't know how to map this. Is there a way to right my square-of-deviation function so that it doesn't take "l" as a parameter? If I wrote function like this then I would know how to map it.

(define (square-of-deviation l)
 (define (square-of-deviation-h n)
  (if (null? n)
   '()
   (cons (expt (- (car n) (average l)) 2) 
         (square-of-deviation-h (cdr n)))))
(square-of-deviation-h l))

I wrote a function that I could use to map, but it requires that I pass the same list twice when I test my code:

(define (square-of-deviation-2 l)
  (lambda (x) (expt (- x (average l)) 2)))

(map (square-of-deviation-2 '(1 2 3 4 5)) '(1 2 3 4 5))

Should I alter my map function here? I wrote it as follows:

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

Solution

  • Try this:

    (define lst '(1 2 3 4 5))
    
    (define avg (average lst))
    
    (define (square-of-deviation-2 x)
      (expt (- x avg) 2))
    
    (map square-of-deviation-2 lst)
    

    Notice that you only need to calculate the average once, so you can do it before calling map, because map's function only expects a single value, which is each of the input list's elements in turn. An even nicer solution would be to pack everything in a single function:

    (define (square-of-deviation lst)
      (let ((avg (average lst)))
        (map (lambda (x) (expt (- x avg) 2)) lst)))