;; squares each element in a list-of-numbers (define (square lon) (cond [(empty? lon) empty] [(cons? lon) (cons (* (first lon) (first lon)) (square (rest lon)))])) ;; removes the symbol 'junk from a list-of-symbols (define (removeJunk los) (cond [(empty? los) empty] [(cons? los) (cons (cond [(symbol=? 'junk (first los)) '__ ] [else (first los)]) (removeJunk (rest los)))])) ;; map: (f: any1 --> any2) list-of-any1 --> list-of-any2 ;; implementation of map (define (mapper f a-list) (cond [(empty? a-list) empty] [(cons? a-list) (cons (f (first a-list)) (map f (rest a-list)))])) "mapper test cases:" (equal? (square (list 1 2 3 4)) (mapper sqr (list 1 2 3 4))) (equal? (removeJunk (list 'a 'b 'junk 'c 'junk 'd)) (mapper (lambda (x) (cond [(symbol=? 'junk x) '__] [else x])) (list 'a 'b 'junk 'c 'junk 'd))) ;; sums a list-of-numbers (define (sum lon) (cond [(empty? lon) 0] [(cons? lon) (+ (first lon) (sum (rest lon)))])) ;; removes all the negative values from a list-of-nums (define (removeNeg lon) (cond [(empty? lon) empty] [(cons? lon) (cond [(> 0 (first lon)) (removeNeg (rest lon))] [else (cons (first lon) (removeNeg (rest lon)))])])) ;; foldRight: (f: any1 any2--> any2) any2 list-of-any1 --> any2 ;; Implementation of foldr (define (foldRight f base a-list) (cond [(empty? a-list) base] [(cons? a-list) (f (first a-list) (foldRight f base (rest a-list)))])) "foldRight test cases:" (equal? (sum (list 1 2 3 4 5)) (foldRight + 0 (list 1 2 3 4 5))) (equal? (removeNeg (list 1 -2 -3 4 -5)) (foldRight (lambda (x r) (cond [(> 0 x) r] [else (cons x r)])) empty (list 1 -2 -3 4 -5))) ;; revList: list-of-any --> list-of-any ;; reverses the elements of a list. (define (revList a-list) (cond [(empty? a-list) empty] [(cons? a-list) (local [(define (helper a-list acc) (cond [(empty? a-list) acc] [(cons? a-list) (helper (rest a-list) (cons (first a-list) acc))]))] (helper a-list empty))])) ;; findMax: non-empty-list-of-numbers --> number ;;find the maximum of a non-empty list of numbers (define (findMax nelon) (local [(define (helper a-list acc) (cond [(empty? a-list) acc] [(cons? a-list) (helper (rest a-list) (cond [(< (first a-list) acc) acc] [else (first a-list)]))]))] (helper nelon(first nelon)))) ;; foldLeft: (f: any1 any2 --> any2) any2 list-of-any1 --> any2 ;; Implementation of the built-in foldl (define (foldLeft f base a-list) (cond [(empty? a-list) base] [(cons? a-list) (local [(define (helper a-list acc) (cond [(empty? a-list) acc] [(cons? a-list) (helper (rest a-list) (f (first a-list) acc))]))] (helper a-list base))])) "foldLeft test cases:" (equal? (reverse (list 'a 'b 'c 'd 'e)) (foldLeft (lambda (x a) (cons x a)) empty (list 'a 'b 'c 'd 'e))) (define lon1 (list 2 -3 4 -5 -4 -3)) (equal? (findMax lon1) (foldLeft (lambda (x a) (cond [(< x a) a] [else x])) (first lon1) lon1))