CS 227 Lecture -*- Outline -*- * Implicit Begin (6.3) Some more syntax to use with I/O. Back in section 2.5, we saw how to put in writeln statements using begin. (But in exercises 4.15 and 4.16, we put in writeln expressions without the begin. How did that work?) Scheme allows you to put in expressions that are called for side effects in the body of a lambda, let, letrec, and in the consequents and the alternatives of a cond. ** Syntax ------------------- IMPLICIT BEGIN explicit implicit (LAMBDA (x) (LAMBDA (x) (BEGIN (writeln x) (writeln x) (* x x)) (* x x))) (LET ((x 3)) (LET ((x 3)) (BEGIN (writeln x) (writeln x) (* x x)) (* x x))) (LETREC ((...)) (LETREC ((...)) (BEGIN (writeln x) (writeln x) (* x x)) (* x x))) (COND (COND ((null? ls) ((null? ls) (BEGIN (writeln x) (writeln x) (* x x)) (* x x))) (ELSE (ELSE (writeln y) (BEGIN (* y 2))) (writeln y) (* y 2)))) ----------------- The syntax allows you to omit the begin ** Examples try ((lambda (x y) (writeln x) (writeln y) (+ x y)) 3 4) and ((lambda (x y) (begin (writeln x) (writeln y) (+ x y))) 3 4) do example with cond watch out: the following is an infinite loop! shows a common misconception ** Pitfalls this doesn't change the functional nature of Scheme... ----------------- PITFALLS (define sum-up ; TYPE: (-> (integer integer) integer) (lambda (n acc) ; ENSURES: result is acc+1+...+n (cond ((zero? n) (writeln "done") acc) (else (writeln "add 1 to acc") (add1 acc) (writeln "sub 1 from n") (sub1 n) (sum-up n acc))))) ----------------- Q: what's wrong with that code? no implicit begin in an if! ----------------- (if #f (+ 3 4) (writeln "was false") (+ 10 1002)) ----------------- would have to use a begin here. (show the correct version)