University of California, Berkeley
EECS Department - Computer Science Division

CS3 Lecture 14 : Lambda

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


Overview of today's lecture


Answers to questions that have come up

Review


Lambda

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

: (let ((a 4)
        (b 5))
    (+ a b))
9

Name Conflicts : AVOID THEM!

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


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

Next Time

Puzzle : Baseball batting averages (as heard on CarTalk)

Game : Kayles [BerlekampConwayGuy82]

References


WWW Maven: Dan Garcia (ddgarcia@cs.berkeley.edu) Send me feedback

Dan Garcia Berkeley Computer Science