Functional Problem Solving (CSC 151 2013F) : EBoards

CSC 151, Review Session with SamR, Week 6


Things to talk about

What's on the quiz?

Let's talk about Let

Form

(let ([NAME EXP]
      [NAME EXP])
   EXP
   EXP
   EXP)

Meaning

Simple example

(let ([x 2]) (* x x))

Complication

(+ (let ([x 2]) (* x x)) x)

Sample interaction

> (let ([x 2]) (* x x))
4
> (+ (let ([x 2]) (* x x)) x)
. . reference to an identifier before its definition: x
> (begin 2 3)
3
> (+ (begin (define x 2) (* x x)) x)
. define: not allowed in an expression context in: (define x 2)

Another example

DEFINITIONS
(define x 3)
(let ([x 2]) (* x x))

OUTPUT
4

And another

DEFINITIONS
(define x 3)
(+ (let ([x 2]) (* x x)) x)

OUTPUT
7

More complicated

DEFINITIONS
(let ([x 2]
      [y (* x x)])
        (+ x y))

OUTPUT
boom!

More complicated

DEFINITIONS

(define x 3)
(let ([x 2]
      [y (* x x)])
        (+ x y))

INTERACTIONS
11

And more

DEFINITIONS
(define x 3)
(let* ([x 2]
       [y (* x x)])
         (+ x y))

INTERACTIONS
6

Let's talk about for-each

    (repeat N PROCEDURE PARAMETER1 PARAMETER2 ...)
    (map PROCEDURE LIST1 LIST2 ...)
    (for-each PROCEDURE LIST1 LIST2 ...)

Code written on the fly

     (define yertle (turtle-new salamasond))

     (repeat 15
             (lambda (turtle)
                (turtle-forward! turtle 1)
                (turtle-set-color! turtle (rgb-darker (turtle-get-color turtle))))
             yertle)

     (define yertle (turtle-new salamasond))
     (for-each
      (lambda (color)
        (turtle-forward! yertle 1)
        (turtle-set-color! yertle color))
      (list color1 color2 ... color15))

Code after testing in DrRacket (and then a failed cut-and-paste)

#lang racket
(require gigls/unsafe)

 (define turtle-get-color
   (lambda (turtle)
     (turtle ':color)))

(define salamasond (image-show (image-new 200 200)))
(define yertle (turtle-new salamasond))

(turtle-teleport! yertle 100 100)
(for-each
 (lambda (color)
   (turtle-forward! yertle 3)
   (turtle-set-color! yertle color))
 (list "blue" "pink" "red" "orange" "maroon"
       "green" "blue" "indigo" "violet"
       "black" "yellow" "purple" "blue"
       "pink" "grey" "gray" "black"))

(turtle-teleport! yertle 100 130)
(turtle-set-color! yertle (rgb-new 255 128 128))
(repeat 15
        (lambda (turtle)
           (turtle-forward! turtle 5)
           (turtle-set-color! turtle (rgb-darker (turtle-get-color turtle))))
        yertle)

Samuel A. Rebelsky, rebelsky@grinnell.edu

Copyright (c) 2007-2013 Janet Davis, Samuel A. Rebelsky, and Jerod Weinman. (Selected materials are copyright by John David Stone or Henry Walker and are used with permission.)

Creative Commons License

This work is licensed under a Creative Commons Attribution 3.0 Unported License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc/3.0/ or send a letter to Creative Commons, 543 Howard Street, 5th Floor, San Francisco, California, 94105, USA.