#lang racket ;; CSE 413 Au12 lecture 5 sample code ;; Two definitions of fibonocci - without and with tail recursion (define (fib n) (if (< n 2) n (+ (fib (- n 1)) (fib (- n 2))))) (define (fibt n) (if (< n 2) n (fibaux (- n 1) 1 0))) ;; Return the nth fibonacci past curr, where curr is the current number ;; in the sequence and prev is the one before that (define (fibaux n curr prev) (if (= n 0) curr (fibaux (- n 1) (+ curr prev) curr))) ;; Recursion patterns ;; Augmenting recursion - build answer a bit at a time ;; n! (define (fact n) (if (< n 2) 1 (* n (fact (- n 1))))) ;; append (define (app lst1 lst2) (if (null? lst1) lst2 (cons (car lst1) (app (cdr lst1) lst2)))) ;; map is a kind of augmenting function ;; return new list that contains old elements incremented by 1 (define (incr-each lst) (if (null? lst) '() (cons (+ 1 (car lst)) (incr-each (cdr lst))))) ;; return new list that contains double each of elements in old list (define (dbl-each lst) (if (null? lst) '() (cons (* 2 (car lst)) (dbl-each (cdr lst))))) ;; return new list whose elements are (f old-elements) ;; (higher-order function that factors out the common code from incr-each and dbl-each (define (map-each func lst) (if (null? lst) '() (cons (func (car lst)) (map-each func (cdr lst))))) (define (dbl n) (* 2 n)) (define (incr n) (+ 1 n)) ;; now (map-each dbl lst) is the same as (dbl-each lst) and (map-each incr lst) ;; does the same thing as (incr-each lst). Can also use an anonymous function ;; value, e.g. (map-each (lambda (n) (+ n 1)) lst) ;; reduce function - reduce the elements of list to an answer ;; sum elements of the list (define (sum-list lst) (if (null? lst) 0 (+ (car lst) (sum-list (cdr lst))))) ;; product of the elements of the list (define (prod-list lst) (if (null? lst) 1 (* (car lst) (prod-list (cdr lst))))) ;; filter function - return a new list that is a subset of the original ;; return new list containing all positive elements of the original list (define (pos-elements lst) (if (null? lst) '() (if (> (car lst) 0) (cons (car lst) (pos-elements (cdr lst))) (pos-elements (cdr lst)))))