Background
Recursion
- Corequisites
- tests
- Fill in the missing expression for the recursive case of the factorial function
#lang racket
(define (fact n)
(cond
[(zero? n) 1]
[else ]))
(module+ test
(require rackunit)
(check-equal? (fact 10) 3628800))
- Use the debugger to find the bug in the following program
#lang racket
(define (list-length list)
(if (empty? list)
0
(+ 1 (list-length list))))
(module+ test
(require rackunit)
(define test-list '(1 2 3))
(check-equal? (length test-list) (list-length test-list)))
The first / rest pattern
- Prerequisites
- quick
Section 2.3.2 of the Racket Guide gives several examples of recursively traversing a list, in particular
(define (my-map f lst)
(cond
[(empty? lst) empty]
[else (cons (f (first lst))
(my-map f (rest lst)))]))
This function uses a very important pattern, processing the first
element of the list with first
and recursively processing the
remaining elements with rest
. In this part of the lab you use this
example as a starting point to rewrite the rainbow
example from
quick to use explicit recursion (i.e. calling first
and rest
),
rather calling than map.
- Make an auxilary function
color-mapper
that takes two parametersp
andcolor-list
and calls(colorize p color)
for each elementcolor
ofcolor-list
. - Your function can steal the structure of
my-map
but you shouldn't call
map
ormy-map
- If you have extra time, repeat the exercise with
for/list
instead offirst
andrest
.