In: Computer Science
*****************PLEASE GIVE THE CODE IN RACKET PROGRAMMING ONLY AND MAKE SURE THE CODE RUNS ON WESCHEME IDE***************
Write a recursive Racket function "sum-diff" that takes two lists of integers that are the same length and evaluates to an integer. The resulting integer should be the sum of the absolute value of the differences between each pair of integers with the same index in the two lists. For example (sum-diff '(-1 -2 -3) '(1 2 3)) should evaluate to 12 because the absolute value of the differences between (-1 and 1), (-2 and 2) and (-3 and 3) are 2, 4, and 6, and 2+4+6=12. Note: (abs n) evaluates to the absolute value of n. Also, if the lists are empty the sum should be 0
Code:
#lang racket
(define (sum-diff lst1 lst2)
; if both lists are empty, then return 0
(cond ((and (null? lst1) (null? lst2)) 0)
; else return the sum of difference of first element in
lst1, first element in lst2 and return value of (sum-diff (cdr
lst1) (cdr lst2))
(else (+ (abs (- (car lst1) (car lst2))) (sum-diff (cdr lst1) (cdr
lst2))))
)
)
; testing sum-diff function
(sum-diff '(-1 -2 -3) '(1 2 3))
(sum-diff '() '())
(sum-diff '(-1 -2 -4 -5) '(1 2 4 5))
(sum-diff '(1 2 3 4) '(5 6 7 -8))
Code Screenshot and Output: