Map Function practice in Scheme -


i having trouble using map function return list of square of deviation of given set of numbers. wrote square-of-deviation function follows, don't know how map this. there way right square-of-deviation function doesn't take "l" parameter? if wrote function know how 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 function use map, requires pass same list twice when test 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 alter map function here? wrote follows:

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

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 need calculate average once, can before calling map, because map's function expects single value, each of input list's elements in turn. nicer solution pack in single function:

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

Comments

Popular posts from this blog

c++ - CryptStringToBinary API behavior -

c++ - Correct method for redrawing a layered window -

java.util.scanner - How to read and add only numbers to array from a text file -