Finish Types; Functional Programming, Scheme




CS152

Chris Pollett

Nov 8, 2021

Outline

Introduction

Type Compatibility

Type Inference

More on Type Inference

Type Checking

Quiz

Which of the following statements is true?

  1. Given two values, type compatibility is the problem of determining if they are of the same type using the type systems rules.
  2. Polymorphisms refers to code that is designed to work with multiple kinds of types.
  3. If two types are equivalent via structural equivalences, they will be equivalent via name equivalence.

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?

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          

Loading a File in Scheme