Functional Problem Solving (CSC 151 2015S) : EBoards

CSC151 2015S, Class 35: Geometric Art Through Numeric Recursion


Overview

Preliminaries

Admin

Upcoming Work

Extra Credit Opportunities

Academic

Peer Support (Afternoon Section)

Miscellaneous

Other Good Things (no extra credit)

Questions

Quick notes on named let

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]
             ...))))

Quiz

Lab