Functional Problem Solving (CSC 151 2016S) : Outlines

Outline 25: Recursion Basics


Held: Monday, 7 March 2016

Back to Outline 24 - Characters and Strings. On to Outline 26 - Recursion Basics, Continued.

Summary

We begin our exploration of recursion, the most general form of repetition available in Scheme. You can use recursion to both build and iterate over different kinds of values.

Related Pages

Overview

Administrivia

Reminders

Upcoming Work:

Extra Credit

Academic / Artistic

Peer

Regular Peer

Misc

Far in the Future

No Extra Credit, But Still Good

Repetition

Some Challenges

Recursion

Recursion in Scheme

Remember that I tend to think in abstractions first. But we'll look at some concrete forms, too.

Here's the form of a typical recursive procedure:

(define PROC
  (lambda (VAL)
    (if (BASE-CASE-TEST)
        (COMPUTE-BASE-CASE VAL)
        (COMBINE (EXTRACT-DATA VAL)
                 (PROC (SIMPLIFY VAL))))))

When the value you're working with is a list and your base case is the null list, the form is somewhat simpler:

(define PROC
  (lambda (LST)
    (if (null? LST)
        NULL-CASE
        (COMBINE (EXTRACT-DATA (car LST))
                 (PROC (cdr LST))))))

Sometimes it's useful to grab the recursive result first, particularly if you're going to use it in multiple ways.

(define PROC
  (lambda (LST)
    (if (null? LST)
        NULL-CASE
        (let ((recursive-result (PROC (cdr LST))))
          (if (TEST)
              (COMBINE-1 (EXTRACT-DATA-1 (car LST)) recursive-result)
              (COMBINE-2 (EXTRACT_DATA-2 (car LST)) recursive-result))))))

Lab