University of California, Berkeley
EECS Department - Computer Science Division

CS3L OaW Lecture 9 : Lambda

(Thanks to Oliver Grillmeyer and Brendan Ferguson for many of the ideas in these notes)


Review

Administrivia

Lambda

Motivation

Introduction

Example : square (aka "The truth about define")

(define (square x)
  (* x x))
(define square 
  (lambda (x) (* x x)))
: square
==>
(        square         3 ) ;; ==>  9
( (lambda (x) (* x x))  3 ) ;; ==>  9

Using lambda with multiple (or no) arguments

: (lambda () 'cal)
#[procedure #x18F0794]
: ((lambda () 'cal))
cal
: ((lambda (a b) (+ a b)) 4 5)
9

The truth about let

Name Conflicts : AVOID THEM!

(define (foo x)
   (let ((x 3))
      (lambda (x)
         (+ x 5)))) ;; Which x do we mean?

Returning a procedure

: (define (make-bookender bookend)
      (lambda (w) (word bookend w bookend)))
make-bookender

: ((make-bookender 'o) 'hi)
ohio

: ((make-bookender 'to) 'n)
tonto
: (define to_to (make-bookender 'to))
to_to
: (to_to 'ron)
toronto
: (define (compose f g)
==>
: (define second 
==>

Lambda and Higher-Order Functions

Overview

: (define (square x) (* x x))
square

: (every square '(1 2 3 4))
(1 4 9 16)
: (every (lambda (x) (* x x)) '(1 2 3 4))
(1 4 9 16)
(define square (lambda (x) (* x x))).
(lambda (x) (* x x))

Example : add-1-to-sent

;; add-1-to-sent
;;
;; Example: (add-1-to-sent '(1 2 3)) ==> (2 3 4)

(define (add-1-to-sent S)
  (every add-1 S))

(define (add-1 num)
  (+ num 1))
(define (add-1-to-sent S)
==>

Example : add-n-to-sent

;; add-n-to-sent
;;
;; Example: (add-n-to-sent 5 '(1 2 3)) ==> (6 7 8)

(define (add-n-to-sent n S)
   (every ??? S))

;; What goes in the ??? -- let's try to find out.
(define (add-n-to-sent n S)
  (every add-n S))

(define (add-n num)
  (+ num n))   ; WRONG, why? ==>
(define (add-n n num)  ; I added a new parameter called n
  (+ n num))           ; ALSO WRONG, BUT FOR A DIFFERENT REASON
                       ; Why? ==>
(define (add-n-to-sent n L)
==>

Example : add-1-to-odds

;; Example:
;;
;; (add-1-to-odds '(1 out of 3 likes u 2 and u b 40))
;; ==> (2 out of 4 likes u 2 and u b 40)

: (define (add-1-to-odds S)
==>
==>
==>
==>

Example : all-letter-twister?

;; Example:
;;
;; (all-letter-twister? 'r '(rubber bumper baby buggy)) ==> #f
;; (all-letter-twister? 's '(six sheiks sixth sheeps sick)) ==> #t

: (define (all-letter-twister? letter S)
==>
==>
==>
==>


Summary

In Lab this week you'll see...

In Life this week you'll see...