; cube-each: list of nums => list of nums (define (cube-each nums) (cond [(empty? nums) empty] [(cons? nums) (cons (* (first nums) (first nums) (first nums)) (cube-each (rest nums)))])) "Examples:" (cube-each (list 4 2 5 0 1)) "should be" (list 64 8 125 0 1) ; There could be a lot of very similar functions: cube-each, ; negate-each, add-1-to-each, etc. We'll abstract them all into ; the following more general function: ; do-to-each : function(X->Y) list-of-X => list-of-Y (define (do-to-each f nums) (cond [(empty? nums) empty] [(cons? nums) (cons (f (first nums)) (do-to-each f (rest nums)))])) "Examples of do-to-each:" (do-to-each sqr (list 4 3 8 -2 5)) "should be" (list 16 9 64 4 25) (do-to-each add1 (list 4 3 8 -2 5)) "should be" (list 5 4 9 -1 6) ; It works equally well on user-defined functions: (define (add17 x) (+ 17 x)) (do-to-each add17 (list 4 3 8 -2 5)) "should be" (list 21 20 25 15 22) ; And there's no reason the input list has to be numbers, rather than ; some other type: (do-to-each posn-x (list (make-posn 3 4) (make-posn 5 -2) (make-posn 0 1))) "should be" (list 3 5 0) ; Of course, it seems silly to define an "add17" function just so we can ; pass it into "do-to-each"; instead, we'll use "lambda" to create a ; function on the fly. (do-to-each (lambda (x) (+ x 17)) (list 4 3 8 -2 5)) "should be" (list 21 20 25 15 22) ; delete-if : function (X -> boolean) list-of-X => list-of-X (define (delete-if test? things) (cond [(empty? things) empty] [(cons? things) (cond [(test? (first things)) (delete-if test? (rest things))] [else (cons (first things) (delete-if test? (rest things)))])])) "Examples of delete-if:" (delete-if (lambda (x) (> x 0)) (list 4 0 -2 1 -6 0 -3 4)) "should be" (list 0 -2 -6 0 -3) ; I THOUGHT there was a "positive?" function built in, but apparently ; not. No matter; I can write one on the fly using "lambda". ; Just as a function can take in a function as a parameter, it can also ; return a function as its value: ; make-adder: num => function(num=>num) (define (make-adder what-to-add) (lambda (x) (+ x what-to-add))) "Examples of make-adder:" (make-adder 3) "is some function" ((make-adder 3) 5) "should be 8" (do-to-each (make-adder 3) (list 1 2 3)) "should be" (list 4 5 6) ; Or both: ; do-twice: function => function (define (do-twice f) (lambda (x) (f (f x)))) "Examples of do-twice:" ((do-twice add1) 5) "should be" 7 ; More generally,... ; iterate: function natural-number => function ; The resulting function applies the given function the given number of ; times. (define (iterate f n) (cond [(<= n 0) (lambda (x) x)] ; iterating 0 times gives the identity function [else (lambda (x) (f ((iterate f (- n 1)) x)))])) "Examples of iterate:" ((iterate add1 4) 5) "should be" 9 ((iterate sqr 3) 2) "should be" 256