Functional Problem Solving (CSC 151 2015S) : EBoards
Primary: [Front Door] [Schedule] - [Academic Honesty] [Disabilities] [Email] - [FAQ] [Teaching & Learning] [Grading] [Taking Notes] [Rubric] - [Calendar]
Current: [Assignment] [EBoard am] [EBoard pm] [Lab] [Outline] [Reading]
Sections: [Assignments] [EBoards am] [EBoards pm] [Labs] [Outlines] [Readings] - [Examples] [Handouts]
Reference: [Setup] [VM] [Errors] - [Functions A-Z] [Functions By Topic] - [Racket] [Scheme Report (R5RS)] [R6RS] [TSPL4]
Related Courses: [Davis (2013F)] [Rebelsky (2014F)] [Weinman (2014F)]
Misc: [Submit Questions] - [SamR] [Glimmer Labs] [CS@Grinnell] [Grinnell] - [Book Office Hours] - [Issue Tracker (Course)]
Overview
Common mechanism for defining recursive functions with helpers. Example: Tally all the positive numbers in a list.
Example input: '(4 -1 2.3 -4)
First step, set up a table
tally remaining
----- ---------
0 '(4 -1 2.3 -4) ; first thing is positive
add 1 Throw away the first thing
1 '(-1 2.3 -4) ; First thing is negatve
do nothing Throw away the first thing
1 '(2.3 -4) ; First thing is postive
add 1 Throw away the first thing
2 '(-4) ; First thing is postive
...
Generalize. Suppose our input is lst.
tally remaining
----- ---------
0 lst
Using letrec
(define tally-positive
(lambda (lst)
(letrec ([kernel (lambda (tally remaining)
(cond
[(null? remaining)
tally]
[(positive? (car remaining))
...]
)_))
(kernel 0 lst))))
There's a huge gap between how we thought about it and how we have to express it. Solution? Redesign the language.
(define tally-positive
(lambda (lst)
(let kernel ([tally 0]
[remaining lst])
(cond
[(null? remaining)
tally]
...))))