Functional Programming; Scheme




CS152

Chris Pollett

Apr. 6, 2009

Outline

Functional Programming

More Functional Programming

What about loops?

How can you do looping if you have a pure functional programming language?

for(int i=0; i <10; i++) {/*do something */}
Seems to require variables; however, we can replace it with recursion:
void my_for(int i, int stop, int step) {
    if ( i < stop) { /* do something */ 
        my_for(i+ step, stop, step)
    }
}
my_for(0, 10, 1);

More on Pure Functional Programming

Couldn't we just use C and write programs in a functional way?

Quiz

Which of the following statements is true?

  1. To handle method calls in Objective-C, the gcc compiler outputs calls to the msgSend procedure.
  2. g++ uses special object-oriented machine code instructions when compiling C++.
  3. gcc during compilation handles the OO features of C++ and Objective-C in the same fashion.

Scheme

Syntax of Scheme

Expressions and Evaluation

42   - a number
"hello" - a string
#t - a Boolean true
#\a - the character 'a'
(2.1 2.2 3.1) - a list of numbers
a - an identifier
hello - another identifier
(+ 2 3) - a list consisting of the identifier "+" and two numbers
(* (+ 2 3) (- 4 3) ) - a list consisting of an identifier and two lists

To evaluate expressions we use the rules:

  1. Constant atoms evaluate to themselves
  2. Identifiers are looked up in the current environment and replaced by the value found there
  3. A list is evaluated by first evaluating each of its elements. The first element in the list must evaluate to a function. This function is then applied to each of the remaining arguments.

More on Evaluation

Conditionals in Scheme

let

Adding things to the Scheme Environment

The define function can be used to add new associations between names and values in Scheme:

(define a 2)
(define emptylist '())
(define (sum lo hi) ; could write: sum (lambda (lo hi) ...
    (if (= lo hi)
         lo
         (+ lo (sum (+ lo 1) hi))) )

Once something has been define can see its value are scheme prompt

>(sum 3 5)
12