;; The first three lines of this file were inserted by DrScheme. They record metadata ;; about the language level of this file in a form that our tools can easily process. #reader(lib "reader.ss" "plai" "lang") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Creating an anonymous procedure: (lambda (x y) (+ x y 10)) ;; Expanding the DEFINE sytactic sugar: (define (ex1 x y) (+ x y 10)) ; is the same as: (define ex2 (lambda (x y) (+ x y 10))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Defining map1 (a simplified version of the built-in map procedure) (define (map1 proc L) (if (null? L) ; Base case: return the empty list '() ; Recursive case: apply the proc to the first element ; of the list, and then construct a list of that and ; map1 of the rest of the list (cons (proc (first L)) (map1 proc (rest L))))) (map1 (lambda (x) (< x 4)) '(1 2 3 4 5 6)) (map1 (lambda (x) (+ x 1)) '(1 2 3 4 5 6)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Our own version of foldr: ; proc is a procedure that combines two elements ; base-case is what you want the last element combined with ; processes from right-to-left (define (fold proc base-case L) (if (null? L) base-case (proc (first L) (fold proc base-case (rest L))))) (fold + 0 '(1 2 3 4 5 6)) (fold (lambda (x b) (or b (> x 5))) #f '(1 7 2 3 4)) (fold (lambda (x b) (or b (> x 5))) #f '(1 0 2 3 4)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Applies proc n times to val (define (repeat n proc val) (if (<= n 0) val (repeat (- n 1) proc (proc val)))) ;; Examples: (repeat 10 (lambda (x) (+ x 1)) 0) (repeat 10 (lambda (x) (cons 'hi x)) '()) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; A constant used below (define h 0.00001) ;; Definition of a derivative: ;; ;; df(x)/dx = (f(x + h) - f(x - h)) / 2h ;; (define (d/dx f) (lambda (x) (/ (- (f (+ x h)) (f (- x h))) (* 2 h)))) ;; A simple function, f(x) = x^2 (define (f x) (* x x)) ;; Sample of applying our simple function: ;; f(x) = x^2 ;; f(3) = 3^2 = 9 (f 3) ;; Taking the derivative of our function and applying it: ;; df(x)/dx = 2x ;; df(3)/dx = 6 ((d/dx f) 3) ;; Taking the 2nd derivative of our function and applying it: ;; d^2 f(x) / dx^2 = 2 ;; d^2 f(3) / dx^2 = 2 ((d/dx (d/dx f)) 3)