You are on page 1of 636

How To Design programs

How to Design Programs


An Introduction to Computing and Programming Matthias Felleisen Robert Bruce Findler Matthew Flatt Shriram rishnamurthi
The MIT Press Cambridge! Massachusetts "ondon! #ngland

Cop$right % &''( Massachusetts Institute o) Technolog$ Illustrations % &''' Torre$ But*er All rights reser+ed, -o part o) this boo. ma$ be reproduced in an$ )orm b$ an$ electronic or mechanical means /including photoco$ing! recording! or in)ormation storage and retrie+al0 without permision in writing )rom the publisher, This 1eb tree is the publisher2endorsed! on2line +ersion o) the boo., 3ou ma$ purchase a paper cop$ directl$ )rom MIT Press or an$ other boo.store,

Last modified: Wednesday, September 24th, 2003 US/Eastern Contents

I Processing Simple Forms of Data 1 Students, Teachers, and Computers 2 Numbers, E pressions, Simple Programs &,( -umbers and Arithmetic &,& 4ariables and Programs &,5 1ord Problems &,6 #rrors &,7 Designing Programs ! Programs are Function Plus "ariable Definitions 5,( Composing Functions 5,& 4ariable De)initions 5,5 Finger #8ercises on Composing Functions # Conditional E pressions and Functions 6,( Booleans and Relations 6,& Functions that Test Conditions 6,5 Conditionals and Conditional Functions 6,6 Designing Conditional Functions $ S%mbolic Information 7,( Finger #8ercises with S$mbols & Compound Data, Part 1' Structures 9,( Structures 9,& #8tended #8ercise: Drawing Simple Pictures 9,5 Structure De)initions 9,6 Data De)initions 9,7 Designing Functions )or Compound Data 9,9 #8tended #8ercise: Mo+ing Circles and Rectangles 9,; #8tended #8ercise: Hangman ( The "arieties of Data ;,( Mi8ing and Distinguishing Data ;,& Designing Functions )or Mi8ed Data ;,5 Composing Functions! Re+isited ;,6 #8tended #8ercise: Mo+ing Shapes ;,7 Input #rrors

) Interme**o 1' S%nta and Semantics <,( The Scheme 4ocabular$ <,& The Scheme =rammar <,5 The Meaning o) Scheme <,6 #rrors <,7 Boolean #8pressions <,9 4ariable De)initions <,; Structure De)initions II Processing +rbitraril% ,arge Data - Compound Data, Part 2' ,ists >,( "ists >,& Data De)initions )or "ists o) Arbitrar$ "ength >,5 Processing "ists o) Arbitrar$ "ength >,6 Designing Functions )or Sel)2Re)erential Data De)initions >,7 More on Processing Simple "ists 1. /ore on Processing ,ists (',( Functions that Produce "ists (',& "ists that Contain Structures (',5 #8tended #8ercise: Mo+ing Pictures 11 Natural Numbers ((,( De)ining -atural -umbers ((,& Processing -atural -umbers o) Arbitrar$ Si*e ((,5 #8tended #8ercise: Creating "ists! Testing Functions ((,6 Alternati+e Data De)initions )or -atural -umbers ((,7 More on the -ature o) -atural -umbers 12 Composing Functions, 0e1isited +gain (&,( Designing Comple8 Programs (&,& Recursi+e Au8iliar$ Functions (&,5 =enerali*ing Problems! =enerali*ing Functions (&,6 #8tended #8ercise: Rearranging 1ords 1! Interme**o 2' ,ist +bbre1iations III /ore on Processing +rbitraril% ,arge Data 1# /ore Self2referential Data Definitions (6,( Structures in Structures

(6,& #8tended #8ercise: Binar$ Search Trees (6,5 "ists in "ists (6,6 #8tended #8ercise: #+aluating Scheme 1$ /utuall% 0eferential Data Definitions (7,( "ists o) Structures! "ists in Structures (7,& Designing Functions )or Mutuall$ Re)erential De)initions (7,5 #8tended #8ercise: More on 1eb Pages 1& De1elopment through Iterati1e 0efinement (9,( Data Anal$sis (9,& De)ining Data Classes and Re)ining Them (9,5 Re)ining Functions and Programs 1( Processing T3o Comple Pieces of Data (;,( Processing Two "ists Simultaneousl$: Case ( (;,& Processing Two "ists Simultaneousl$: Case & (;,5 Processing Two "ists Simultaneousl$: Case 5 (;,6 Function Simpli)ication (;,7 Designing Functions that Consume Two Comple8 Inputs (;,9 #8ercises on Processing Two Comple8 Inputs (;,; #8tended #8ercise: #+aluating Scheme! Part & (;,< #?ualit$ and Testing 1) Interme**o !' ,ocal Definitions and ,e ical Scope (<,( @rgani*ing Programs with local (<,& "e8ical Scope and Bloc. Structure I" +bstracting Designs 1- Similarities in Definitions (>,( Similarities in Functions (>,& Similarities in Data De)initions 2. Functions are "alues &',( S$nta8 and Semantics &',& Contracts )or Abstract and Pol$morphic Functions 21 Designing +bstractions from E amples &(,( Abstracting )rom #8amples &(,& Finger #8ercises with Abstract "ist Functions &(,5 Abstraction and a Single Point o) Control

&(,6 #8tended #8ercise: Mo+ing Pictures! Again &(,7 -ote: Designing Abstractions )rom Templates 22 Designing +bstractions 3ith First2Class Functions &&,( Functions that Produce Functions &&,& Designing Abstractions with Functions2as24alues &&,5 A First "oo. at =raphical Aser Inter)aces 2! /athematical E amples &5,( Se?uences and Series &5,& Arithmetic Se?uences and Series &5,5 =eometric Se?uences and Series &5,6 The Area Ander a Function &5,7 The Slope o) a Function 2# Interme**o #' Defining Functions on the Fl% " 4enerati1e 0ecursion 2$ + Ne3 Form of 0ecursion &7,( Modeling a Ball on a Table &7,& Sorting Buic.l$ 2& Designing +lgorithms &9,( Termination &9,& Structural +ersus =enerati+e Recursion &9,5 Ma.ing Choices 2( "ariations on a Theme &;,( Fractals &;,& From Files to "ines! )rom "ists to "ists o) "ists &;,5 Binar$ Search &;,6 -ewtonCs Method &;,7 #8tended #8ercise: =aussian #limination 2) +lgorithms that 5ac6trac6 &<,( Tra+ersing =raphs &<,& #8tended #8ercise: Chec.ing /on0 Bueens 2- Interme**o $' The Cost of Computing and "ectors &>,( Concrete Time! Abstract Time

&>,& The De)inition o) DDon the @rder o)CC &>,5 A First "oo. at 4ectors "I +ccumulating 7no3ledge !. The ,oss of 7no3ledge 5',( A Problem with Structural Processing 5',& A Problem with =enerati+e Recursion !1 Designing +ccumulator2St%le Functions 5(,( Recogni*ing the -eed )or an Accumulator 5(,& Accumulator2St$le Functions 5(,5 Trans)orming Functions into Accumulator2St$le !2 /ore 8ses of +ccumulation 5&,( #8tended #8ercise: Accumulators on Trees 5&,& #8tended #8ercise: Missionaries and Cannibals 5&,5 #8tended #8ercise: Board Solitaire !! Interme**o &' The Nature of Ine act Numbers 55,( Fi8ed2si*e -umber Arithmetic 55,& @+er)low 55,5 Ander)low 55,6 DrSchemeCs -umbers "II Changing the State of "ariables !# /emor% for Functions !$ +ssignment to "ariables 57,( Simple Assignments at 1or. 57,& Se?uencing #8pression #+aluations 57,5 Assignments and Functions 57,6 A First Ase)ul #8ample !& Designing Functions 3ith /emor% 59,( The -eed )or Memor$ 59,& Memor$ and State 4ariables 59,5 Functions that Initiali*e Memor$ 59,6 Functions that Change Memor$

!( E amples of /emor% 8sage 5;,( Initiali*ing State 5;,& State Changes )rom Aser Interactions 5;,5 State Changes )rom Recursion 5;,6 Finger #8ercises on State Changes 5;,7 #8tended #8ercise: #8ploring Places !) Interme**o (' The Final S%nta and Semantics 5<,( The 4ocabular$ o) Ad+anced Scheme 5<,& The =rammar o) Ad+anced Scheme 5<,5 The Meaning o) Ad+anced Scheme 5<,6 #rrors in Ad+anced Scheme "III Changing Compound "alues !- Encapsulation 5>,( Abstracting with State 4ariables 5>,& Practice with #ncapsulation #. /utable Structures 6',( Structures )rom Functions 6',& Mutable Functional Structures 6',5 Mutable Structures 6',6 Mutable 4ectors 6',7 Changing 4ariables! Changing Structures #1 Designing Functions that Change Structures 6(,( 1h$ Mutate Structures 6(,& Structural Design Recipes and Mutation! Part ( 6(,5 Structural Design Recipes and Mutation! Part & 6(,6 #8tended #8ercise: Mo+ing Pictures! a "ast Time #2 E9ualit% 6&,( #8tensional #?ualit$ 6&,& Intensional #?ualit$ #! Changing Structures, "ectors, and :b;ects 65,( More Practice with 4ectors 65,& Collections o) Structures with C$cles 65,5 Bac.trac.ing with State HTML conversion by TeX2page 2003-09-19

Preface
It goes against the grain of modern ed cation to teach chi!dren to program" #hat f n is there in ma$ing p!ans% ac& iring discip!ine in organi'ing tho ghts% devoting attention to detai! and !earning to be se!f-critica!( 22 Alan Perlis! )pigrams in *rogramming Man$ pro)essions re?uire some )orm o) computer programming, Accountants program spreadsheets and word processorsE photographers program photo editorsE musicians program s$nthesi*ersE and pro)essional programmers instruct plain computers, Programming has become a re?uired s.ill, 3et programming is more than Fust a +ocational s.ill, Indeed! good programming is a )un acti+it$! a creati+e outlet! and a wa$ to e8press abstract ideas in a tangible )orm, And designing programs teaches a +ariet$ o) s.ills that are important in all .inds o) pro)essions: critical reading! anal$tical thin.ing! creati+e s$nthesis! and attention to detail, 1e there)ore belie+e that the stud$ o) program design deser+es the same central role in general education as mathematics and #nglish, @r! put more succinctl$! e1er%one should learn ho3 to design programs< @n one hand! program design teaches the same anal$tical s.ills as mathematics, But! unli.e mathematics! wor.ing with programs is an acti+e approach to learning, Interacting with so)tware pro+ides immediate )eedbac. and thus leads to e8ploration! e8perimentation! and sel)2e+aluation, Furthermore! designing programs produces use)ul and )un things! which +astl$ increases the sense o) accomplishment when compared to drill e8ercises in mathematics, @n the other hand! program design teaches the same anal$tical reading and writing s.ills as #nglish, #+en the smallest programming tas.s are )ormulated as word problems, 1ithout critical reading s.ills! a student cannot design programs that match the speci)ication, Con+ersel$! good program design methods )orce a student to articulate thoughts about programs in proper #nglish,

The Design 0ecipe for Functions Problem Anal$sis G Data De)inition Contract! Purpose G #))ect Statements! Header #8amples Function Template Function De)inition Tests
Figure 1' The basic steps o) a program design recipe This boo. is the )irst boo. on programming as the core subFect o) a liberal arts education, Its main )ocus is the design process that leads )rom problem statements to well2organi*ed solutionsE it deemphasi*es the stud$ o) programming language details! algorithmic minutiae! and speci)ic application domains, @ur desire to )ocus on the design process re?uires two radical inno+ations )or introductor$ courses, The )irst inno+ation is a set o) e+p!icit design g ide!ines, #8isting curricula tend to pro+ide +ague and ill2de)ined suggestions! such as DDdesign )rom top to bottomCC or DDma.e the program structural,CC 1e ha+e instead de+eloped design guidelines that lead students )rom a problem statement to a computational solution in step2b$2step )ashion with well2de)ined intermediate products, In the process the$ learn to read! to anal$*e! to organi*e! to e8periment! to thin. in a s$stematic manner, The second inno+ation is a radicall$ new programming en+ironment, In the past! te8ts on programming ignored the role o) the programming en+ironment in the learning processE the$ simpl$ assumed that students had access to a pro)essional en+ironment, This boo. pro+ides a programming environment for beginners, It also grows with the students as the$ master more and more o) the material until it supports a )ull2)ledged language )or the whole spectrum o) programming tas.s: large2scale programming as well as scripting, @ur guidelines are )ormulated as a number o) program design recipes,( A design recipe guides a beginning programmer through the entire problem2sol+ing process, 1ith design recipes! a beginner almost ne+er again stares at a blan. piece o) paper or a blan. computer screen, Instead! the student will chec. the design recipe and use the ?uestion2 and2answer guidelines to ma.e some progress, 1e created the design recipes b$ identi)$ing categories o) problems, The identi)ication o) a problem categor$ is based on the classes o) data that are used to represent the rele+ant in)ormation, Starting )rom the structure o) this class description students deri+e the programs with a chec.list, Figure ( shows the basic si8 steps o) a design recipe chec.list, #ach step produces a well2de)ined intermediate product: (, the description o) the class o) problem dataE &, the in)ormal speci)ication o) a programCs beha+iorE

5, the illustration o) the beha+ior with e8amplesE 6, the de+elopment o) a program template or la$outE 7, the trans)ormation o) the template into a complete de)initionE and 9, the disco+er$ o) errors through testing, The maFor di))erence concerns the relationship o) steps ( and 6, Design recipes help beginners and teachers ali.e, Teachers can use the recipes to inspect a beginnerCs problem2sol+ing s.ills! to diagnose wea.nesses! and to suggest speci)ic remedial steps, A)ter all! each stage o) the design recipe $ields a well2de)ined! chec.able product, I) a beginner is stuc.! a teacher can inspect the intermediate products and determine what the problem is, Based on this anal$sis! the teacher can then pro+ide guidance )or a speci)ic step in the recipe! raise appropriate ?uestions! and recommend additional practice e8ercises,

Why Everyone Should Learn to Program


,nd as imagination bodies forth The forms of things to n$no-n% and the poet.s pen T rns them to shapes% and gives to airy nothing , !oca! habitation and a name" 22 Sha.espeare! , Mids mmer /ight.s 0ream 4 /i0 @ur claim that e+er$one programs or should learn to program might appear strange considering that! at )irst glance! )ewer and )ewer people seem to program these da$s, Instead! the maForit$ o) people use application pac.ages! which donCt seem to re?uire an$ programming, #+en programmers use DDprogram generators!CC pac.ages that create programs )rom! sa$! business rules, So wh$ should an$one learn to programH The answer consists o) two parts, First! it is indeed true that traditiona! forms of programming are use)ul )or Fust a )ew people, But! programming as -e the a thors nderstand it is use)ul )or e+er$one: the administrati+e secretar$ who uses spreadsheets as well as the high2tech programmer, In other words! we ha+e a broader notion o) programming in mind than the traditional one, 1e e8plain our notion in a moment, Second! we teach our idea o) programming with a technolog$ that is based on the principle o) minimal intrusion, Hence our notion o) programming teaches problem2 anal$sis and problem2sol+ing s.ills -itho t imposing the o+erhead o) traditional programming notations and tools,

To get a better understanding o) modern programming! ta.e a closer loo. at spreadsheets! one o) toda$Cs popular application pac.ages, A user enters )ormulas into a spreadsheet, The )ormulas describe how a cell , depends on another cell 1, Then! as the user enters a number into 1! the spreadsheet automaticall$ calculates the contents o) cell ,, For complicated spreadsheets! a cell ma$ depend on man$ other cells! not Fust one, @ther application pac.ages re?uire similar acti+ities, Consider word processors and st$le sheets, A st$le sheet speci)ies how to create a /part o) a0 document )rom $et2to2be2 determined words or sentences, 1hen someone pro+ides speci)ic words and a st$le sheet! the word processor creates the document b$ replacing names in the st$le sheet with speci)ic words, Similarl$! someone who conducts a 1eb search ma$ wish to speci)$ what words to loo. )or! what words should be ne8t to each other! and what words should not occur in the page, In this case! the output depends on the search engineCs cache o) 1eb pages and the userCs search e8pression, Finall$! using a program generator in man$ wa$s relies on the same s.ills as those necessar$ )or application pac.ages, A program generator creates a program in a traditional programming language! such as CII or Ja+a! )rom high2le+el descriptions! such as business rules or scienti)ic laws, Such rules t$picall$ relate ?uantities! sales! and in+entor$ records and thus speci)$ computations, The other parts o) the program! especiall$ how it interacts with a user and how it stores data in the computerCs dis.! are generated with little or no human inter+ention, All o) these acti+ities instruct some computer so)tware to do something )or us, Some use scienti)ic notation! some ma$ use st$li*ed #nglish! some use a concrete programming notation, All o) them are some )orm o) programming, The essence o) these acti+ities boils down to two concepts: (, relating one ?uantit$ to another ?uantit$! and &, e+aluating a relationship b$ substituting +alues )or names, Indeed! the two concepts characteri*e programming at the lowest le+el! the computerCs nati+e language! and in a modern )ashionable language such as Ja+a, A program relates its inputs to outputsE and! when a program is used )or speci)ic inputs! the e+aluation substitutes concrete +alues )or names, -o one can predict what .ind o) application pac.ages will e8ist )i+e or ten $ears )rom now, But application pac.ages will continue to re?uire some )orm o) programming, To prepare students )or these .inds o) programming acti+ities! schools can either )orce them to stud$ algebra! which is the mathematical )oundation o) programming! or e8pose them to some )orm o) programming, Asing modern programming languages and

en+ironments! schools can do the latter! the$ can do it e))ecti+el$! and the$ can ma.e algebra )un,

Design Recipes
2oo$ing is at once chi!d.s p!ay and ad !t 3oy" ,nd coo$ing done -ith care is an act of !ove" 22 Craig Claiborne /(>&'2&'''0! Food #ditor! /e- 4or$ Times "earning to design programs is li.e learning to pla$ soccer, A pla$er must learn to trap a ball! to dribble with a ball! to pass! and to shoot a ball, @nce the pla$er .nows those basic s.ills! the ne8t goals are to learn to pla$ a position! to pla$ certain strategies! to choose among )easible strategies! and! on occasion! to create +ariations o) a strateg$ because none o) the e8isting strategies )its, A programmer is also +er$ much li.e an architect! a composer! or a writer, The$ are creati+e people who start with ideas in their heads and blan. pieces o) paper, The$ concei+e o) an idea! )orm a mental outline! and re)ine it on paper until their writings re)lect their mental image as much as possible, As the$ bring their ideas to paper! the$ emplo$ basic drawing! writing! and instrumental s.ills to e8press certain st$le elements o) a building! to describe a personCs character! or to )ormulate portions o) a melod$, The$ can practice their trade because the$ ha+e honed their basic s.ills )or a long time and can use them on an instincti+e le+el, Programmers also )orm outlines! translate them into )irst designs! and iterati+el$ re)ine them until the$ trul$ match the initial idea, Indeed! the best programmers edit and rewrite their programs man$ times until the$ meet certain aesthetic standards, And Fust li.e soccer pla$ers! architects! composers! or writers! programmers must practice the basic s.ills o) their trade )or a long time be)ore the$ can be trul$ creati+e, Design recipes are the e?ui+alent o) soccer ball handling techni?ues! writing techni?ues! techni?ues o) arrangements! and drawing s.ills, A single design recipe represents a point o) the program design space, 1e ha+e studied this space and ha+e identi)ied man$ important categories, This boo. selects the most )undamental and the most practical recipes and presents them in increasing order o) di))icult$,& About hal) the design recipes )ocus on the connection between input data and programs, More speci)icall$! the$ show how the template o) a program is deri+ed )rom the description o) the input data, 1e call this data-driven program design! and it is the most )re?uentl$ used )orm o) design, Data2dri+en designs are eas$ to create! eas$ to understand! and eas$ to e8tend and modi)$, @ther design recipes introduce the notion o) generative rec rsion! acc m !ation! and history sensitivity, The )irst one produces recursi+e programs that generate new instances o) problems as the$ recurE accumulator2 st$le programs collect data as the$ process inputsE and histor$2sensiti+e programs remember in)ormation between successi+e applications, "ast! but not least! we also

introduce a design recipe )or abstracting o+er programs, Abstracting is the act o) generali*ing two /or more0 similar designs into one and o) deri+ing the original instances )rom it, @n man$ occasions! a problem naturall$ suggests one design recipe, @n others! a programmer must choose )rom among se+eral possibilitiesE each choice ma$ produce programs with +astl$ di))erent organi*ations, Ma.ing choices is natural )or a creati+e programmer, But! unless a programmer is thoroughl$ )amiliar with the bag o) design recipes to choose )rom and completel$ understands the conse?uences o) choosing one o+er the other! the process is necessaril$ ad hoc and leads to whimsical! bad designs, 1e hope that b$ mapping out a collection o) design recipes! we can help programmers understand what to choose )rom and how to choose, -ow that we ha+e e8plained what we mean b$ DDprogrammingCC and DDprogram design!CC the reader can see wh$ and how teaching program design instills thin.ing s.ills that are important in a +ariet$ o) pro)essions, To design a program properl$! a student must: (, anal$*e a problem statement! t$picall$ stated as a word problemE &, e8press its essence! abstractl$ and with e8amplesE 5, )ormulate statements and comments in a precise languageE 6, e+aluate and re+ise these acti+ities in light o) chec.s and testsE and 7, pa$ attention to details, All o) these are acti+ities that are use)ul )or a businessman! a law$er! a Fournalist! a scientist! an engineer! and man$ others, 1hile traditional programming re?uires these s.ills! too! beginners o)ten donCt understand this connection, The problem is that traditional programming languages and traditional )orms o) programming )orce students to per)orm a large amount o) boo.2 .eeping wor. and to memori*e a large number o) language2speci)ic )acts, In short! menia! -or$ dro-ns the teaching of essentia! s$i!!s, To a+oid this problem! teachers must use a programming en+ironment that imposes as little o+erhead as possible and that accommodates beginners, Because such tools didnCt e8ist when we started! we de+eloped them,

The Choice of Scheme and DrScheme


#e ascribe bea ty to that -hich is simp!e% -hich has no s perf! o s parts5 -hich e+act!y ans-ers its end% -hich stands re!ated to a!! things% -hich is the mean of many e+tremes" 22 Ralph 1aldo #merson! The 2ond ct of Life 1e ha+e chosen Scheme as the programming language )or this boo.! and we ha+e designed and implemented DrScheme! a programming en+ironment )or the language with special assistance )or beginning students, The programming en+ironment is )reel$ a+ailable at the boo.Cs o))icial 1eb site,5 Still! the boo. it is not about programming in Scheme, 1e onl$ use a small number o) Scheme constructs in this boo., Speci)icall$! we use si8 constructs /)unction de)inition and application! conditional e8pressions! structure de)inition! local de)initions! and assignments0 plus a do*en or so basic )unctions, This tin$ subset o) the language is all that is needed to teach the principles o) computing and programming, Someone who wishes to use Scheme as a tool will need to read additional material, The choice o) Scheme )or beginners is natural, First! the core o) Scheme permits programmers to )ocus on Fust those two elements o) programming that we pointed out at the beginning o) the pre)ace: programs as relations between ?uantities and e+aluating programs )or speci)ic inputs, Asing Fust this core language! students can de+elop complete programs d ring the first session with a teacher, Second! Scheme can easil$ be arranged as a tower o) language le+els, This propert$ is crucial )or beginners who ma.e simple notational mista.es that generate obscure error messages about ad+anced )eatures o) a language, The result is o)ten a waste)ul search and a )eeling o) )rustration on the studentCs part, To a+oid this problem! our programming en+ironment! DrScheme! implements se+eral care)ull$ chosen sublanguages o) Scheme, Based on this arrangement! the en+ironment can signal error messages that are appropriate to a studentCs le+el o) .nowledge, Better still! the la$ering o) languages pre+ents man$ basic mista.es, 1e de+eloped the la$ers and the protection modes b$ obser+ing beginners )or wee.s in RiceCs computer lab, As students learn more about programming and the language! the teacher can e8pose students to richer la$ers o) the language! which allows students to write more interesting and more concise programs, Third! the DrScheme programming en+ironment o))ers a trul$ interacti+e e+aluator, It consists o) two windows: a Definitions window! where students de)ine programs! and an Interactions window! which acts li.e a poc.et calculator, Students can enter e8pressions into the latter! and DrScheme determines their +alues, In other words! computation starts with poc.et2calculator arithmetic! which the$ .now ?uite well! and ?uic.l$ proceeds )rom there to calculations with structures! lists! and trees 22 the .inds o) data that computer programs reall$ manipulate, Furthermore! an interacti+e mode o)

e+aluation encourages students to e8periment in all .inds o) wa$s and thus stimulates their curiosit$, Finall$! the use o) an interacti+e e+aluator with a rich data language permits students to )ocus on problem sol+ing and program design acti+ities, The .e$ impro+ement is that interacti+e e+aluation renders a discussion o) input and output operations /almost0 super)luous, This has se+eral conse?uences, First! input and output operations re?uire memori*ation, "earning these things is tedious and boring, Con+ersel$! students are better o)) learning problem2sol+ing s.ills and using canned input and output support, Second! good te8t2oriented input re?uires deep programming s.ills! which are best ac?uired in a course on computational problem2sol+ing, Teaching bad te8t2oriented input is a waste o) the teachersC and the studentsC time, Third! modern so)tware emplo$s graphical user inter)aces /=AI0! which programmers design with editors and DDwi*ardsCC but not b$ hand, Again! students are best o)) learning to design the )unctions that are connected to rulers! buttons! te8t )ields and so on! rather than memori*ing the speci)ic protocols that currentl$ )ashionable =AI libraries impose, In short! discussing input and output is a waste o) +aluable learning time during a )irst introduction to programming, I) students decide to pursue programming in more depth! ac?uiring the necessar$ /Scheme0 .nowledge about input and output procedures is straight)orward, In summar$! students can learn the core o) Scheme in a couple o) hours! $et the language is as power)ul as a con+entional programming language, As a result! students can )ocus immediatel$ on the essence o) programming! which greatl$ enhances their general problem2sol+ing s.ills,

The Parts of the Book


The boo. consists o) eight parts and se+en interme**os, The parts )ocus on program designE the interme**os introduce other topics concerning programming and computing, Figure & shows the dependence graph )or the pieces o) the boo., The graph demonstrates that there are se+eral paths through the boo. and that a partial co+erage o) the material is )easible, Parts I through III co+er the )oundations o) data2dri+en program design, Part I4 introduces abstraction in designs, Parts 4 and 4I are about generati+e recursion and accumulation, For these )irst si8 parts! the boo. uses a completel$ )unctional 22 or algebraic 22 )orm o) programming, @ne and the same e8pression alwa$s e+aluates to the same result! no matter how o)ten we e+aluate it, This propert$ ma.es it eas$ to design! and to reason about! programs, To cope with inter)aces between programs and the rest o) the world! howe+er! we enrich the language with assignment statements and abandon some o) our algebraic reasoning, The last two parts show what this means )or the design o) programs, More precisel$! the$ show how the design recipes o) the )irst si8 parts appl$ and wh$ we must be much more care)ul once assignments are added,

Interme**os introduce topics that are important )or computing and programming in general but not )or program design per se, Some introduce the s$nta8 and semantics o) our chosen subsets o) Scheme on a rigorous basis! a )ew introduce additional programming constructs, Interme**o 7 is a discussion o) the abstract cost o) computing /time! space! energ$0 and introduces +ectors, Interme**o 9 contrasts two wa$s o) representing numbers and processing them, The co+erage o) some interme**os can be dela$ed until a speci)ic need arises, This is especiall$ true o) the interme**os on SchemeCs s$nta8 and semantics, But! considering the central role o) interme**o 5 in )igure &! it should be co+ered in a timel$ )ashion,

Figure 2' The dependencies among parts and interme**os IT#RATI4# R#FI-#M#-T A-D IT#RATI@- @F T@PICS: S$stematic program design is particularl$ interesting and important )or large proFects, The step )rom small single2 )unction problems to small multi)unction proFects re?uires an additional design idea: iterati+e re)inement, The goal is to design the core o) a program and to add )unctionalit$ to this core until the entire set o) re?uirements is met, Students in a )irst course can! and must! get their )irst taste o) iterati+e re)inement, Hence! in order to ac?uaint students with the techni?ue! we ha+e included e8tended e8ercises, T$picall$! a brie) o+er+iew sets the stage )or a collection o) e8ercises, The

e8ercises gentl$ guide students through some design iterations, In section (9! the idea is spelled out e8plicitl$, Furthermore! the boo. re+isits certain e8ercise and e8ample topics time and again, For e8ample! sections 9,9! ;,6! (',5! &(,6! 6(,6! and a )ew e8ercises in between the last two sections co+er the idea o) mo+ing pictures across a can+as, The students thus see the same problem se+eral times! each time with more and more .nowledge about how to organi*e programs, Adding pieces o) )unctionalit$ to a program demonstrates wh$ programmers must )ollow a design discipline, Sol+ing the problem again shows students how to choose )rom alternati+e design recipes, Finall$! on occasion! new .nowledge Fust helps students impro+e the program organi*ationE in other words! students learn that programs arenCt )inished a)ter the$ wor. )or the )irst time but that! li.e papers and boo.s! the$ need editing, T#ACHPAC S: A second aspect o) wor.ing on proFects is that programmers ha+e to wor. in teams, In an instructional conte8t! this means that one studentCs program has to )it precisel$ to someone elseCs, To simulate what DD)itting oneCs )unction to someone elseCsCC means! we pro+ide DrScheme teachpac.s, Roughl$ spea.ing! a teachpac. simulates a team partner $et a+oids the )rustration o) wor.ing with mista.es in a partnerCs program component, More technicall$! the proFects almost alwa$s consist o) a +iew and a model program component /in the sense o) the model2+iew so)tware architecture0, In a t$pical setting! students design the model component, The teachpac.s pro+ide the +iew components! o)ten in the )orm o) /graphical0 user inter)aces, Thus the$ eliminate the tedious! mindless portions o) coding, Furthermore! this particular separation o) concerns mimics that o) real2world proFects, Fitting model components to +iew components re?uires students to pa$ attention to precise speci)ications o) )unctions, It demonstrates the paramount importance o) )ollowing a design discipline, It is also a critical s.ill )or programmers and is o)ten underemphasi*ed in beginning courses, In part I4 we show how to construct some simple =AIs and how =AI e+ents trigger the application o) model )unctions, The goal is to e8plain that constructing =AIs is no m$ster$! but not to spend a lot o) time on a topic that re?uires mostl$ rote learning and little computational thin.ing, SCH#DA"#: #ach uni+ersit$! college! and school has its own needs and must )ind an appropriate schedule, At Rice Ani+ersit$! we con+entionall$ co+er the entire boo. plus some additional material in a single semester, An instructor at a research uni+ersit$ should probabl$ .eep up a similar pace, A high school teacher will necessaril$ pursue a slower pace, Man$ o) the high schools that tested the boo. co+ered the )irst three parts in a semesterE some used onl$ the )irst part to teach algebraic problem sol+ing )rom a computational perspecti+eE and $et others wor.ed through the entire boo. in a $ear, For more in)ormation on schedules! +isit the boo.Cs 1eb site,

TH# B@@ @- TH# 1#B: The boo. comes in two +ersions: a paper cop$ and a )reel$ accessible on2line +ersion at
http://www.htdp.org/

The 1eb site also pro+ides additional material! especiall$ e8tended e8ercises o) the st$le mentioned abo+e, At this time! the 1eb page o))ers e8ercises on the +isual simulation o) ball games and the management o) 1eb site, More e8ercises will be added, The two +ersions o) the boo. come with di))erent .inds o) hints, #ach is mar.ed with one o) the )ollowing three icons:

This mar.er re)ers to 0r6cheme hintsE the$ are a+ailable in both +ersions o) the boo., The programming en+ironment has been designed with students in mind, The hints suggest how to use DrScheme at the +arious stages o) the learning process, This mar.er re)ers to teacher hints! which suggest strategies on how to present a section! on how to approach an e8ercise! or on how to supplement some material, This mar.er lin.s to on-!ine so! tions" Some solutions are )reel$ a+ailableE others are accessible to registered teachers onl$, To )ind out more about registration! see the boo.Cs 1eb site, T3P@=RAPH3 A-D D#FI-ITI@-S: For readabilit$! Scheme programs are t$peset using a small number o) )onts, Ita!ic words re)er to program names and +ariables, Sans Seri) items are constants and built2in operations, 5oldface words are Scheme .e$words, De)initions come in three +arieties, There are those terms that concern the principles o) programming and computing, The boo. lists the )irst occurrence o) such terms with SMA"" CAPITA" "#TT#RS, @ther de)initions are o) a more )leeting natureE the$ introduce terms that are important )or a section! an e8ample! an e8ercise! or some other small part o) the boo., The boo. uses s!anted words to emphasi*e such de)initions, Finall$! the boo. also de)ines classes o) data, Most data de)initions are bo8ed! and the )irst occurrence o) the de)ined name is also t$peset using s!anted words,

ckno!ledgments
Four people deser+e special than.s: Robert DDCor.$CC Cartwright! who co2de+eloped a predecessor o) RiceCs introductor$ course with the )irst authorE Daniel P, Friedman! )or as.ing the )irst author to rewrite The Litt!e LI6*er /also MIT Press0 in (><6! because it started this proFectE John Clements! who designed! implemented! and maintains DrSchemeCs stepperE and Paul Stec.ler! who )aith)ull$ supported the team with contributions to our suite o) programming tools,

The de+elopment o) the boo. bene)ited )rom man$ other )riends and colleagues who used it in their courses andKor ga+e detailed comments on earl$ dra)ts, 1e are grate)ul to them )or their help and their patience: Ian Barland! John Clements! Bruce Duba! Mi.e #rnst! athi Fisler! Daniel P, Friedman! John =reiner! John Stone! =eraldine Morin! and 4aldemar Tame*, A do*en generations o) 2omp 210 students at Rice Ani+ersit$ used earl$ dra)ts o) the te8t and contributed impro+ements in +arious wa$s, In addition! numerous attendees o) our TeachSchemeL wor.shops used earl$ dra)ts in their classrooms, Man$ sent in comments and suggestions, As representati+e o) these we mention the )ollowing acti+e contributors: Ms, Barbara Adler! Dr, Stephen Bloch! Mr, Jac. Cla$! Dr, Richard Clemens! Mr, $le =illette! Ms, aren Buras! Mr, Mar+in Hernande*! Mr, Michael Hunt! Ms, aren -orth! Mr, Jamie Ra$mond! and Mr, Robert Reid, Christopher Felleisen patientl$ wor.ed through the )irst )ew parts o) the boo. with his )ather and pro+ided direct insight into the +iews o) a $oung student, Hr+oFe Bla*e+ic /sailing! at the time! as Master o) the "P=KC Harriette0! Joe Machar$ /Ani+ersit$ o) Atah0 and Daniel P, Friedman /Indiana Ani+ersit$0 disco+ered numerous t$pos in the )irst printing! which we ha+e now )i8ed, Than. $ou to e+er$one, Finall$! Matthias e8presses his gratitude to Helga )or her man$ $ears o) patience and )or creating a home )or an absent2minded husband and )ather, Robb$ is grate)ul to Hsing2 Huei Huang )or her support and encouragementE without her! he would not ha+e gotten an$thing done, Matthew than.s 1en 3uan )or her constant support and enduring music, Shriram is indebted to athi Fisler )or support! patience and puns! and )or her participation in this proFect,

Readers whose e8perience is e8clusi+el$ based on programming languages such as CKCII! Basic! and Pascal should read DDprocedureCC or DDmethodCC where the pre)ace mentions DDprogram,CC
(

@ur design recipes were inspired b$ wor. with Daniel P, Friedman on structural recursion! with Robert Harper on t$pe theor$! and b$ Michael A, Jac.sonCs design method,
&

Scheme has an o))icial de)inition 22 the Re+ised Report on Scheme! edited b$ Richard else$! 1illiam Clinger! and Jonathan Rees 22 and man$ implementations, For a cop$ o) the report and )or a list o) alternati+e Scheme implementations! +isit www.schemers.org on the 1eb, -ote! howe+er! that the language o) this boo. e8tends that o) the report and is tailored to beginners,
5

Part I Processing Simple Forms of Data Section 1 Students, Teachers, and Computers
=etting Started 1e learn to compute at a $oung age, At )irst we Fust add and subtract numbers, @ne plus one e?uals two, Fi+e minus two is three, As we grow older we learn about additional mathematical operations! li.e e8ponentiation and sine! but we also learn to describe rules o) computation, =i+en a circle o) radius r! its circum)erence is r times two times pi, A minimum2wage laborer who wor.s )or / hours earns / times 7,57 dollars, The truth is! our teachers turn us into computers and program us to e8ecute simple computer programs, So! the secret is out, Computer programs are Fust +er$ )ast students, The$ can per)orm millions o) additions while we might still be struggling with the )irst one, But computer programs can do more than Fust manipulate numbers, The$ can guide an airplane, The$ can pla$ games, The$ can loo. up a personCs phone number, The$ can print the pa$roll chec.s )or huge corporations, In short! computers process all .inds o) in)ormation, People state in)ormation and instructions in #nglish, The temperature is 57o 2E con+ert this temperature into Fahrenheit, It ta.es this car 57 seconds to accelerate )rom *ero to ('' miles per hourE determine how )ar the car gets in &' seconds,

Computers! howe+er! barel$ understand basic #nglish and certainl$ canCt understand comple8 instructions e8pressed in #nglish, Instead we must learn to spea. a computer language so that we can communicate in)ormation and instructions, A computerCs language o) instruction and in)ormation is a PR@=RAMMI-= "A-=AA=#, In)ormation e8pressed in a programming language is called DATA, There are man$ )la+ors o) data, / mbers are one class o) data, / mber series belong to the class o) C@MP@A-D DATA! because each series is made up o) other pieces o) smaller pieces o) data! namel$! numbers, To contrast the two .inds o) data! we also call numbers AT@MIC DATA, "etters are other e8amples o) atomic dataE )amil$ trees are compound data, Data represents in)ormation! but the concrete interpretation is up to us, For e8ample! a number li.e 5;,7( ma$ represent a temperature! a time! or a distance, A letter li.e DDACC ma$ denote a school grade! a ?ualit$ s$mbol )or eggs! or a part o) an address, "i.e data! instructions! also called @P#RATI@-S! come in se+eral )la+ors, #ach class o) data comes with a set o) PRIMITI4# @P#RATI@-S, For numbers! we naturall$ get +! -! *! and so on, Programmers compose primiti+e operations into PR@=RAMS, Thus! we ma$ thin. o) primiti+e operations as the words o) a )oreign language and o) programming as )orming sentences in this language, Some programs are as small as essa$s, @thers are li.e sets o) enc$clopedias, 1riting good essa$s and boo.s re?uires care)ul planning! and writing good programs does! too, Small or large! a good program cannot be created b$ tin.ering around, It must be care)ull$ designed, #ach piece needs a lot o) attentionE composing programs into larger units must )ollow a well2planned strateg$, Designing programs properl$ must be practiced )rom our +er$ )irst da$ o) programming, In this boo.! we will learn to design computer programs! and we will learn to understand how the$ )unction, Becoming and being a programmer is )un! but it is not eas$, The best part o) being a programmer is watching our DDproductsCC grow and become success)ul, It is )un to obser+e a computer program pla$ a game, It is e8citing to see a computer program help someone, To get to this point! howe+er! we must practice man$ s.ills, As we will )ind out! programming languages are primiti+eE especiall$! their grammar is restricti+e, And un)ortunatel$! computers are stupid, The smallest grammatical mista.e in a program is a )atal stumbling bloc. )or a computer, 1orse! once our program is in proper grammatical shape! it might not per)orm the computations as intended, Programming a computer re?uires patience and concentration, @nl$ attention to minute details will a+oid )rustrating grammatical mista.es, @nl$ rigorous planning and adherence to the plan will pre+ent serious logical mista.es in our designs, But when we )inall$ master the design o) programs! we will ha+e learned s.ills that are use)ul )ar be$ond the realm o) programming,

"etCs get startedL

Section 2 Numbers, E pressions, Simple Programs


In the beginning! people thought o) computers as number crunchers, And indeed! computers are +er$ good at wor.ing with numbers, Since teachers start their )irst2 graders on computing with numbers! we start with numbers! too, @nce we .now how computers deal with numbers! we can de+elop simple programs in no timeE we Fust translate common sense into our programming notation, Still! e+en de+eloping such simple programs re?uires discipline! and so we introduce the outline o) the most )undamental design recipe and the basic programming guideline at the end o) this section,

"#$ %um&ers and


Computing

rithmetic

-umbers come in man$ di))erent )la+ors: positi+e and negati+e integers! )ractions /also .nown as rationals0! and reals are the most widel$ .nown classes o) numbers:
5 -5 2/3 17/3 #i1.4142135 23731

The )irst is an integer! the second one a negati+e integer! the ne8t two are )ractions! and the last one is an ine8act representation o) a real number, "i.e a poc.et calculator! the simplest o) computers! Scheme permits programmers to add! subtract! multipl$! and di+ide numbers:
!+"5"5# !+"-5"5# !+"5"-5# !-"5"5# !*"3"4# !/"$"12#

The )irst three as. Scheme to per)orm additionsE the last three demand a subtraction! a multiplication! and a di+ision, All arithmetic e8pressions are parenthesi*ed and mention the operation )irstE the numbers )ollow the operation and are separated b$ spaces,

Stepper As in arithmetic or algebra! we can nest e8pressions:


""!*"!+"2"2#"!/"!*"!+"3"5#"!/"3%"1%##"2##

Scheme e+aluates these e8pressions e8actl$ as we do, It )irst reduces the innermost parenthesi*ed e8pressions to numbers! then the ne8t la$er! and so on:
""!*"!+"2"2#"!/"!*"!+"3"5#"!/"3%"1%##"2## &"!*"4"!/"!*"$"3#"2## &"!*"4"!/"24"2## &"!*"4"12# &"4$

Because e+er$ Scheme e8pression has the shape


!operation"'"..."(#

there is ne+er an$ ?uestion about which part has to be e+aluated )irst, 1hene+er '"... ( are numbers! the e8pression can be e+aluatedE otherwise! '"..."( are e+aluated )irst, Contrast this with

which is an e8pression that we encounter in grade school, @nl$ a substantial amount o) practice guarantees that we remember to e+aluate the multiplication )irst and the addition a)terwards,6 Finall$! Scheme not onl$ pro+ides simple arithmetical operations but a whole range o) ad+anced mathematical operations on numbers, Here are )i+e e8amples: (, !s)rt"'# computes /,0(K&E &, !e*pt"'"(# computes ,1E 5, !remainder"'"(# computes the remainder o) the integer di+ision ,K1E 6, !+og"'# computes the natural logarithm o) 'E and 7, !sin"'# computes the sine o) , radians,

1hen in doubt whether a primiti+e operation e8ists or how it wor.s! use DrScheme to test whether an operation is a+ailable with a simple e8ample, + Note on Numbers: Scheme computes with #NACT integers and rationals as long as we use primiti+e operations that produce e8act results, Thus! it displa$s the result o) !/ 44"14# as 22/7, An)ortunatel$! Scheme and other programming languages compromise as )ar as real numbers are concerned, For e8ample! since the s?uare root o) 2 is not a rational but a real number! Scheme uses an I-#NACT -AMB#R:
""!s)rt"2# &"#i1.4142135 23731

The #i notation warns the programmer that the result is an appro8imation o) the true number, @nce an ine8act number has become a part o) a calculation! the process continues in an appro8imate manner, To wit:
""!-"#i1.%"#i%.,# &"#i%.%,,,,,,,,,,,,,,,$

but
""!-"#i1%%%.%"#i,,,.,# &"#i%.1%%%%%%%%%%%%2274

e+en though we .now )rom mathematics that both di))erences should be %.1 and e?ual, @nce numbers are ine8act! caution is necessar$, This imprecision is due to the common simpli)ication o) writing down numbers li.e the s?uare root o) & or as rational numbers, Recall that the decimal representations o) these numbers are in)initel$ long /without repetition0, A computer! howe+er! has a )inite si*e! and there)ore can onl$ represent a portion o) such a number, I) we choose to represent these numbers as rationals with a )i8ed number o) digits! the representation is necessaril$ ine8act, Interme**o 9 will e8plain how ine8act numbers wor., To )ocus our studies on the important concepts o) computing and not on these details! the teaching languages o) DrScheme deal as much as possible with numbers as precise numbers, 1hen we write 1.25! DrScheme interprets this number as a precise )raction! not as an ine8act number, 1hen DrSchemeCs Interactions window displa$s a number such as 1.25 or 22/7! it is the result o) a computation with precise rationals and )ractions, @nl$ numbers pre)i8ed b$ #i are ine8act representations, E ercise 2<1<1< Find out whether DrScheme has operations )or s?uaring a numberE )or computing the sine o) an angleE and )or determining the ma8imum o) two numbers, Solution

E ercise 2<1<2< #+aluate !s)rt"4#! !s)rt"2#! and !s)rt"-1# in DrScheme, Then! )ind out whether DrScheme .nows an operation )or determining the tangent o) an angle, Solution

"#" 'aria&les and Programs


Programming In algebra we learn to )ormulate dependencies between ?uantities using 4ARIAB"# #NPR#SSI@-S, A +ariable is a placeholder that stands )or an un.nown ?uantit$, For e8ample! a dis. o) radius r has the appro8imate area7

In this e8pression! r stands )or an$ positi+e number, I) we now come across a dis. with radius 7! we can determine its area b$ substituting 7 )or r in the abo+e )ormula and reducing the resulting e8pression to a number:

More generall$! e8pressions that contain +ariables are rules that describe how to compute a number -hen we are gi+en +alues )or the +ariables, A program is such a rule, It is a rule that tells us and the computer how to produce data )rom some other data, "arge programs consist o) man$ small programs and combine them in some manner, It is there)ore important that programmers name each rule as the$ write it down, A good name )or our sample e8pression is area-of-dis-, Asing this name! we would e8press the rule )or computing the area o) a dis. as )ollows:
!define"!area-of-dis-"r#" ""!*"3.14"!*"r"r###

The two lines sa$ that area-of-dis- is a rule! that it consumes a single I-PAT! called r! and that the result! or @ATPAT! is going to be !*"3.14"!*"r"r## once we .now what number r represents, Programs combine basic operations, In our e8ample! area-of-dis- uses onl$ one basic operation! multiplication! but defined programs ma$ use as man$ operations as necessar$, @nce we ha+e de)ined a program! we ma$ use it as i) it were a primiti+e operation, For each +ariable listed to the right o) the program name! we must suppl$ one input, That is! we ma$ write e8pressions whose operation is area-of-dis- )ollowed b$ a number:
""!area-of-dis-"5#

1e also sa$ that we APP"3 area-of-dis- to 5,

The application o) a defined operation is e+aluated b$ cop$ing the e8pression named area-of-dis- and b$ replacing the +ariable /r0 with the number we supplied /50:
""!area-of-dis-"5#" &"!*"3.14"!*"5"5## &"!*"3.14"25# &"7$.5

Man$ programs consume more than one input, Sa$ we wish to de)ine a program that computes the area o) a ring! that is! a dis. with a hole in the center:

The area o) the ring is that o) the outer dis. minus the area o) the inner dis.! which means that the program re?uires t-o un.nown ?uantities: the outer and the inner radii, "et us call these un.nown numbers o.ter and inner, Then the program that computes the area o) a ring is de)ined as )ollows:
!define"!area-of-ring"o.ter"inner#" ""!-"!area-of-dis-"o.ter# """""!area-of-dis-"inner###

The three lines e8press that area-of-ring is a program! that the program accepts two inputs! called o.ter and inner! and that the result is going to be the di))erence between !area-of-dis-"o.ter# and !area-of-dis-"inner#, In other words! we ha+e used both basic Scheme operations and defined programs in the de)inition o) area-ofring, 1hen we wish to use area-of-ring! we must suppl$ two inputs:
""!area-of-ring"5"3#"

The e8pression is e+aluated in the same manner as !area-of-dis-"5#, 1e cop$ the e8pression )rom the de)inition o) the program and replace the +ariable with the numbers we supplied:
""!area-of-ring"5"3#" &"!-"!area-of-dis-"5# """""!area-of-dis-"3## &"!-"!*"3.14"!*"5"5## """""!*"3.14"!*"3"3### &"...

The rest is plain arithmetic,

E ercise 2<2<1< De)ine the program Fahrenheit-/Celsius!9 which consumes a temperature measured in Fahrenheit and produces the Celsius e?ui+alent, Ase a chemistr$ or ph$sics boo. to loo. up the con+ersion )ormula,

Teachpac.s 1hen the )unction is )ull$ de+eloped! test it using the teachpac. convert.ss, The teachpac. pro+ides three )unctions: con0ert-g.i! con0ert-rep+! and con0ert-fi+e, The )irst creates a graphical user inter)ace, Ase it with
!con0ert-g.i"Fahrenheit-/Celsius#

The e8pression will create a new window in which users can manipulate a slider and buttons, The second emulates the Interactions window, Asers are as.ed to enter a Fahrenheit temperature! which the program reads! e+aluates! and prints, Ase it +ia
!con0ert-rep+"Fahrenheit-/Celsius#

The last operation processes entire )iles, To use it! create a )ile with those numbers that are to be con+erted, Separate the numbers with blan. spaces or new lines, The )unction reads the entire )ile! con+erts the numbers! and writes the results into a new )ile, Here is the e8pression:
!con0ert-fi+e"1in.dat1"Fahrenheit-/Celsius"1o.t.dat1#

This assumes that the name o) the newl$ created )ile is in.dat and that we wish the results to be written to the )ile o.t.dat, For more in)ormation! use DrSchemeCs Help Des. to loo. up the teachpac. convert.ss, Solution E ercise 2<2<2< De)ine the program dollar-/euro! which consumes a number o) dollars and produces the euro e?ui+alent, Ase the currenc$ table in the newspaper to loo. up the current e8change rate, Solution E ercise 2<2<!< De)ine the program triang+e, It consumes the length o) a triangleCs side and the perpendicular height, The program produces the area o) the triangle, Ase a geometr$ boo. to loo. up the )ormula )or computing the area o) a triangle, Solution E ercise 2<2<#< De)ine the program con0ert3, It consumes three digits! starting with the least signi)icant digit! )ollowed b$ the ne8t most signi)icant one! and so on, The program produces the corresponding number, For e8ample! the e8pected +alue o)

!con0ert3"1"2"3#"

is 321, Ase an algebra boo. to )ind out how such a con+ersion wor.s,

Solution

E ercise 2<2<$< A t$pical e8ercise in an algebra boo. as.s the reader to e+aluate an e8pression li.e

)or n O &! n O 7! and n O >, Asing Scheme! we can )ormulate such an e8pression as a program and use the program as man$ times as necessar$, Here is the program that corresponds to the abo+e e8pression:
!define"!f"n# ""!+"!/"n"3#"2##

First determine the result o) the e8pression at n O &! n O 7! and n O > b$ hand! then with DrSchemeCs stepper, Also )ormulate the )ollowing three e8pressions as programs: (, n& I (' &, /(K&0 P n& I &' 5, & - /(Kn0 Determine their results )or n O & and n O > b$ hand and with DrScheme, Solution

"#( Word Pro&lems


Programmers are rarel$ handed mathematical e8pressions to turn into programs, Instead the$ t$picall$ recei+e in)ormal problem descriptions that o)ten contain irrele+ant and sometimes ambiguous in)ormation, The programmersC )irst tas. is to e8tract the rele+ant in)ormation and then to )ormulate appropriate e8pressions, Here is a t$pical e8ample: Compan$ N3M G Co, pa$s all its emplo$ees Q(& per hour, A t$pical emplo$ee wor.s between &' and 97 hours per wee., De+elop a program that determines the wage o) an emplo$ee )rom the number o) hours o) wor.,

The last sentence is the )irst to mention the actual tas.: to write a program that determines one ?uantit$ based on some other ?uantit$, More speci)icall$! the program consumes one ?uantit$! the number o) hours o) wor.! and produces another one! the wage in dollars, The )irst sentence implies how to compute the result! but doesnCt state it e8plicitl$, In this particular e8ample! though! this poses no problem, I) an emplo$ee wor.s h hours! the wage is -ow that we ha+e a rule! we can )ormulate a Scheme program:
!define"!wage"h# ""!*"12"h##

The program is called wageE its parameter h stands )or the hours an emplo$ee wor.sE and its result is !*"12"h#! the corresponding wage, E ercise 2<!<1< AtopiaCs ta8 accountants alwa$s use programs that compute income ta8es e+en though the ta8 rate is a solid! ne+er2changing (7R, De)ine the program ta*! which determines the ta8 on the gross pa$, Also de)ine netpa2, The program determines the net pa$ o) an emplo$ee )rom the number o) hours wor.ed, Assume an hourl$ rate o) Q(&, Solution E ercise 2<!<2< The local supermar.et needs a program that can compute the +alue o) a bag o) coins, De)ine the program s.m-coins, It consumes )our numbers: the number o) pennies! nic.els! dimes! and ?uarters in the bagE it produces the amount o) mone$ in the bag, Solution E ercise 2<!<!< An old2st$le mo+ie theater has a simple pro)it )unction, #ach customer pa$s Q7 per tic.et, #+er$ per)ormance costs the theater Q&'! plus Q,7' per attendee, De+elop the )unction tota+-profit, It consumes the number o) attendees /o) a show0 and produces how much income the attendees produce, Solution

"#) Errors
#rrors 1hen we write Scheme programs! we must )ollow a )ew care)ull$ designed rules! which are a compromise between a computerCs capabilities and human beha+ior,; Fortunatel$! )orming Scheme de)initions and e8pressions is intuiti+e, #8pressions are either AT@MIC! that is! numbers and +ariablesE or the$ are C@MP@A-D e8pressions! in which case the$ start with DD/CC! )ollowed b$ an operation! some more e8pressions! and terminated b$ DD0CC, #ach e8pression in a compound e8pression should be preceded b$ at least one spaceE line brea.s are permissible! and sometimes increase readabilit$,

De)initions ha+e the )ollowing schematic shape:


!define"!f"*"..."2# ""an-e*pression#

That is! a de)inition is a se?uence o) se+eral words and e8pressions: DD/CC! the word DDde)ineCC! DD/CC! a non2empt$ se?uence o) names separated b$ spaces! DD0CC! an e8pression! and a closing DD0CC, The embedded se?uence o) names! f"*"..."2! introduces the name o) the program and the names o) its parameters, S%nta Errors') -ot all parenthesi*ed e8pressions are Scheme e8pressions, For e8ample! !1%# is a parenthesi*ed e8pression! but Scheme does not accept it as a legal Scheme e8pression because numbers are not supposed to be included in parentheses, Similarl$! a sentence li.e !1%"+"2%# is also ill )ormedE SchemeCs rules demand that the operator is mentioned )irst, Finall$! the )ollowing two de)initions are not well )ormed:
!define"!3"*# ""!+"!*#"1%## !define"!4"*# ""*"1%#

The )irst one contains an e8tra pair o) parentheses around the +ariable *! which is not a compound e8pressionE the second contains two atomic e8pressions! * and 1%! instead o) one, 1hen we clic. DrSchemeCs 5*ec.te button! the programming en+ironment )irst determines whether the de)initions are )ormed according to SchemeCs rules, I) some part o) the program in the Definitions window is ill )ormed! DrScheme signals a S3-TAN #RR@R with an appropriate error message and highlights the o))ending part, @therwise it permits the user to e+aluate e8pressions in the Interactions window,

#rrors E ercise 2<#<1< #+aluate the )ollowing sentences in DrScheme! one at a time:
!+"!1%#"2%# !1%"+"2%# !+"+#

Read and understand the error messages,

Solution

E ercise 2<#<2< #nter the )ollowing sentences! one b$ one! into DrSchemeCs Definitions window and clic. 5*ec.te:
!define"!f"1# ""!+"*"1%##

!define"!g"*# ""+"*"1%# !define"h!*#" ""!+"*"1%##

Read the error messages! )i8 the o))ending de)inition in an appropriate manner! and repeat until all de)initions are legal, Solution 0un2time Errors' The e+aluation o) Scheme e8pressions proceeds according to the intuiti+e laws o) algebra and arithmetic, 1hen we encounter new operations! we will e8tend these laws! )irst intuiti+el$ and then! in section <! rigorousl$, For now! it is more important to understand that not all legal Scheme e8pressions ha+e a result, @ne ob+ious e8ample is !/"1"%#, Similarl$! i) we de)ine
!define"!f"n# ""!+"!/"n"3#"2##

we cannot as. DrScheme to e+aluate !f"5"$#, 1hen the e+aluation o) a legal Scheme e8pression demands a di+ision b$ *ero or similarl$ nonsensical arithmetic operations! or when a program is applied to the wrong number o) inputs! DrScheme stops the e+aluation and signals a RA-2TIM# #RR@R, T$picall$ it prints an e8planation in the Interactions window and highlights the )ault$ e8pression, The highlighted e8pression triggered the error signal, E ercise 2<#<!< #+aluate the )ollowing grammaticall$ legal Scheme e8pressions in DrSchemeCs Interactions window:
!+"5"!/"1"%## !sin"1%"2%# !somef"1%#

Read the error messages,

Solution

E ercise 2<#<#< #nter the )ollowing grammaticall$ legal Scheme program into the Definitions window and clic. the 5*ec.te button:
!define"!somef"*# ""!sin"*"*##

Then! in the Interactions window! e+aluate the e8pressions:


!somef"1%"2%# !somef"1%#

and read the error messages, Also obser+e what DrScheme highlights,

Solution

,ogical Errors' A good programming en+ironment assists the programmer in )inding s$nta8 and runtime errors, The e8ercises in this section illustrate how DrScheme catches s$nta8 and run2time errors, A programmer! howe+er! can also ma.e "@=ICA" #RR@RS, A logical mista.e does not trigger an$ error messagesE instead! the program computes incorrect results, Consider the wage program )rom the preceding section, I) the programmer had accidentall$ de)ined it as
!define"!wage"h# ""!+"12"h##

the program would still produce a number e+er$ time it is used, Indeed! i) we e+aluate !wage"12/11#! we e+en get the correct result, A programmer can catch such mista.es onl$ b$ designing programs care)ull$ and s$stematicall$,

"#* Designing Programs


Designing Programs The preceding sections show that the de+elopment o) a program re?uires man$ steps, 1e need to determine whatCs rele+ant in the problem statement and what we can ignore, 1e need to understand what the program consumes! what it produces! and how it relates inputs to outputs, 1e must .now! or )ind out! whether Scheme pro+ides certain basic operations )or the data that our program is to process, I) not! we might ha+e to de+elop au8iliar$ programs that implement these operations, Finall$! once we ha+e a program! we must chec. whether it actuall$ per)orms the intended computation, This might re+eal s$nta8 errors! run2time problems! or e+en logical errors, To bring some order to this apparent chaos! it is best to set up and to )ollow a D#SI=R#CIP#! that is! a step2b$2step prescription o) what we should do and the order> in which we should do things, Based on what we ha+e e8perienced thus )ar! the de+elopment o) a program re?uires at least the )ollowing )our acti+ities:

66"7ontract:"area-of-ring":"n.m8er"n.m8er""-/""n.m8er 66"3.rpose:"to"comp.te"the"area"of"a"ring"whose"radi.s"is 66"o.ter"and"whose"ho+e"has"a"radi.s"of"inner 66"5*amp+e:"!area-of-ring"5"3#"sho.+d"prod.ce"5%.24 66"Definition:"9refines"the"header: !define"!area-of-ring"o.ter"inner# ""!-"!area-of-dis-"o.ter# """""!area-of-dis-"inner### "" 66";ests: !area-of-ring"5"3#" 66"e*pected"0a+.e

7',&6

Figure !' The design recipe: A complete e8ample 8nderstanding the Program=s Purpose' The goal o) designing a program is to create a mechanism that consumes and produces data, 1e there)ore start e+er$ program de+elopment b$ gi+ing the program a meaning)ul name and b$ stating what .ind o) in)ormation it consumes and produces, 1e call this a C@-TRACT, Here is how we write down a contract )or area-of-ring! one o) our )irst programs:('
66"area-of-ring":"n.m8er"n.m8er""-/""n.m8er

The semicolons indicate that this line is a C@MM#-T, The contract consists o) two parts, The )irst! to the le)t o) the colon! states the programCs name, The second! to the right o) the colon! speci)ies what .ind o) data the program consumes and what it producesE the inputs are separated )rom the output b$ an arrow, @nce we ha+e a contract! we can add the H#AD#R, It restates the programCs name and gi+es each input a distinct name, These names are /algebraic0 +ariables and are re)erred to as the programCs PARAM#T#RS,(( "etCs ta.e a loo. at the contract and header )or area-of-ring:
66"area-of-ring":"n.m8er"n.m8er""-/""n.m8er !define"!area-of-ring"o.ter"inner#"...#

It sa$s that we will re)er to the )irst input as o.ter and the second one as inner, Finall$! using the contract and the parameters! we should )ormulate a short PARP@S# STAT#M#-T )or the program! that is! a brie) comment o) -hat the program is to compute, For most o) our programs! one or two lines will su))iceE as we de+elop larger and larger programs! we ma$ need to add more in)ormation to e8plain a programCs purpose,

Here is the complete starting2point )or our running e8ample:


66"area-of-ring":"n.m8er"n.m8er""-/""n.m8er 66"to"comp.te"the"area"of"a"ring"whose"radi.s"is 66"o.ter"and"whose"ho+e"has"a"radi.s"of"inner !define"!area-of-ring"o.ter"inner#"...#

>ints' I) the problem statement pro+ides a mathematical )ormula! the number o) distinct +ariables in the )ormula suggests how man$ inputs the program consumes, For other word problems! we must inspect the problem to separate the gi+en )acts )rom what is to be computed, I) a gi+en is a )i8ed number! it shows up in the program, I) it is an un.nown number that is to be )i8ed b$ someone else later! it is an input, The ?uestion /or the imperati+e0 in the problem statement suggests a name )or the program, Program E amples' To gain a better understanding o) what the program should compute! we ma.e up e8amples o) inputs and determine what the output should be, For e8ample! area-of-ring should produce 5%.24 )or the inputs 5 and 3! because it is the di))erence between the area o) the outer dis. and the area o) the inner dis., 1e add e8amples to the purpose statement:
""66"area-of-ring":"n.m8er"n.m8er""-/""n.m8er ""66"to"comp.te"the"area"of"a"ring"whose"radi.s"is ""66"o.ter"and"whose"ho+e"has"a"radi.s"of"inner ""66"e*amp+e:"!area-of-ring"5"3#"sho.+d"prod.ce"5%.24 ""!define"!area-of-ring"o.ter"inner#"...#

Ma.ing up e8amples 22 before 3e 3rite do3n the program=s bod% 22 helps in man$ wa$s, First! it is the onl$ sure wa$ to disco+er logical errors with testing, I) we use the )inished program to ma.e up e8amples! we are tempted to trust the program because it is so much easier to run the program than to predict what it does, Second! e8amples )orce us to thin. through the computational process! which! )or the complicated cases we will encounter later! is critical to the de+elopment o) the )unction bod$, Finall$! e8amples illustrate the in)ormal prose o) a purpose statement, Future readers o) the program! such as teachers! colleagues! or bu$ers! greatl$ appreciate illustrations o) abstract concepts, The 5od%' Finall$! we must )ormulate the programCs bod$, That is! 3e must replace the ??...== in our header 3ith an e pression, The e8pression computes the answer )rom the parameters! using SchemeCs basic operations and Scheme programs that we alread$ defined or intend to define, 1e can onl$ )ormulate the programCs bod$ i) we understand how the program computes the output )rom the gi+en inputs, I) the input2output relationship is gi+en as a mathematical )ormula! we Fust translate mathematics into Scheme, I)! instead! we are gi+en a word problem! we must cra)t the e8pression care)ull$, To

this end! it is help)ul to re+isit the e8amples )rom the second step and to understand ho- we computed the outputs )or speci)ic inputs, In our running e8ample! the computational tas. was gi+en +ia an in)ormall$ stated )ormula that reused area-of-dis-! a pre+iousl$ defined program, Here is the translation into Scheme:
!define"!area-of-ring"o.ter"inner# ""!-"!area-of-dis-"o.ter# """""!area-of-dis-"inner###

Testing' A)ter we ha+e completed the program de)inition! we must still test the program, At a minimum! we should ensure that the program computes the e8pected outputs )or the program e8amples, To )acilitate testing! we ma$ wish to add the e8amples to the bottom o) the Definitions window as i) the$ were e?uations, Then! when we clic. the 5*ec.te button! the$ are e+aluated! and we see whether the program wor.s properl$ on them, Testing cannot show that a program produces the correct outputs )or all possible inputs 22 because there are t$picall$ an in)inite number o) possible inputs, But testing can re+eal s$nta8 errors! run2time problems! and logical mista.es, For )ault$ outputs! we must pa$ special attention to our program e8amples, It is possible that the e8amples are wrongE that the program contains a logical mista.eE or that both the e8amples and the program are wrong, In either case! we ma$ ha+e to step through the entire program de+elopment again, Figure 5 shows what we get a)ter we ha+e de+eloped the program according to our recipe, Figure 6 summari*es the recipe in tabular )orm, It should be consulted whene+er we design a program,

Phase Contract Purpose and Header

=oal to name the )unctionE to speci)$ its classes o) input data and its class o) output dataE to describe its purposeE to )ormulate a header to characteri*e the input2 output relationship +ia e8amples to de)ine the )unction

Acti+it$ choose a name that )its the problem stud$ the problem )or clues on how man$ un.nown DDgi+ensCC the )unction consumes pic. one +ariable per inputE i) possible! use names that are mentioned )or the DDgi+ensCC in the problem statement describe what the )unction should produce using the chosen +ariables names )ormulate the contract and header: EE name : n mber ...22S n mber EE to compute ... )rom +1 ... /define /name +1 ...0 ...0

#8amples

search the problem statement )or e8amples wor. through the e8amples +alidate the results! i) possible ma.e up e8amples

Bod$

Test

to disco+er mista.es /DDt$posCC and logic0

)ormulate how the )unction computes its results de+elop a Scheme e8pression that uses SchemeCs primiti+e operations! other )unctions! and the +ariables translate the mathematical e8pressions in the problem statement! when a+ailable appl$ the )unction to the inputs o) the e8amples chec. that the outputs are as predicted

Figure #' The design recipe at a glance The design recipe is not a magic bullet )or the problems we encounter during the design o) a program, It pro+ides some guidance )or a process that can o)ten appear to be o+erwhelming, The most creati+e and most di))icult step in our recipe concerns the design o) the programCs bod$, At this point! it relies hea+il$ on our abilit$ to read and understand written material! on our abilit$ to e8tract mathematical relationships! and on our .nowledge o) basic )acts, -one o) these s.ills is speci)ic to the de+elopment o) computer programsE the .nowledge we e8ploit is speci)ic to the application domain in which we are wor.ing, The remainder o) the boo. will show what and how much computing can contribute to this most complicated step, Domain 7no3ledge: Formulating the bod$ o) a program o)ten re?uires .nowledge about the area! also .nown as domain! )rom which the problem is drawn, This )orm o) .nowledge is called D@MAI- -@1"#D=#, It ma$ ha+e to be drawn )rom simple mathematics! such as arithmetic! )rom comple8 mathematics! such as di))erential

e?uations! or )rom non2mathematical disciplines: music! biolog$! ci+il engineering! art! and so on, Because programmers cannot .now all o) the application domains o) computing! the$ must be prepared to understand the language o) a +ariet$ o) application areas so that the$ can discuss problems with domain e8perts, The language is o)ten that o) mathematics! but in some cases! the programmers must in+ent a language! especiall$ a data language )or the application area, For that reason! it is imperati+e that programmers ha+e a solid understanding o) the )ull possibilities o) computer languages,

Another ad+antage o) SchemeCs notation is that we alwa$s .now where to place an operator or where to )ind it: to the immediate right o) the opening parenthesis, This is important in computing because we need man$ more operators than Fust the )ew numerical operators that we use in arithmetic and algebra,
6

It is common to spea. o) the area o) a circle! but mathematicall$ spea.ing! the circle is onl$ the dis.Cs outer edge,
7

An arrow is .e$ed in as - )ollowed b$ /,

This statement is true )or an$ other programming language as well! )or e8ample! spreadsheet languages! C! word processor macro, Scheme is simpler than most o) these and eas$ to understand )or computers, An)ortunatel$! to human beings who grow up on in)i8 e8pressions such as 7 I 6! Scheme pre)i8 e8pressions such as !+"5"4# initiall$ appear to be complicated, A bit o) practice will ?uic.l$ eliminate this misconception,
;

<

1e will )ind out in section < wh$ such errors are called synta+ errors,

As we will see later! the order is not completel$ )i8ed, It is possible! and )or a number o) reasons! desirable to switch the order o) some steps in some cases,
>

('

An arrow is .e$ed in as - )ollowed b$ /, @thers also call them F@RMA" AR=AM#-TS or I-PAT 4ARIAB"#S,

((

Section !

Programs are Function Plus "ariable Definitions


In general! a program consists not Fust o) one! but o) man$ de)initions, The area-ofring program! )or e8ample! consists o) two de)initions: the one )or area-of-ring and another one )or area-of-dis-, 1e re)er to both as FA-CTI@- D#FI-ITI@-s and! using mathematical terminolog$ in a loose wa$! sa$ that the program is C@MP@S#D o) se+eral )unctions, Because the )irst one! area-of-ring! is the )unction we reall$ wish to use! we re)er to it as the MAI- FA-CTI@-E the second one! area-of-dis-! is an AANI"IAR3 FA-CTI@-! occasionall$ also called H#"P#R FA-CTI@-, The use o) au8iliar$ )unctions ma.es the design process manageable and renders programs readable, Compare the )ollowing two +ersions o) area-of-ring:
!define"!area-of-ring"o.ter inner#" ""!-"!area-of-dis-"o.ter# """""!area-of-dis-"inner### !define"!area-of-ring"o.ter inner#" ""!-"!*"3.14"!*"o.ter"o.ter## """""!*"3.14"!*"inner inner####

The de)inition on the le)t composes au8iliar$ )unctions, Designing it helped us brea. up the original problem into smaller! more easil$ sol+able problems, Reading it reminds us o) our reasoning that the area is the di))erence between the area o) the )ull dis. and the area o) the hole, In contrast! the de)inition on the right re?uires a reader to reconstruct the idea that the two sube8pressions compute the area o) two dis.s, Furthermore! we would ha+e had to produce the right de)inition in one monolithic bloc.! without bene)it o) di+iding the problem2sol+ing process into smaller steps, For a small program such as area-of-ring! the di))erences between the two st$les are minor, For large programs! howe+er! using au8iliar$ )unctions is not an option but a necessit$, That is! e+en i) we are as.ed to write a single program! we should consider brea.ing it up into se+eral small programs and C@MP@SI-= them as needed, Although we are not $et in a position to de+elop trul$ large programs! we can still get a )eeling )or the idea b$ de+eloping two +ersions in parallel, The )irst subsection contrasts the two de+elopment st$les with an e8ample )rom the business domain, It demonstrates how brea.ing up a program into se+eral )unction de)initions can greatl$ increase our con)idence in the correctness o) the o+erall program, The second subsection introduces the concept o) a +ariable de)inition! which is an additional important ingredient )or the de+elopment o) programs, The last subsection proposes some e8ercises,

(#$ Composing +unctions


Consider the )ollowing problem: Imagine the owner o) a mo+ie theater who has complete )reedom in setting tic.et prices, The more he charges! the )ewer the people who can a))ord tic.ets, In a recent e8periment the owner determined a precise relationship between the price o) a tic.et and a+erage attendance, At a price o) Q7,'' per tic.et! (&' people attend a per)ormance, Decreasing the price b$ a dime /Q,('0 increases attendance b$ (7, An)ortunatel$! the increased attendance also comes at an increased cost, #+er$ per)ormance costs the owner Q(<', #ach attendee costs another )our cents /Q','60, The owner would li.e to .now the e8act relationship between pro)it and tic.et price so that he can determine the price at which he can ma.e the highest pro)it, 1hile the tas. is clear! how to go about it is not, All we can sa$ at this point is that se+eral ?uantities depend on each other, 1hen we are con)ronted with such a situation! it is best to tease out the +arious dependencies one at a time: (, *rofit is the di))erence between re+enue and costs, &, The reven e is e8clusi+el$ generated b$ the sale o) tic.ets, It is the product o) tic.et price and number o) attendees, 5, The costs consist o) two parts: a )i8ed part /Q(<'0 and a +ariable part that depends on the number o) attendees, 6, Finall$! the problem statement also speci)ies how the number o) attendees depends on the tic.et price, "etCs )ormulate a )unction )or each o) these dependenciesE a)ter all! )unctions compute how ?uantities depend on each other, 1e start with contracts! headers! and purpose statements, Here is the one )or profit:
66"profit":"n.m8er""-/""n.m8er 66"to"comp.te"the"profit"as"the"difference"8etween"re0en.e"and costs 66"at"some"gi0en"tic-et-price !define"!profit"tic-et-price#"...#

It depends on the tic.et price because both re+enue and cost depend on the tic.et price, Here are the remaining three:
66"re0en.e":"n.m8er""-/""n.m8er

66"to"comp.te"the"re0en.e<"gi0en"tic-et-price" !define"!re0en.e"tic-et-price#"...# 66"cost":"n.m8er""-/""n.m8er 66"to"comp.te"the"costs<"gi0en"tic-et-price !define"!cost"tic-et-price#"...# 66"attendees":"n.m8er""-/""n.m8er 66"to"comp.te"the"n.m8er"of"attendees<"gi0en"tic-et-price !define"!attendees"tic-et-price#"...#

#ach purpose statement is a rough transliteration o) some part o) the problem statement, E ercise !<1<1< The ne8t step is to ma.e up e8amples )or each o) the )unctions, Determine how man$ attendees can a))ord a show at a tic.et price o) Q5,''! Q6,''! and Q7,'', Ase the e8amples to )ormulate a general rule that shows how to compute the number o) attendees )rom the tic.et price, Ma.e up more e8amples i) needed, Solution E ercise !<1<2< Ase the results o) e8ercise 5,(,( to determine how much it costs to run a show at Q5,''! Q6,''! and Q7,'', Also determine how much re+enue each show produces at those prices, Finall$! )igure out how much pro)it the monopolistic mo+ie owner can ma.e with each show, 1hich is the best price /o) these three0 )or ma8imi*ing the pro)itH Solution @nce we ha+e written down the basic material about our )unctions and calculated out se+eral e8amples! we can replace the DD...CC with Scheme e8pressions, The le)t column o) )igure 7 contains complete de)initions o) all )our )unctions, The profit )unction computes its result as the di))erence between the result o) re0en.e and cost! Fust as the problem anal$sis and purpose statement suggest, The computation o) both depends on tic-et-price! which is what the applications sa$, To compute the re+enue! we )irst compute the number o) attendees )or the gi+en tic-et-price and multipl$ it with tic-et-price, Similarl$! to compute the cost we add the )i8ed portion o) the cost to the +ariable part! which is the product o) the number o) attendees and %.%4 /)our cents0, Finall$! the computation o) the number o) attendees also )ollows the problem statement, The base attendance at a price o) )i+e dollars is (&'! and )or each (' cents less than )i+e dollars! (7 more attendees show up,

66"=ow"to"design"a"program" !define"!profit"tic-et-price# ""!-"!re0en.e"tic-et-price# """""!cost"tic-et-price### !define"!re0en.e"tic-et-price# ""!*""!attendees"tic-et-price# tic-et-price## !define"!cost"tic-et-price# ""!+"1$%" """""!*".%4"!attendees"tic-etprice#### !define"!attendees"tic-et-price# ""!+"12% """""!*"!/"15".1%#"!-"5.%% tic-et-price####

66"=ow"not"to"design"a program" !define"!profit"price# ""!-"!*"!+"12% """!*"!/"15".1%# """"""!-"5.%% price### price# """""!+"1$%" !*".%4 """!+"12% """"""!*"!/"15".1%# "!-"5.%% price#######

Figure $' Two wa$s to e8press the profit program Instead o) de+eloping a )unction per dependenc$ in the problem statement! we could ha+e tried to e8press the relationship between the tic.et price and the ownerCs pro)it in a single )unction, The right column in )igure 7 shows the most straight)orward wa$ o) doing so, And indeed! it is eas$ to chec. that the two pro)it programs in )igure 7 produce the same pro)it when gi+en the same tic.et price, Still! it is also ob+ious that while the arrangement on the le)t con+e$s the intention behind the program directl$! the program on the right is nearl$ impossible to understand, 1orse! i) we are as.ed to modi)$ some aspect o) the program! sa$! the relationship between the number o) attendees and the price o) the tic.et! we can do this )or the le)t column in a small amount o) time! but we need to spend a much longer time )or the right one, Based on our e8perience! we thus )ormulate the )irst and most important guideline o) programming:

=uideline on Au8iliar$ Functions


Formulate au8iliar$ )unction de)initions )or e+er$ dependenc$ between ?uantities mentioned in the problem statement or disco+ered with e8ample calculations, Sometimes we will )ind that some o) the re?uired )unctions are alread$ a+ailable as programs )or other problems, Indeed! we ha+e alread$ encountered such an e8ample: area-of-dis-, At other times! we will ma.e a list o) )unctions and de+elop each one separatel$, 1e ma$ then )ind that some o) the )unctions! such as attendees! are use)ul in se+eral other de)initions! leading to a networ.2li.e relationship among )unctions, E ercise !<1<!< Determine the pro)it that the mo+ie owner ma.es at Q5,''! Q6,''! and Q7,'' using the program de)initions in both columns, Ma.e sure that the results are the same as those predicted in e8ercise 5,(,&, Solution

E ercise !<1<#< A)ter stud$ing the cost structure o) a show! the owner disco+ered se+eral wa$s o) lowering the cost, As a result o) his impro+ements! he no longer has a )i8ed cost, He now simpl$ pa$s Q(,7' per attendee, Modi)$ both programs to re)lect this change, 1hen the programs are modi)ied! test them again with tic.et prices o) Q5,''! Q6,''! and Q7,'' and compare the results, Solution

(#" 'aria&le Definitions


De)ining 4ariables 1hen a number occurs man$ times in our program/s0! we should gi+e it a name using a 4ARIAB"# D#FI-ITI@-! which associates a name with a +alue, @ne e8ample is 3.14! which we ha+e used in place o) , Here is how we could gi+e this number a name:
!define"3I"3.14#

-ow! e+er$ time we re)er to 3I! DrScheme replaces it with 3.14, Asing a name )or a constant ma.es it easier to replace it with a di))erent +alue, Suppose our program contains the de)inition )or 3I! and we decide that we need a better appro8imation o) )or the entire program, B$ changing the de)inition to
!define"3I"3.1415,#

the impro+ement is used e+er$where where we use 3I, I) we didnCt ha+e a name li.e 3I )or ! we would ha+e to )ind and all instances o) 3.14 in the program and replace them with 3.1415,, "et us )ormulate this obser+ation as our second guideline:

=uideline on 4ariable De)initions


=i+e names to )re?uentl$ used constants and use the names instead o) the constants in programs, Initiall$! we wonCt use man$ +ariable de)initions )or constants! because our programs are small, But! as we learn to write larger programs! we will ma.e more use o) +ariable de)initions, As we will see! the abilit$ to ha+e a single point o) control )or changes is important )or +ariable and )unction de)initions,

E ercise !<2<1< Pro+ide +ariable de)initions )or all constants that appear in the pro)it program o) )igure 7 and replace the constants with their names, Solution

(#( +inger E,ercises on Composing +unctions


Asing DD...CC E ercise !<!<1< The Anited States uses the )ng!ish s$stem o) /length0 measurements, The rest o) the world uses the metric s$stem, So! people who tra+el abroad and companies that trade with )oreign partners o)ten need to con+ert #nglish measurements to metric ones and +ice +ersa, Here is a table that shows the si8 maFor units o) length measurements o) the #nglish s$stem:(& #nglish ( inch ( foot ( %ard ( rod ( furlong ( mile metric O &,76 cm O (& in, O5 )t, O 7/(K&0 $d, O 6' rd, O< )l,

De+elop the )unctions inches-/cm! feet-/inches! yards-/feet! rods-/yards! furlongs-/rods! and miles-/furlongs, Then de+elop the )unctions feet-/cm! yards-/cm! rods-/inches! and miles-/feet, >int' Reuse )unctions as much as possible, Ase +ariable de)initions to speci)$ constants, Solution E ercise !<!<2< De+elop the program 0o+.me-c2+inder, It consumes the radius o) a c$linderCs base dis. and its heightE it computes the +olume o) the c$linder, Solution E ercise !<!<!< De+elop area-c2+inder, The program consumes the radius o) the c$linderCs base dis. and its height, Its result is the sur)ace area o) the c$linder, Solution

E ercise !<!<#< De+elop the )unction area-pipe, It computes the sur)ace area o) a pipe! which is an open c$linder, The program consumes three +alues: the pipeCs inner radius! its length! and the thic.ness o) its wall, De+elop two +ersions: a program that consists o) a single de)inition and a program that consists o) se+eral )unction de)initions, 1hich one e+o.es more con)idenceH Solution E ercise !<!<$< De+elop the program height! which computes the height that a roc.et reaches in a gi+en amount o) time, I) the roc.et accelerates at a constant rate g! it reaches a speed o) g P t in t time units and a height o) (K& T v T t where v is the speed at t, Solution E ercise !<!<&< Recall the program Fahrenheit-/Celsius )rom e8ercise &,&,(, The program consumes a temperature measured in Fahrenheit and produces the Celsius e?ui+alent, De+elop the program Celsius-/Fahrenheit! which consumes a temperature measured in Celsius and produces the Fahrenheit e?ui+alent, -ow consider the )unction
66"I":"n.m8er""-/""n.m8er 66"to"con0ert"a">ahrenheit"temperat.re"to"7e+si.s"and"8ac-" !define"!I"f# ""!Celsius-/Fahrenheit"!Fahrenheit-/Celsius"f###

#+aluate !I"32# b$ hand and using DrSchemeCs stepper, 1hat does this suggest about the composition o) the two )unctionsH Solution See The #or!d 1oo$ )ncyc!opedia 1993! 1eights and Measurements,

(&

Section # Conditional E pressions and Functions

For man$ problems! computer programs must deal with di))erent situations in di))erent wa$s, A game program ma$ ha+e to determine whether an obFectCs speed is in some range or whether it is located in some speci)ic area o) the screen, For an engine control program! a condition ma$ describe whether or when a +al+e is to be opened, To deal with conditions! we need to ha+e a wa$ o) sa$ing a condition is true or )alseE we need a new class o) +alues! which! b$ con+ention! are called B@@"#A- /or truth0 +alues, This section introduces booleans! e8pressions that e+aluate to Booleans! and e8pressions that compute +alues depending on the boolean result o) some e+aluation,

)#$ Booleans and Relations


Boolean @perations Consider the )ollowing problem statement: Compan$ N3M G Co, pa$s all its emplo$ees Q(& per hour, A t$pical emplo$ee wor.s between &' and 97 hours per wee., De+elop a program that determines the wage o) an emplo$ee )rom the number o) hours o) wor.! if the n mber is -ithin the proper range, The italic words highlight the new part /compared to section &,50, The$ impl$ that the program must deal with its input in one wa$ i) it is in the legitimate range! and in a di))erent wa$ i) it is not, In short! Fust as people need to reason about conditions! programs must compute in a conditional manner, Conditions are nothing new, In mathematics we tal. o) true and )alse claims! which are conditions, For e8ample! a number ma$ be e?ual to! less than! or greater than some other number, I) + and y are numbers! we state these three claims about + and y with (, + O y: DD+ is e?ual to yCCE &, + U y: DD+ is strictl$ less than yCCE 5, + S y: DD+ is strictl$ greater than yCC, For an$ speci)ic pair o) /real0 numbers! e8actl$ one o) these claims holds, I) + O 6 and y O 7! the second claim is a true statement! and the others are )alse, I) + O 7 and y O 6! howe+er! the third claim is true! and the others are )alse, In general! a claim is true )or some +alues o) the +ariables and )alse )or others, In addition to determining whether an atomic claim holds in a gi+en situation! it is sometimes important to determine whether combinations o) claims hold, Consider the three claims abo+e! which we can combine in se+eral wa$s:

(, + O y &, + O y 5, + O y

and or or

+Uy +Uy +Uy,

and or

+Sy +Sy

The )irst compound claim is )alse because no matter what numbers we pic. )or + and y! two o) the three claims are )alse, The second compound claim! howe+er! alwa$s holds no matter what numbers we pic. )or + and y, Finall$! the third .ind o) compound claim is the most important o) all! because it is true in some cases and )alse in others, For e8ample! it holds when + O 6! y O 6 and + O 6! y O 7! but it is )alse i) + O 7 and y O 5, "i.e mathematics! Scheme has DDwordsCC )or e8pressing truth and )alsit$! )or stating atomic claims! )or combining claims into compound claims! and )or e8pressing that a claim is true or )alse, The DDwordCC )or true is tr.e and the DDwordCC )or )alse is fa+se, I) a claim concerns the relationship between two numbers! it can t$picall$ be e8pressed with a R#"ATI@-A" @P#RATI@-! )or e8ample! &! ?! and /, Translating the three mathematical claims )rom abo+e )ollows our well2.nown pattern o) writing a le)t parenthesis! )ollowed b$ the operator! its arguments! and a right parenthesis: (, !&"*"2#: DD+ is e?ual to yCCE &, !?"*"2#: DD+ is strictl$ less than yCCE and 5, !/"*"2#: DD+ is strictl$ greater than yCC, 1e will also encounter ?& and /& as relational operators, A Scheme e8pression that compares numbers has a result Fust li.e an$ other Scheme e8pression, The result! howe+er! is tr.e or fa+se! not a number, That is! when an atomic Scheme claim about two numbers is true! it e+aluates to tr.e, For e8ample!
""!?"4"5#" &"tr.e

Similarl$! a )alse claim e+aluates to fa+se:


""!&"4"5#" &"fa+se

#8pressing compound conditions in Scheme is e?uall$ natural, Suppose we want to combine !&"*"2# and !?"2"@# so that the compound claim holds i) both conditions are true, In Scheme we would write
!and"!&"*"2#"!?"2"@##

to e8press this relationship, Similarl$! i) we want to )ormulate a compound claim that is true i) /at least0 one o) two claim holds! we write
!or"!&"*"2#"!?"2"@##

Finall$! when we write something such as


!not"!&"*"2##

we state that we wish the negation o) a claim to be true,(5 Compound conditions! li.e atomic conditions! e+aluate to tr.e or fa+se, Consider the )ollowing compound condition:
!and"!&"5"5#"!?"5" ##

It consists o) two atomic claims: !&"5"5# and !?"5" #, Both e+aluate to tr.e! and there)ore the e+aluation o) the and2e8pression continues as )ollows:
""..." &"!and"tr.e"tr.e# &"tr.e

The last step )ollows because! i) both parts o) an and2e8pression are tr.e! the entire e8pression e+aluates to tr.e, In contrast! i) one o) the two claims in an and2e8pression e+aluates to fa+se! the and2e8pression e+aluates to fa+se:
""!and"!&"5"5#"!?"5"5## &"!and"tr.e"fa+se# &"fa+se

The e+aluation rules )or or and not are similarl$ intuiti+e, The ne8t )ew sections will e8plain wh$ programming re?uires )ormulating conditions and reasoning about them, E ercise #<1<1< 1hat are the results o) the )ollowing Scheme conditionsH (, !and"!/"4"3#"!?&"1%"1%%## &, !or"!/"4"3#"!&"1%"1%%##

5, !not"!&"2"3##

Solution

E ercise #<1<2< 1hat are the results o) (, !/"*"3# &, !and"!/"4"*#"!/"*"3## 5, !&"!*"*"*#"*# )or /a0 *"&"4! /b0 *"&"2! and /c0 *"&"7/2 H Solution

)#" +unctions that Test Conditions


Testing Here is a simple )unction that tests some condition about a number:
66"is-5A":"n.m8er""-/""8oo+ean 66"to"determine"whether"n"is"e).a+"to"5 !define"!is-5A"n# ""!&"n"5##

The )unction produces tr.e i)! and onl$ i)! its input is e?ual to 5, Its contract contains one no+el element: the word 8oo+ean, Just li.e n.m8er! 8oo+ean represents a class o) +alues that is built into Scheme, Anli.e n.m8er! 8oo+ean consists o) Fust two +alues: tr.e and fa+se, Here is a slightl$ more interesting )unction with a boolean output:
66"is-8etween-5- A":"n.m8er""-/""8oo+ean 66"to"determine"whether"n"is"8etween"5"and" "!e*c+.si0e# !define"!is-8etween-5- A"n# ""!and"!?"5"n#"!?"n" ###

It consumes a number and produces tr.e i) the number is between! but does not include! 5 and , @ne good wa$ to understand the )unction is to sa$ that it describes the )ollowing inter+al on the number line:

Inter1al 5oundaries: An inter+al boundar$ mar.ed with DD/CC or DD0CC is e8cluded )rom the inter+alE an inter+al boundar$ mar.ed with DDVCC or DDWCC is included, The )ollowing third )unction )rom numbers to boolean +alues represents the most complicated )orm o) inter+al:
66"is-8etween-5- -or-o0er-1%A":"n.m8er""-/""8oo+ean 66"to"determine"whether"n"is"8etween"5"and" "!e*c+.si0e#" 66"or"+arger"than"or"e).a+"to"1% !define"!is-8etween-5- -or-o0er-1%A"n# ""!or"!is-8etween-5- A"n#"!/&"n"1%###

The )unction returns tr.e )or two portions o) the number line:

The le)t part o) the inter+al is the portion between! but not including! 5 and E the right one is the in)inite line starting at! and including! 1%, An$ point on those two portions o) the line satis)ies the condition e8pressed in the )unction is-8etween-5- -or-o0er1%A, All three )unctions test numeric conditions, To design or to comprehend such )unctions! we must understand inter+als and combinations /also .nown as unions0 o) inter+als, The )ollowing e8ercises practice this important s.ill, E ercise #<2<1< Translate the )ollowing )i+e inter+als on the real line into Scheme )unctions that accept a number and return tr.e i) the number is in the inter+al and fa+se i) it is outside: (, the inter+al /5!;W:

&, the inter+al V5!;W:

5, the inter+al V5!>0:

6, the union o) /(!50 and />!((0:

7, and the range o) numbers o tside o) V(!5W,

Solution E ercise #<2<2< Translate the )ollowing three Scheme )unctions into inter+als on the line o) reals:
1."!define"!in-inter0a+-1A"*# """""""!and"!?"-3"*#"!?"*"%### 2."!define"!in-inter0a+-2A"*# """""""!or"!?"*"1#"!/"*"2### 3."!define"!in-inter0a+-3A"*# """""""!not"!and"!?&"1"*#"!?&"*"5####

Also )ormulate contracts and purpose statements )or the three )unctions, #+aluate the )ollowing e8pressions b$ hand: (, !in-inter0a+-1A"-2# &, !in-inter0a+-2A"-2#

5, !in-inter0a+-3A"-2# Show the important steps, Ase the pictures to chec. $our results, Solution

E ercise #<2<!< Mathematical e?uations in one +ariable are claims about an un.nown number, For e8ample! the ?uadratic e?uation

is a claim concerning some un.nown number +, For + O - (! the claim holds:

For + O (! it doesnCt! because

and 6 is not e?ual to ', A number )or which the claim holds is called a so! tion to the e?uation, 1e can use Scheme to )ormulate e?uational conditions as a )unction, I) someone then claims to ha+e a solution! we can use the )unction to test whether the proposed solution is! in )act! a solution, @ur running e8ample corresponds to the )unction
66"e).ation1":"n.m8er""-/""8oo+ean 66"to"determine"whether"*"is"a"so+.tion"for"+2""+""2""B""+""+""1""& % !define"!e).ation1"*# ""!&"!+"!*"*"*#"!+"!*"2"*#"1##"%##

1hen we appl$ e).ation1 to some number! we get tr.e or fa+se:


""!e).ation1"-1# &"tr.e

and
""!e).ation1"+1# &"fa+se

Translate the )ollowing e?uations into Scheme )unctions: (, 6 P n I & O 9& &, & P n& O ('&

5, 6 P n& I 9 P n I & O 69&

Determine whether 1%! 12! or 14 are solutions o) these e?uations,

Solution

E ercise #<2<#< #?uations are not onl$ ubi?uitous in mathematics! the$ are also hea+il$ used in programming, 1e ha+e used e?uations to state what a )unction should do with e8amples! we ha+e used them to e+aluate e8pressions b$ hand! and we ha+e added them as test cases to the Definitions

Testing window, For e8ample! i) our goal is to de)ine Fahrenheit-/Celsius! we might ha+e added our e8amples as test cases as )ollows:
66"test"e*pression: !Fahrenheit-/Celsius"32# 66"e*pected"res.+t: %

and
66"test"e*pression: !Fahrenheit-/Celsius"212# 66"e*pected"res.+t:" 1%%

A)ter clic.ing the 5*ec.te button we can compare the two numbers, I) the$ are e?ual! we .now our )unction wor.s, As our results become more and more comple8! comparing +alues becomes more and more tedious, Asing &! we can instead translate these e?uations into claims:
!&"!Fahrenheit-/Celsius"32# """%#

and
!&"!Fahrenheit-/Celsius"212# """1%%#

-ow! i) all claims e+aluate to tr.e! we .now that our )unction wor.s )or the speci)ied e8amples, I) we see a fa+se an$where! something is still wrong, Re)ormulate the test cases )or e8ercises &,&,(! &,&,&! &,&,5! and &,&,6 as claims,

Testing: 1riting tests as claims is good practice! though we need to .now more about e?ualit$ to de+elop good automatic tests, To do so! we resume the discussion o) e?ualit$ and testing in section (;,<, Solution

)#( Conditionals and Conditional +unctions


Conditionals Some ban.s pa$ di))erent le+els o) interest )or sa+ing accounts, The more a customer deposits! the more the ban. pa$s, In such arrangements! the interest rate depends on the interva! into which the sa+ings amount )alls, To assist their ban. cler.s! ban.s use interest2rate )unctions, An interest )unction consumes the amount that a customer wishes to deposit and responds with the interest that the customer recei+es )or this amount o) mone$, @ur interest rate )unction must determine which o) se+eral conditions holds )or the input, 1e sa$ that the )unction is a C@-DITI@-A" FA-CTI@-! and we )ormulate the de)inition o) such )unctions using C@-DITI@-A" #NPR#SSI@-S, The general shape o) a conditional e8pression is
!cond ""9).estion"answer: or ""... ""9else"answer:# The dots indicate that a cond2e8pression ma$ contain an arbitrar$ number o) cond2lines, #ach cond2line! also called a cond2clause! contains two e8pressions! called C@-DITI@and A-S1#R, A condition is a conditional e8pression that in+ol+es the parametersE the !cond ""9).estion"answer: ""... ""9).estion"answer:#

answer is a Scheme e8pression that computes the result )rom the parameters and other data i) the conditional e8pression holds,(6 Conditional e8pressions are the most complicated )orm o) e8pressions we ha+e encountered and will encounter, It is there)ore eas$ to ma.e mista.es when we write them down, Compare the )ollowing two parenthesi*ed e8pressions:
!cond ""9!?"n"1%#"5.%: ""9!?"n"2%#"5: ""9!?"n"3%#"tr.e:# !cond ""9!?"n"1%#"3%"12: ""9!/"n"25#"fa+se: ""9!/"n"2%#"%:# cond2line contains two

The le)t one is a +alid cond2e8pression because each e8pressions, In contrast! the right one is not a +alid cond2e8pression, Its )irst line contains three e8pressions instead o) two, 1hen Scheme e+aluates a cond2e8pression! it determines the +alue o) each condition! one b$ one, A condition must e+aluate to tr.e or fa+se, For the )irst condition that e+aluates to tr.e! Scheme e+aluates the corresponding answer! and the +alue o) the answer is the +alue o) the entire cond2e8pression, I) the last condition is else and all other conditions )ail! the answer )or the cond is the +alue o) the last answer e8pression,(7

Here are two simple e8amples:


!cond ""9!?&"n"1%%%#".%4%: ""9!?&"n"5%%%#".%45: ""9!?&"n"1%%%%#".%55: ""9else".% %:# I) we e+aluate to fa+se in both e8pressions, For the e8pression on the le)t the )ourth condition! !/"2%%%%"1%%%%#! e+aluates to tr.e and there)ore the answer is %. %, For the e8pression on the right! the else clause speci)ies what the result o) the entire e8pression is, In contrast! i) n is 1%%%%! the +alue is .%55 because )or both e8pressions! !?&"1%%%%"1%%%# and !?& 1%%%%"5%%%# e+aluate to fa+se and !?&"1%%%%"1%%%%# e+aluates to tr.e, !cond ""9!?&"n"1%%%#".%4%: ""9!?&"n"5%%%#".%45: ""9!?&"n"1%%%%#".%55: ""9!/"n"1%%%%#".% %:# replace n with 2%%%%! the )irst three conditions

E ercise #<!<1< Decide which o) the )ollowing two cond2e8pressions is legal:


!cond ""9!?"n"1%#"2%: ""9!/"n"2%#"%: ""9else"1:# !cond"9!?"n"1%#"2%: """"""9*"1%"n: !cond ""9!?"n"1%#"2%: ""9!and"!/"n"2%#"!?&"n"3%##: ""9else"1:#

#8plain wh$ the other one is not, 1h$ is the )ollowing illegalH Velse 777W0 E
"Co+.tion

E ercise #<!<2< 1hat is the +alue o)


!cond ""9!?&"n"1%%%#".%4%: ""9!?&"n"5%%%#".%45: ""9!?&"n"1%%%%#".%55: ""9!/"n"1%%%%#".% %:#

when n is /a0 5%%! /b0 2$%%! and /c0 15%%%H E ercise #<!<!< 1hat is the +alue o)
!cond ""9!?&"n"1%%%#"!*".%4%"1%%%#: ""9!?&"n"5%%%#"!+"!*"1%%%".%4%#" ""!*"!-"n"1%%%#".%45##: ""9else"!+"!*"1%%%".%4%#" """!*"4%%%".%45# """!*"!-"n"1%%%%#".%55##:#

Solution

when n is /a0 5%%! /b0 2$%%! and /c0 15%%%H

Solution

1ith the help o) cond2e8pressions! we can now de)ine the interest rate )unction that we mentioned at the beginning o) this section, Suppose the ban. pa$s 6R )or deposits o) up

to Q(!''' /inclusi+e0! 6,7R )or deposits o) up to Q7!''' /inclusi+e0! and 7R )or deposits o) more than Q7!''', Clearl$! the )unction consumes one number and produces one:
66"interest-rate":"n.m8er""-/""n.m8er 66"to"determine"the"interest"rate"for"the"gi0en"amo.nt !define"!interest-rate"amo.nt#"...#

Furthermore! the problem statement pro+ides three e8amples: (, !&"!interest-rate"1%%%#".%4%# &, !&"!interest-rate"5%%%#".%45# 5, !&"!interest-rate"$%%%#".%5%# Recall that e8amples are now )ormulated as boolean e8pressions when possible, The bod$ o) the )unction must be a cond2e8pression that distinguishes the three cases mentioned in the problem statement, Here is a s.etch:
""!cond """"9!?&"amo.nt"1%%%#"...: """"9!?&"amo.nt"5%%%#"...: """"9!/"amo.nt"5%%%#"...:#

Asing the e8amples and the outline o) the cond2e8pression! the answers are eas$:
!define"!interest-rate"amo.nt# ""!cond """"9!?&"amo.nt"1%%%#"%.%4%: """"9!?&"amo.nt"5%%%#"%.%45: """"9!/"amo.nt"5%%%#"%.%5%:##

Since we .now that the )unction re?uires onl$ three cases! we can also replace the last condition with else:
!define"!interest-rate"amo.nt# ""!cond """"9!?&"amo.nt"1%%%#"%.%4%: """"9!?&"amo.nt"5%%%#"%.%45: """"9else"%.%5%:##

1hen we appl$ interest-rate to an amount! sa$! 4%%%! the calculation proceeds as usual, Scheme )irst copies the bod$ o) the )unction and replaces amo.nt b$ 4%%%:
""!interest-rate"4%%%# &"!cond """"9!?&"4%%%"1%%%#"%.%4%: """"9!?&"4%%%"5%%%#"%.%45: """"9else"%.%5%:#

&"%.%45"

The )irst condition is fa+se but the second one is tr.e! so the result is %.%45 or 6,7R, The e+aluation would proceed in the same manner i) we had used the +ariant o) the )unction with !/"amo.nt"5%%%# instead o) else,

)#) Designing Conditional +unctions


De+eloping conditional )unctions is more di))icult than designing a plain )unction, The .e$ is to recogni*e that the problem statement lists cases and to identi)$ the di))erent cases, To emphasi*e the importance o) this idea! we introduce and discuss a design recipe )or designing conditional )unctions, The new recipe introduces a new step! DATA A-A"3SIS! which re?uires a programmer to understand the di))erent situations that the problem statement discusses, It also modi)ies the #8amples and the Bod$ steps o) the design recipe in section &,7: Data +nal%sis and Definition' A)ter we determine that a problem statement deals with distinct situations! we must identi)$ all o) them, The second step is a DATA D#FI-ITI@-! an idea that we will e8plore a lot more, For numeric )unctions! a good strateg$ is to draw a number line and to identi)$ the inter+als that correspond to a speci)ic situation, Consider the contract )or the interest-rate )unction:
""66"interest-rate":"n.m8er""-/""n.m8er ""66"to"determine"the"interest"rate"for"the"gi0en"amo.nt"/& % ""!define"!interest-rate"amo.nt#"...#

It inputs non2negati+e numbers and produces answers )or three distinct situations:

For )unctions that process booleans! the cond2e8pression must distinguish between e8actl$ two situations: tr.e and fa+se, 1e will soon encounter other )orms o) data that re?uire case2based reasoning, Function E amples' @ur choice o) e8amples accounts )or the distinct situations, At a minimum! we must de+elop one )unction e8ample per situation, I) we characteri*ed the situations as numeric inter+als! the e8amples should also include all borderline cases,

For our interest-rate )unction! we should use %! 1%%%! and 5%%% as borderline cases, In addition! we should pic. numbers li.e 5%%! 2%%%! and 7%%% to test the interiors o) the three inter+als, The Function 5od% 22 Conditions' The )unctionCs bod$ must consist o) a cond2e8pression that has as man$ clauses as there are distinct situations, This re?uirement immediatel$ suggests the )ollowing bod$ o) our solution:
!define"!interest-rate"amo.nt# ""!cond """"9..."...: """"9..."...: """"9..."...:##

-e8t we must )ormulate the conditions that characteri*e each situation, The conditions are claims about the )unctionCs parameters! e8pressed with SchemeCs relational operators or with our own )unctions, The number line )rom our e8ample translates into the )ollowing three conditions: (, !and"!?&"%"amo.nt#"!?&"amo.nt"1%%%## &, !and"!?"1%%%"amo.nt#"!?&"amo.nt"5%%%## 5, !?"5%%%"amo.nt# Adding these conditions to the )unction produces a better appro8imation o) the )inal de)inition:
!define"!interest-rate"amo.nt# ""!cond """"9!and"!?&"%"amo.nt#"!?&"amo.nt"1%%%##"...: """"9!and"!?"1%%%"amo.nt#"!?&"amo.nt"5%%%##"...: """"9!/"amo.nt"5%%%#"...:##

At this stage! a programmer should chec. that the chosen conditions distinguish inputs in an appropriate manner, Speci)icall$! i) some input belongs to a particular situation and cond2line! the preceding conditions should e+aluate to fa+se and the condition o) the line should e+aluate to tr.e, The Function 5od% 22 +ns3ers' Finall$! it is time to determine what the )unction should produce )or each cond2 clause, More concretel$! we consider each line in the cond2e8pression separatel$! assuming that the condition holds, In our e8ample! the results are directl$ speci)ied b$ the problem statement, The$ are 4.%! 4.5! and 5.%, In more complicated e8amples! we ma$ ha+e to determine

an e8pression )or each cond2answer )ollowing the suggestion o) our )irst design recipe, >int' I) the answers )or each cond2clause are comple8! it is good practice to de+elop one answer at a time, Assume that the condition e+aluates to tr.e! and de+elop an answer using the parameters! primiti+es! and other )unctions, Then appl$ the )unction to inputs that )orce the e+aluation o) this new answer, It is legitimate to lea+e DD...CC in place o) the remaining answers, Simplification' 1hen the de)inition is complete and tested! a programmer might wish to chec. whether the conditions can be simpli)ied, In our e8ample! we .now that amo.nt is alwa$s greater than or e?ual to %! so the )irst condition could be )ormulated as
!?&"amo.nt"1%%%#

Furthermore! we .now that cond2e8pressions are e+aluated se?uentiall$, That is! b$ the time the second condition is e+aluated the )irst one must ha+e produced fa+se, Hence we .now that the amount is not less than or e?ual to 1%%%! which ma.es the le)t component o) the second condition super)luous, The appropriatel$ simpli)ied s.etch o) interest-rate is as )ollows:
!define"!interest-rate"amo.nt# ""!cond """"9!?&"amo.nt"1%%%#"...: """"9!?&"amo.nt"5%%%#"...: """"9!/"amo.nt"5%%%#"...:##

Figure 9 summari*es these suggestions on the design o) conditional )unctions, Read it in conFunction with )igure 6 and compare the two rows )or DDBod$,CC Reread the table when designing a conditional )unctionL

Phase Data Anal$sis

=oal to determine the distinct situations a )unction deals with #8amples to pro+ide an e8ample per situation Bod$ /(0 to )ormulate a Conditions conditional e8pression Bod$ /&0 Answers to )ormulate the answers )or the cond2clauses

Acti+it$ inspect the problem statement )or distinct situations enumerate all possible situations choose at least one e8ample per situation )or inter+als or enumerations! the e8amples must include borderline cases write down the s.eleton o) a cond e8pression! with one clause per situation )ormulate one condition per situation! using the parameters ensure that the conditions distinguish the e8amples appropriatel$ deal with each cond2line separate!y assume the condition holds and de+elop a Scheme e8pression that computes the appropriate answer )or this case

Figure &' Designing the bod$ o) a conditional )unction /Ase with the recipe in )igure 6 /pg, 700 E ercise #<#<1< De+elop the )unction interest, "i.e interest-rate! it consumes a deposit amount, Instead o) the rate! it produces the actual amount o) interest that the mone$ earns in a $ear, The ban. pa$s a )lat 6R )or deposits o) up to Q(!'''! a )lat 6,7R per $ear )or deposits o) up to Q7!'''! and a )lat 7R )or deposits o) more than Q7!''', Solution E ercise #<#<2< De+elop the )unction ta*! which consumes the gross pa$ and produces the amount o) ta8 owed, For a gross pa$ o) Q&6' or less! the ta8 is 'RE )or o+er Q&6' and Q6<' or less! the ta8 rate is (7RE and )or an$ pa$ o+er Q6<'! the ta8 rate is &<R, Also de+elop netpa2, The )unction determines the net pa$ o) an emplo$ee )rom the number o) hours wor.ed, The net pay is the gross pa$ minus the ta8, Assume the hourl$ pa$ rate is Q(&, >int' Remember to de+elop au8iliar$ )unctions when a de)inition becomes too large or too comple8 to manage, Solution E ercise #<#<!< Some credit card companies pa$ bac. a small portion o) the charges a customer ma.es o+er a $ear, @ne compan$ returns (, ,&7R )or the )irst Q7'' o) charges!

&, ,7'R )or the ne8t Q(''' /that is! the portion between Q7'' and Q(7''0! 5, ,;7R )or the ne8t Q(''' /that is! the portion between Q(7'' and Q&7''0! 6, and (,'R )or e+er$thing abo+e Q&7'', Thus! a customer who charges Q6'' a $ear recei+es Q(,''! which is ',&7 P (K('' P 6''! and one who charges Q(!6'' a $ear recei+es Q7,;7! which is (,&7 O ',&7 P (K('' P 7'' )or the )irst Q7'' and ',7' P (K('' P >'' O 6,7' )or the ne8t Q>'', Determine b$ hand the pa$2bac.s )or a customer who charged Q&''' and one who charged Q&9'', De)ine the )unction pa2-8ac-! which consumes a charge amount and computes the corresponding pa$2bac. amount, Solution E ercise #<#<#< An e?uation is a claim about numbersE a ?uadratic e?uation is a special .ind o) e?uation, All ?uadratic e?uations /in one +ariable0 ha+e the )ollowing general shape:

In a speci)ic e?uation! a! b and c are replaced b$ numbers! as in

or

The +ariable + represents the un.nown, Depending on the +alue o) *! the two sides o) the e?uation e+aluate to the same +alue /see e8ercise 6,&,50, I) the two sides are e?ual! the claim is trueE otherwise it is )alse, A number that ma.es the claim true is a so! tion, The )irst e?uation has one solution! - (! as we can easil$ chec.:

The second e?uation has two solutions: I ( and - (,

The number o) solutions )or a ?uadratic e?uation depends on the +alues o) a! b! and c, I) the coe))icient a is '! we sa$ the e?uation is degenerate and do not consider how man$ solutions it has, Assuming a is not '! the e?uation has (, two solutions i) b& S 6 P a P c! &, one solution i) b& O 6 P a P c! and 5, no solution i) b& U 6 P a P c, To distinguish this case )rom the degenerate one! we sometimes use the phrase proper ?uadratic e?uation, De+elop the )unction how-man2! which consumes the coe))icients a! 8! and c o) a proper ?uadratic e?uation and determines how man$ solutions the e?uation has:
!how-man2"1"%"-1#"&"2 !how-man2"2"4"2#"&"1

Ma.e up additional e8amples, First determine the number o) solutions b$ hand! then with DrScheme,

How would the )unction change i) we didnCt assume the e?uation was properH Solution

In truth! the operations and and or are di))erent )rom not! which is wh$ the$ are t$peset in di))erent )onts, 1e ignore this minor di))erence )or now,
(5

The use o) brac.ets! that is! 9 and :! in place o) parentheses is optional! but it sets apart the conditional clauses )rom other e8pressions and helps people read )unctions,
(6

I) the cond2e8pression has no else clause and all conditions e+aluate to fa+se! an error is signaled in (eginning"Ct.dent Scheme,
(7

Section $ S%mbolic Information


S$mbols! Images These da$s computers mostl$ process s$mbolic in)ormation such as names! words! directions! or images, All modern programming languages support at least one wa$ o) representing s$mbolic in)ormation, Scheme supports se+eral wa$s to e8press s$mbolic in)ormation: s$mbols! strings! /.e$board0 characters! and images, A symbo! is a se?uence o) .e$board characters(9 preceded b$ a single )orward ?uotation mar.:
'the 'dog 'ate 'a 'choco+ate 'catD 'twoE3 'andFsoFonA

"i.e a number! a s$mbol has no inherent meaning, It is up to the )unctionCs user to relate s$mbolic data and real2world in)ormation! though the connection is t$picall$ ob+ious in a speci)ic conte8t, For e8ample! 'east will usuall$ re)er to the direction where the sun rises! 'professor will be the title o) a person teaching and researching at a uni+ersit$,

Figure (' The planets as images in DrScheme "i.e numbers! s$mbols are atomic pieces o) data, Their purpose is to represent things such as )amil$ and )irst names! Fob titles! commands! announcements! and so on, Scheme pro+ides onl$ one basic operation on s$mbols: s2m8o+&A! a comparison operation, It consumes two s$mbols and produces tr.e i) and onl$ i) the two s$mbols are identical: (, &, 5,

!s2m8o+&A"'=e++o"'=e++o#"&"tr.e

!s2m8o+&A"'=e++o"'=owd2#"&"fa+se

!s2m8o+&A"'=e++o"*#"&"tr.e

i) * stands )or '=e++o

6,

!s2m8o+&A"'=e++o"*#"&"fa+se

i) * stands )or '=owd2

S$mbols were )irst introduced to computing b$ researchers in arti)icial intelligence who wanted to design )unctions that could ha+e con+ersations with people, Consider the )unction rep+2! which replies with some remar. to the )ollowing greetings: DDgood morning!CC DDhow are $ou!CC DDgood a)ternoon!CC and DDgood e+ening,CC #ach o) those short sentences can be represented as a s$mbol: 'GoodHorning! '=ow'reIo.! 'Good'fternoon! and 'Good50ening, Thus! rep+2 consumes a s$mbol and replies with a s$mbol:
66"rep+2":"s2m8o+""-/""s2m8o+ 66"to"determine"a"rep+2"for"the"greeting"s !define"!rep+2"s#"...#

Furthermore! the )unction must distinguish among )our situations! impl$ing! according to our design recipe )rom section 6,6! a )our2clause cond2e8pression:
!define"!rep+2"s# ""!cond """"9!s2m8o+&A"s"'GoodHorning#"...: """"9!s2m8o+&A"s"'=ow'reIo.A#"...: """"9!s2m8o+&A"s"'Good'fternoon#"...: """"9!s2m8o+&A"s"'Good50ening#"...:##

The cond2clauses match the )our s$mbols! which is naturall$ much easier than matching )our inter+als, From this )unction template it is a short step to the )inal )unction, Here is one +ersion o) rep+2:
!define"!rep+2"s# ""!cond """"9!s2m8o+&A"s"'GoodHorning#"'=i: """"9!s2m8o+&A"s"'=ow'reIo.A#"'>ine: """"9!s2m8o+&A"s"'Good'fternoon#"'IJeed'Jap: """"9!s2m8o+&A"s"'Good50ening#"'(o2'mI;ired:##

1e can thin. o) man$ di))erent wa$s o) how to replace the DD...CC in the template with replies, But no matter what we replace them with! the basic template could be de)ined without concern )or the output o) the )unction, 1e will see in subse?uent sections that this )ocus on the input data is actuall$ the norm and that concern )or the output data can be postponed, + Note on Strings: A string is a second )orm o) s$mbolic data, "i.e a s$mbol! a string consists o) a se?uence o) .e$board characters! but the$ are enclosed in string ?uotes:
1the"dog1 1isnKt1 1made"of1 1choco+ate1 1twoE31 1and"so"onA1

In contrast to s$mbols! strings are not atomic, The$ are compound data! which we discuss later in the boo., For now! we use strings as i) the$ were )anc$ s$mbolsE the onl$ operation needed is string&A! which compares two strings the wa$ s2m8o+&A

compares two s$mbols, @therwise we ignore strings! and when we use them! we act as i) the$ were s$mbols, + Note on Images: An image is a third )orm o) s$mbolic data! and it is )un to de+elop )unctions that process images, "i.e s$mbols! images donCt ha+e an$ a priori meaning! but we tend to connect them easil$ with the intended in)ormation, DrScheme supports images: see )igure ;! which shows the beginning o) a )unction that manipulates planet pictures, Images are +alues li.e numbers and booleans, The$ can there)ore be used inside o) e8pressions, Most o)ten though! we gi+e images names because the$ are t$picall$ used b$ se+eral )unctions, I) we donCt li.e the picture! it is then easil$ replaced with a di))erent one /see section 5,&0,

*#$ +inger E,ercises !ith Sym&ols


Teachpac.s E ercise $<1<1< #+aluate !rep+2"'=ow'reIo.A# b$ hand and with DrSchemeCs stepper, Formulate a complete set o) e8amples )or rep+2 as boolean e8pressions /using s2m8o+&A0, Solution E ercise $<1<2< De+elop the )unction chec--g.ess, It consumes two numbers! g.ess and target, Depending on how g.ess relates to target! the )unction produces one o) the )ollowing three answers: ';ooCma++! '3erfect! or ';ooLarge, The )unction implements one part o) a two2pla$er number guessing game, @ne pla$er pic.s a random number between ' and >>>>>, The other pla$erCs goal is to determine this number! called target! with the least number o) guesses, To each guess! the )irst pla$er responds with one o) the three responses that chec--g.ess implements, The )unction chec--g.ess and the teachpac. guess.ss implement the )irst pla$er, The teachpac. pic.s the random number! pops up a window in which the second pla$er can choose digits! and hands o+er the g.ess and the target to chec--g.ess, To pla$ the game! set the teachpac. to guess.ss using the Lang.ageMCet"teachpac- option, Then e+aluate the e8pression
!g.ess-with-g.i"chec--g.ess#

a)ter chec--g.ess has been thoroughl$ tested,

Solution

E ercise $<1<!< De+elop the )unction chec--g.ess3, It implements a larger portion o) the number guessing game o) e8ercise 7,(,& than the )unction chec--g.ess, -ow the teachpac. hands o+er the digits that the user guesses! not the number that the$ )orm,

To simpli)$ the problem a little bit! the game wor.s with onl$ three numbers, Thus! chec--g.ess3 consumes three digits and a number, The )irst digit is the least signi)icant! the third one is the most signi)icant, The number is called target and represents the randoml$ chosen number, Depending on how g.ess! the number determined b$ the three digits! relates to target! chec--g.ess3 produces one o) the )ollowing three answers: ';ooCma++! '3erfect! or ';ooLarge, The rest o) the game is still implemented b$ guess.ss, To pla$ the game with chec-g.ess3! e+aluate
!g.ess-with-g.i-3"chec--g.ess3#

a)ter the )unction has been thoroughl$ tested,

>int' Remember to de+elop an au8iliar$ )unction per concept,

Solution

E ercise $<1<#< De+elop what--ind, The )unction consumes the coe))icients a! 8! and c o) a ?uadratic e?uation, It then determines whether the e?uation is degenerate and! i) not! how man$ solutions the e?uation has, The )unction produces one o) )our s$mbols: 'degenerate! 'two! 'one! or 'none,

>int' Compare with e8ercise 6,6,6,

Solution

E ercise $<1<$< De+elop the )unction chec--co+or, It implements a .e$ portion o) a color guessing game, @ne pla$er pic.s two colors )or two s?uaresE we call those targets, The other one tries to guess which color is assigned to which s?uareE the$ are guesses, The )irst pla$erCs response to a guess is to chec. the colors and to produce one o) the )ollowing answers: (, '3erfect! i) the )irst target is e?ual to the )irst guess and the second target is e?ual to the second guessE &, 'Nne7o+or't7orrect3osition! i) the )irst guess is e?ual to the )irst target or the second guess is e?ual to the second targetE 5, 'Nne7o+orNcc.rs! i) either guess is one o) the two targetsE and 6, 'Jothing7orrect! otherwise,

These )our answers are the onl$ answers that the )irst pla$er gi+es, The second pla$er is to guess the two chosen target colors with as )ew guesses as possible, The )unction chec--co+or simulates the )irst pla$erCs chec.ing action, It consumes )our colorsE )or simplicit$! we assume that a color is a s$mbol! sa$! 'red, The )irst two arguments to chec--co+or are DDtargets!CC the latter two are DDguesses,CC The )unction produces one o) the )our answers, 1hen the )unction is tested! use the teachpac. to master.ss to pla$ the color2guessing game,(; The teachpac. pro+ides the )unction master, #+aluate !master"chec--co+or# and choose colors with the mouse, Solution

-ot all .e$board characters are legal in s$mbols, For e8ample! a blan. space or a comma are illegal,
(9

(;

MasterMind! the commercial +ersion o) this game! is pla$ed in a di))erent manner,

Section & Compound Data, Part 1' Structures


The input o) a )unction is seldom a single measurement /number0! a single switch position /boolean0! or a single name /s$mbol0, Instead! it is almost alwa$s a piece o) data that represents an obFect with man$ properties, #ach propert$ is a piece o) in)ormation, For e8ample! a )unction ma$ consume a record about a CDE the rele+ant in)ormation might include the artistCs name! the CD title! and the price, Similarl$! i) we are to model the mo+ement o) an obFect across a plane with a )unction! we must represent the position o) the obFect in the plane! its speed in each direction! and possibl$ its color, In both cases! we re)er to se+eral pieces o) in)ormation as i) the$ were one: one record and one point, In short! we C@MP@A-D se+eral pieces o) data into a single piece o) data, Scheme pro+ides man$ di))erent methods )or compounding data, In this section! we deal with str ct res, A structure combines a )i8ed number o) +alues into a single piece o) data, In section >! we will encounter a method )or combining an arbitraril$ large number o) +alues into a single piece o) data,

-#$ Structures
Structures Suppose we wish to represent the pi+e!s /colored dots0 on our computer monitors, A pi8el is +er$ much li.e a Cartesian point, It has an + coordinate! which tells us where the pi8el is in the hori*ontal direction! and it has a y coordinate! which tells us where the pi8el is located in the downwards +ertical direction, =i+en the two numbers! we can locate a pi8el on the monitor! and so can a computer program, DrSchemeCs teachpac.s represent pi8els with posn structures, A posn structure combines two numbers, That is! a posn is a single +alue that contains two +alues, 1e can create a posn structure with the operation ma-e-posn! which consumes two numbers and ma.es a posn, For e8ample!
!ma-e-posn"3"4# !ma-e-posn"$" # !ma-e-posn"5"12#

are posn structures, #ach o) these structures has the same status as a number as )ar as computations are concerned, Both primiti+e operations and )unctions can consume and produce structures, -ow consider a )unction that computes how )ar some pi8el is )rom the origin, The contract! header! and purpose statement are eas$ to )ormulate:
66"distance-to-%":"posn""-/""n.m8er 66"to"comp.te"the"distance"of"a-posn"to"the"origin" !define"!distance-to-%"a-posn#"...#

In other words! distance-to-% consumes a single +alue! a posn structure! and produces a single +alue! a number, 1e alread$ ha+e some input e8amples! namel$! the three posn structures mentioned abo+e, 1hat we need ne8t are e8amples that relate inputs and outputs, For points with % as one o) the coordinates! the result is the other coordinate:
""!distance-to-%"!ma-e-posn"%"5## &"5 and ""!distance-to-%"!ma-e-posn"7"%## &"7

In general! we .now )rom geometr$ that the distance )rom the origin to a position with coordinates * and 2 is distance

Thus!
""!distance-to-%"!ma-e-posn"3"4## &"5 ""!distance-to-%"!ma-e-posn"$" ## &"1% ""!distance-to-%"!ma-e-posn"5"12## &"13""

@nce we ha+e e8amples! we can turn our attention to the de)inition o) the )unction, The e8amples impl$ that the design o) distance-to-% doesnCt need to distinguish between di))erent situations, Still! we are stuc. now! because distance-to-% has a single parameter that represents the entire pi8el but we need the two coordinates to compute the distance, Put di))erentl$! we .now how to combine two numbers into a posn structure using ma-e-posn and we donCt .now how to e8tract these numbers )rom a posn structure, Scheme pro+ides operations )or e8tracting +alues )rom structures,(< For posn structures! Scheme supports two such operations: posn-* and posn-2, The )ormer operation e8tracts the + coordinateE the latter e8tracts the y coordinate,

To describe how posn-*! posn-2! and ma-e-posn are related! we can use e?uations that are roughl$ analogous to the e?uations that go+ern addition and subtraction:
""!posn-*"!ma-e-posn"7"%##" &"7

and
""!posn-2"!ma-e-posn"7"%## &"%

The e?uations onl$ con)irm what we alread$ .now, But suppose we introduce the )ollowing de)inition:
""!define"a-posn"!ma-e-posn"7"%##

Then we can use the two operations as )ollows in the Interactions window:
""!posn-*"a-posn#" &"7 ""!posn-2"a-posn# &"%

-aturall$! we can nest such e8pressions:


""!*"!posn-*"a-posn#"7# &"4, ""!+"!posn-2"a-posn#"13# &"13

-ow we .now enough to complete the de)inition o) distance-to-%, 1e .now that the )unctionCs a-posn parameter is a posn structure and that the structure contains two numbers! which we can e8tract with !posn-*"a-posn# and !posn-2"a-posn#, "et us add this .nowledge to our )unction outline:
!define"!distance-to-%"a-posn# ""..."!posn-*"a-posn#"... ""..."!posn-2"a-posn#"...#

Asing this outline and the e8amples! the rest is eas$:


!define"!distance-to-%"a-posn# ""!s)rt """"!+"!s)r"!posn-*"a-posn## """""""!s)r"!posn-2"a-posn#####

The )unction s?uares !posn-*"a-posn# and !posn-2"a-posn#! which represent the + and y coordinates! sums up the results! and ta.es the s?uare root, 1ith DrScheme! we can also ?uic.l$ chec. that our new )unction produces the proper results )or our e8amples, E ercise &<1<1< #+aluate the )ollowing e8pressions:

(, !distance-to-%"!ma-e-posn"3"4## &, !distance-to-%"!ma-e-posn"!*"2"3#"!*"2"4### 5, !distance-to-%"!ma-e-posn"12"!-" "1### b$ hand, Show all steps, Assume that s)r per)orms its computation in a single step, Chec. the results with DrSchemeCs stepper, Solution

-#" E,tended E,ercise. Dra!ing Simple Pictures


Drawing DrScheme pro+ides the graphics teachpac. draw.ss! which introduces simple graphics operations: (, draw-so+id-+ine! which consumes two posn structures! the beginning and the end o) the line on the can+as! and a color, &, draw-so+id-rect! which consumes )our arguments: a posn structure )or the upper2le)t corner o) the rectangle! a number )or the width o) the rectangle! another number )or its height! and a color, 5, draw-so+id-dis-! which consumes three arguments: a posn structure )or the center o) the dis.! a number )or the radius o) the dis.! and a color, 6, draw-circ+e! which consumes three arguments: a posn structure )or the center o) the circle! a number )or the radius! and a color, #ach o) the operation produces tr.e! i) it succeeds in changing the can+as as speci)ied, 1e re)er to the action to the can+as as an #FF#CT! but we will ignore stud$ing the precise nature o) e))ects until part 4II, Also! i) an$thing goes wrong with the operation! it stops the e+aluation with an error, #ach drawing operation also comes with a matching c+ear- operation: c+ear-so+id+ine! c+ear-so+id-rect! c+ear-so+id-dis-! and c+ear-circ+e, I) these )unctions are applied to the same arguments as their matching draw- )unction! the$ clear the corresponding shapes o) the can+as,(>

Drawing operations on computers interpret the screen as )ollows:

First! the origin o) the plane is in the upper2le)t corner, Second! y coordinates grow in the downwards direction, Anderstanding the di))erence between this picture and the more con+entional Cartesian plane is critical )or drawing shapes with programs, Drawing E ercise &<2<1< #+aluate the )ollowing e8pressions in order: (, !start"3%%"3%%#! which opens a can+asE &, !draw-so+id-+ine"!ma-e-posn"1%"1%#"!ma-e-posn"11%"1%#"'red#! which draws a red line close to! and parallel to! the upper end o) the can+asE 5, !draw-so+id-rect"!ma-e-posn"1%"3%#"1%%"5%"'8+.e#! which draws a blue rectangle o) width ('' and height 7' parallel to the red lineE 6, !draw-circ+e"!ma-e-posn"11%"3%#"3%"'2e++ow#! which draws a $ellow circle o) radius 5' centered at the upper right corner o) the rectangleE 7, !draw-so+id-dis-"!ma-e-posn"1%"$%#"5%"'green#! which draws a green dis. o) radius 7' centered at the lower le)t corner o) the rectangleE and 9, !stop#! which closes the can+as, Read the documentation )or draw.ss in DrSchemeCs HelpDes., The de)initions and e8pressions in )igure < draw a tra))ic light, The program )ragment illustrates the use o) global de)initions )or speci)$ing and computing constants, Here! the constants represent the dimensions o) the can+as! which is the outline o) the tra))ic light! and the positions o) three light bulbs,

66"dimensions"of"traffic"+ight"""" !define"OID;="5%# !define"=5IG=;"1 %# !define"(PL(-Q'DIPC"2%# !define"(PL(-DIC;'J75"1%# 66"the"positions"of"the"8.+8s" !define"R-(PL(C"!).otient"OID;="2## !define"I-Q5D"!+"(PL(-DIC;'J75"(PL(-Q'DIPC## !define"I-I5LLNO"!+"I-Q5D"(PL(-DIC;'J75"!*"2"(PL(-Q'DIPC### !define"I-GQ55J"!+"I-I5LLNO"(PL(-DIC;'J75"!*"2"(PL(-Q'DIPC### 66"draw"the"+ight"with"the"red"8.+8"t.rned"on !start"OID;="=5IG=;# !draw-so+id-dis-"!ma-e-posn"R-(PL(C"I-Q5D#"(PL(-Q'DIPC"'red# !draw-circ+e"!ma-e-posn"R-(PL(C"I-I5LLNO#"(PL(-Q'DIPC"'2e++ow#

/draw2circle /ma.e2posn N2BA"BS 32=R##-0 BA"B2RADIAS =green0 Figure )' Drawing a tra))ic light E ercise &<2<2< De+elop the )unction c+ear-8.+8, It consumes a s$mbol that denotes one o) the possible colors: 'green! '2e++ow! or 'red! and it produces tr.e, Its e))ect is DDto turn o))CC the matching bulb in the tra))ic light, Speci)icall$! it should clear the dis. and displa$ a circle o) the matching color instead, Choice of Design 0ecipe: See section 7 )or designing )unctions that consume one o) an enumeration o) s$mbols, Testing: 1hen testing )unctions that draw shapes into a can+as! we ignore test e8pressions, Although it is possible to implement appropriate test suites! the problem is be$ond the scope o) this boo., Combining Effects: The primiti+e operations )or drawing and clearing dis.s and circles produce tr.e i) the$ success)ull$ complete their tas., The natural wa$ to combine the +alues and the e))ects o) these )unctions is to use an and2e8pression, In particular! i) e*p1 and e*p2 produce e))ects and we wish to see the e))ects o) e*p2 a)ter those o) e*p1! we write
!and"e*p1"e*p2#

"ater we will stud$ e))ects in more detail and learn di))erent wa$s to combine e))ects, Solution E ercise &<2<!< De+elop a )unction draw-8.+8, It consumes a s$mbol that denotes one o) the possible colors: 'green! '2e++ow! or 'red! and produces tr.e, Its e))ect is DDto turn onCC the matching bulb in the tra))ic light, Solution

E ercise &<2<#< De+elop the )unction switch, It consumes two s$mbols! each o) which stands )or a tra))ic light color! and produces tr.e, Its e))ects are to clear the bulb )or the )irst color and then to draw the second bulb, Solution E ercise &<2<$< Here is the )unction ne*t:
66"ne*t":"s2m8o+""-/""s2m8o+ 66"to"switch"a"traffic"+ightKs"c.rrent"co+or"and"to"ret.rn"the ne*t"one" !define"!ne*t"c.rrent-co+or# ""!cond """"9!and"!s2m8o+&A"c.rrent-co+or"'red#"!switch"'red"'green## """""'green: """"9!and"!s2m8o+&A"c.rrent-co+or"'2e++ow#"!switch"'2e++ow"'red## """""'red: """"9!and"!s2m8o+&A"c.rrent-co+or"'green#"!switch"'green"'2e++ow## """""'2e++ow:##

It consumes the current color o) a tra))ic light /as a s$mbol0 and produces the ne8t color that the tra))ic light shows, That is! i) the input is 'green! it produces '2e++owE i) it is '2e++ow! it produces 'redE and i) it is 'red! it produces 'green, Its e))ect is to switch the tra))ic light )rom the input color to the ne8t color, Replace the last three lines o) the program )ragment in )igure < with !draw-8.+8 'red#, This creates a tra))ic light that is red, Then use ne*t to switch the tra))ic light )our times, Solution

-#( Structure Definitions


In the preceding section we e8plored one particular class o) structures: the posn structures, A posn structure combines two numbers! and it is use)ul to represent pi8els, I) we wish to represent emplo$ee records or points in three2dimensional space! howe+er! posns are useless, DrScheme there)ore permits programmers to de)ine their own structures so that the$ can represent all .inds o) obFects with a )i8ed number o) properties,

Asing and De)ining Structures A STRACTAR# D#FI-ITI@- is! as the term sa$s! a new )orm o) de)inition, Here is DrSchemeCs de)inition o) posn:
!define-struct"posn"!*"2##""

1hen DrScheme e+aluates this structure de)inition! it creates three operations )or us! which we can use to create data and to program:

(, ma-e-posn! the C@-STRACT@R! which creates posn structuresE &, posn-*! a S#"#CT@R! which e8tracts the + coordinateE 5, posn-2! also a selector! which e8tracts the y coordinate, In general! the names o) these new operations are created b$ pre)i8ing the name o) the structure with DDma.e2CC and b$ post)i8ing the name with all the )ield names, This naming con+ention appears to be complicated but! with some practice! it is eas$ to remember, -ow consider the )ollowing e8ample:
!define-struct"entr2"!name"@ip"phone##

The structure represents a simpli)ied entr$ into an address boo., #ach entr2 combines three +alues, 1e also sa$ that each entr2 structure has three )ields: name! @ip! and phone, Because there are three )ields! the constructor ma-e-entr2 consumes three +alues, For e8ample!
!ma-e-entr2"'3eterLee"1527%"' % -7771#

creates an entr2 structure with '3eterLee in the name2)ield! 1527% in the @ip2)ield! and ' % -7771 in the phone2)ield, @ne wa$ to thin. o) a structure is as a bo8 with as man$ compartments as there are )ields:
name 'ip phone K3eterLee 1527% K % -7771 '3eterLee1527%' % -7771

The italici*ed labels name the )ields, B$ putting +alues in the compartments! we illustrate speci)ic entr2 structures, The define-struct de)inition o) entr2 also introduces new selectors:
entr2-name""""entr2-@ip""""entr2-phone

Here is how we can use the )irst one:


""!entr2-name"!ma-e-entr2"'3eterLee"1527%"' % -7771## &"'3eterLee

I) we gi+e the structure a name!


!define"phone8oo-"!ma-e-entr2"'3eterLee"1527%"' % -7771##

then we can use the selectors in the Interactions window to e8tract the data )rom the three )ields:
""!entr2-name"phone8oo-# &"'3eterLee ""!entr2-@ip"phone8oo-# &"1527% ""!entr2-phone"phone8oo-# &"' % -7771

Put more graphicall$! a constructor creates a bo8 with se+eral compartments and puts +alues in it, A selector re+eals the contents o) a particular compartment! but lea+es the bo8 alone, Here is one )inal e8ample! a structure )or representing roc. stars:
!define-struct"star"!+ast"first"instr.ment"sa+es##

It de)ines the class o) star structures! each o) which has )our )ields, Accordingl$! we get )i+e new primiti+e operations:
ma-e-star"""star-+ast"""star-first""""star-instr.ment""""starsa+es

The )irst is )or constructing star structuresE the others are selector operations )or e8tracting +alues )rom a star structure, To create a star structure! we appl$ ma-e-star to three s$mbols and a positi+e integer:
!ma-e-star"'>riedman"'Dan"'.-e+e+e"1,%%4# !ma-e-star"';a+cott"'7aro+2n"'8anSo"$%%%%# !ma-e-star"'=arper"'Qo8ert"'8agpipe"27$ %#

To select the )irst name o) a star structure called 5! we use


!star-first"5#

@ther )ields are e8tracted with other selectors, E ercise &<!<1< Consider the )ollowing structure de)initions: (, !define-struct"mo0ie"!tit+e"prod.cer## &, !define-struct"8o2friend"!name"hair"e2es"phone##

5, !define-struct"cheer+eader"!name"n.m8er## 6, !define-struct"7D"!artist"tit+e"price## 7, !define-struct"sweater"!materia+"si@e"prod.cer## 1hat are the names o) the constructors and the selectors that each o) them adds to SchemeH Draw bo8 representations )or each o) these structures, Solution E ercise &<!<2< Consider the )ollowing structure de)inition
!define-struct"mo0ie"!tit+e"prod.cer##

and e+aluate the )ollowing e8pressions: (, !mo0ie-tit+e"!ma-e-mo0ie"';he3hantomHenace"'L.cas## &, !mo0ie-prod.cer"!ma-e-mo0ie"';he5mpireCtri-es(ac-"'L.cas## -ow e+aluate the )ollowing e8pressions! assuming * and 2 stand )or arbitrar$ s$mbols: (, !mo0ie-tit+e"!ma-e-mo0ie"*"2## &, !mo0ie-prod.cer"!ma-e-mo0ie"*"2## Formulate e?uations that state general laws concerning the relationships o) mo0ietit+e and mo0ie-prod.cer and ma-e-mo0ie, Solution Functions both consume and produce structures, Suppose we need to record an increase o) sales )or one o) our stars, This act should be recorded in the starCs record, To do so! we should ha+e a )unction that consumes a star structure and produces a star structure with the same in)ormation e8cept )or the sales component, "etCs assume )or now that the )unction adds &'''' to the starCs sales, First! we write down a basic description o) the )unction! using our contract! header! and purpose )ormat:
66"increment-sa+es":"star""-/""star

66"to"prod.ce"a"star"record"+i-e"a-star"with"2%%%%"more"sa+es" !define"!increment-sa+es"a-star#"...#

Here is an e8ample o) how the )unction should process star structures:


""!increment-sa+es"!ma-e-star"''88a"'Tohn"'0oca+s"122%%## sho.+d"prod.ce ""!ma-e-star"''88a"'Tohn"'0oca+s"322%%##

The three sample star structures )rom abo+e are also good e8amples o) potential inputs,
66"increment-sa+es":"star""-/""star 66"to"prod.ce"a"star"record"+i-e"a-star"with"2%%%%"more"sa+es !define"!increment-sa+es"a-star# ""!ma-e-star"!star-+ast"a-star# """""""""""""!star-first"a-star# """""!star-instr.ment"a-star#

/I /star2sales a2star0 &''''000 Figure -' The complete de)inition o) increment-sa!es

The increment-sa+es )unction must construct a new star structure with ma-e-star! but to do so! it must also e8tract the data in a-star, A)ter all! almost all o) the data in a-star is a part o) the star structure produced b$ increment-sa+es, This suggests that the de)inition o) increment-sa+es contains e8pressions that e8tract the )our )ields o) a-star:
!define"!increment-sa+es"a-star#" ""..."!star-+ast"a-star#"... ""..."!star-first"a-star#"... ""..."!star-instr.ment"a-star#"... ""..."!star-sa+es"a-star#"..."#

As we ha+e seen with the e8amples! the )unction adds 2%%%% to !star-sa+es"a-star# and assembles the )our pieces o) data into a star structure with ma-e-star, Figure > contains the complete de)inition, E ercise &<!<!< Pro+ide a structure de)inition that represents an air)orceCs Fet )ighters, Assume that a )ighter has )our essential properties: designation /'f22! 'tornado! or 'mig220! acceleration! top2speed! and range, Then de+elop the )unction within-range, The )unction consumes a )ighter record and the distance o) a target )rom the /)ighterCs0 base, It determines whether the )ighter can reach the intended target, Also de+elop the )unction red.ce-range, The )unction consumes a )ighter record and produces one in which the range )ield is reduced to <'R o) the original +alue, Solution

-#) Data Definitions


Consider the )ollowing e8pression:
!ma-e-posn"''+8ert"'He2er#

It constructs a posn structure )rom two s$mbols, I) we now appl$ distance-to-% to this structure! the computation )ails miserabl$:
""!distance-to-%"!ma-e-posn"''+8ert"'He2er## &"!s)rt """"!+"!s)r"!posn-*"!ma-e-posn"''+8ert"'He2er### """""""!s)r"!posn-2"!ma-e-posn"''+8ert"'He2er##### &"!s)rt """"!+"!s)r"''+8ert# """""""!s)r"!posn-2"!ma-e-posn"''+8ert"'He2er##### &"!s)rt """"!+"!*"''+8ert"''+8ert# """""""!s)r"!posn-2"!ma-e-posn"''+8ert"'He2er#####

That is! it re?uires us to multipl$ ''+8ert with itsel), Similarl$!


!ma-e-star"''+8ert"'He2er"1%%%%"'e+ectric-organ#

does not produce a star structure according to our intentions, In particular! the structure is not suitable )or processing b$ increment-sa+es, To a+oid such problems and to assist with the de+elopment o) )unctions! we must add a data de)inition to each structure de)inition,

Data De)initions A DATA D#FI-ITI@- states! in a mi8ture o) #nglish and Scheme! how we intend to use a class o) structures and how we construct elements o) this class o) data, For e8ample! here is a data de)inition )or posn structures: A posn is a structure:
!ma-e-posn"*"2#

where * and 2 are numbers, It sa$s that a +alid posn structure alwa$s contains two numbers! and nothing else, Hence! when we use ma-e-posn to create a posn structure! we must appl$ it to two numbersE when a )unction contains selector e8pressions )or posn structures! we ma$ now assume that their result is a number, The data de)inition )or star structures is onl$ slightl$ more complicated: A star is a structure:

!ma-e-star"+ast"first"instr.ment"sa+es#

where +ast! first! and instr.ment are s$mbols and sa+es is a number, This data de)inition sa$s that +alid star structures contain s$mbols in the )ields )or +ast name! first name! and instr.ment! and a number in the sa+es )ield,

Figure 1.' The meaning o) data de)initions In general! a data de)inition identi)ies a subclass o) SchemeCs uni+erse o) +alues: see )igure (', As we ha+e seen so )ar! SchemeCs uni+erse contains numbers! s$mbols! images! strings! chars! booleans! and man$ di))erent classes o) structures, @ur )unctions! howe+er! are intended to wor. onl$ )or a subclass o) +alues, For e8ample! area-ofdis- consumes onl$ numbersE rep+2 )rom section 7 consumes onl$ s$mbols, A )ew subclasses! such as n.m8er! alread$ ha+e names! because the$ are use)ul )or all .inds o) programming tas.s, @thers are onl$ interesting in the conte8t o) a speci)ic problem, For those cases! a programmer should introduce a data de)inition, The most important role o) a data de)inition is that o) a co+enant between programmers and users, 1e e8pect both groups to respect such data de)initions! and we e8pect the programmer to e8ploit it )or the )unction construction, For e8ample! when the programmer o) distance-to-% speci)ies that all posns contain two numbers! a user must alwa$s appl$ distance-to-% to a posn structure with two numbers, Furthermore! as we will discuss o+er the ne8t )ew sections! we e8pect a programmer to e8ploit data de)initions )or )unction de+elopments, -aturall$! a data de)inition in #nglish and Scheme does not pre+ent us )rom abusing ma-e-posn, It is! howe+er! a written statement o) intent! and a person who willingl$ +iolates or ignores this co+enant must )ace the conse?uences o) ill2beha+ing computations,&' E ercise &<#<1< Pro+ide data de)initions )or the )ollowing structure de)initions: (, !define-struct"mo0ie"!tit+e"prod.cer## &, !define-struct"8o2friend"!name"hair"e2es"phone## 5, !define-struct"cheer+eader"!name"n.m8er## 6, !define-struct"7D"!artist"tit+e"price##

7, !define-struct"sweater"!materia+"si@e"prod.cer##

Ma.e appropriate assumptions about what data goes with which )ield,

Solution

E ercise &<#<2< Pro+ide a structure de)inition and a data de)inition )or representing points in time since midnight, A point in time consists o) three numbers: hours! minutes! and seconds, Solution E ercise &<#<!< Pro+ide a structure de)inition and a data de)inition )or representing three2letter words, A word consists o) letters! which we represent with the s$mbols 'a through '@, Solution

-#* Designing +unctions for Compound Data


Sections 9,( through 9,6 suggest that the design o) )unctions )or compound data proceeds in a regular manner, First! a programmer must recogni*e that structures are needed, 1e )ollow the simple rule o) using structures whene+er the description o) some obFect speci)ies se+eral pieces o) in)ormation, I) we donCt use structures in these cases! we ?uic.l$ lose trac. o) which data belongs to which obFect! especiall$ when we write large )unctions that process massi+e amounts o) data, Second! a programmer can use the structure and data de)initions )or the organi*ation o) a )unction, 1e use the term template when we design )unctions, As we will see in this and man$ )uture sections! the template matches the data de)inition! and the template is the essential step in the care)ul design o) )unctions, To emphasi*e this point! we modi)$ our )unction design recipe )rom section &,7 to accommodate compound data, Most importantl$! wor.ing with compound data re?uires adFustments in a )ew o) the basic design steps and two new steps: data anal$sis and template design:

66"Data"'na+2sis"U"Definitions: !define-struct"st.dent"!+ast"first"teacher## 66"'"st.dent"is"a"str.ct.re:"!ma-e-st.dent"+"f"t#"where"f<"+<"and t"are"s2m8o+s. 66"7ontract:"s.8st-teacher":"st.dent"s2m8o+""-/""st.dent 66"3.rpose:"to"create"a"st.dent"str.ct.re"with"a"new" 66"teacher"name"if"the"teacherKs"name"matches"'>rit@ 66"5*amp+es: 66"!s.8st-teacher"!ma-e-st.dent"'>ind"'Hatthew"'>rit@#"'5+ise# 66"&" 66"!ma-e-st.dent"'>ind"'Hatthew"'5+ise# 66"!s.8st-teacher"!ma-e-st.dent"'>ind"'Hatthew"''manda#"'5+ise# 66"&" 66"!ma-e-st.dent"'>ind"'Hatthew"''manda# 66";emp+ate: 66"!define"!process-st.dent"a-st.dent"a-teacher#" 66"..."!st.dent-+ast"a-st.dent#"... 66"..."!st.dent-first"a-st.dent#"... 66"..."!st.dent-teacher"a-st.dent#"...# 66"Definition:" !define"!s.8st-teacher"a-st.dent"a-teacher#" ""!cond """"9!s2m8o+&A"!st.dent-teacher"a-st.dent#"'>rit@#" """""!ma-e-st.dent"!st.dent-+ast"a-st.dent# """""""""""""""""""!st.dent-first"a-st.dent# """a-teacher#: """"9else"a-st.dent:## "" 66";ests: !s.8st-teacher"!ma-e-st.dent"'>ind"'Hatthew"'>rit@#"'5+ise# 66"e*pected"0a+.e: !ma-e-st.dent"'>ind"'Hatthew"'5+ise# !s.8st-teacher"!ma-e-st.dent"'>ind"'Hatthew"''manda#"'5+ise# 66"e*pected"0a+.e:"

/ma.e2student =Find =Matthew =Amanda0 Figure 11' The design recipe )or compound data: A complete e8ample Data +nal%sis and Design' Be)ore we can de+elop a )unction! we must understand how to represent the in)ormation in our problem statement within our chosen programming language, To do so! we search the problem statement )or descriptions o) /rele+ant0 obFects and then design a data representation based on the results o) our anal$sis, Antil now we could use SchemeCs classes o) atomic data /numbers! s$mbols! images! etc,0 to represent in)ormation, But the$ are not enough, I) we disco+er that an obFect has / properties! we introduce a structure de)inition with / )ields and suppl$ a data de)inition that speci)ies what .ind o) data the )ields ma$ contain, "et us consider )unctions that process student records at a school, I) a studentCs interesting properties )or a school are

(, the )irst name! &, the last name! and 5, the name o) the home2room teacher! then we should represent in)ormation about a student as a structure:
!define-struct"st.dent"!+ast"first"teacher##

Here is the data de)inition that speci)ies the class o) student structures as precisel$ as possible: A st dent is a structure:
!ma-e-st.dent"+"f"t#

where +! f! and t are s$mbols, The corresponding data class contains structures li.e these:
!ma-e-st.dent"'find+er"'-athi"'matthias# !ma-e-st.dent"'fis+er"'sean"'matthias# !ma-e-st.dent"'f+att"'shriram"'matthias#

Contract' For the )ormulation o) contracts! we can use the names o) the atomic classes o) data! such as n.m8er and s2m8o+! and those names that we introduced in data de)initions! such as st.dent, Template' A )unction that consumes compound data is li.el$ to compute its result )rom the components o) its input, To remind oursel+es o) the components! we )irst design a template, For compound data! a T#MP"AT# consists o) a header and a bod$ that lists all possible selector e8pressions, #ach selector e8pression is the application o) an appropriate selector primiti+e to a parameter that stands )or a structure, In other words! a template e8presses what we .now about the inputs! and nothing about the outputs, 1e can there)ore use the same template )or all )unctions that consume the same .ind o) structure, Also! because a template does not e8press an$thing about the purpose o) the )unction! 3e can formulate it before or after 3e ha1e de1eloped e amples< Consider a )unction that consumes a st.dent structure and a teacher name:
66"process-st.dent":""st.dent"s2m8o+""-/""AAA !define"!process-st.dent"a-st.dent"a-teacher#"...#

Then a-st.dent is a parameter that stands )or a structure and a-teacher stands )or Fust a s$mbol, The template there)ore has the )ollowing shape:
66"process-st.dent":""st.dent"s2m8o+""-/""AAA !define"!process-st.dent"a-st.dent"a-teacher#" ""..."!st.dent-+ast"a-st.dent#"... ""..."!st.dent-first"a-st.dent#"... ""..."!st.dent-teacher"a-st.dent#"...#

The AAA output reminds us that we donCt assume an$thing about the output o) the )unction, 1e design e+er$ )unction that consumes a st.dent structure using this template, E amples' "et us stud$ two e8amples o) )unctions that consume st.dent structures, The )irst )unction! chec-! is supposed to return the last name o) the student i) the teacherCs name is e?ual to a-teacher and 'none otherwise:
!chec-"!ma-e-st.dent"'Oi+son"'>rit@"'=arper#"'=arper# 66"e*pected"0a+.e: 'Oi+son !chec-"!ma-e-st.dent"'Oi+son"'>rit@"'Lee#"'=arper# 66"e*pected"0a+.e 'none

The second )unction! transfer! is supposed to produce a student structure that contains the same in)ormation as a-st.dent e8cept )or the teacher )ield! which should be a-teacher:
!transfer"!ma-e-st.dent"'Oi+son"'>rit@"'=arper#"'Lee# 66"e*pected"0a+.e:" !ma-e-st.dent"'Oi+son"'>rit@"'Lee# !transfer"!ma-e-st.dent"'Ooops"'=e+en"'>+att#"'>is+er# 66"e*pected"0a+.e:" !ma-e-st.dent"'Ooops"'=e+en"'>is+er#

5od%' The template pro+ides as man$ clues )or the de)inition o) the )unction as the e8amples, As be)ore! the goal o) this step is to )ormulate an e8pression that computes the answer )rom the a+ailable data using other )unctions or SchemeCs primiti+e, The template reminds us that the a+ailable data are the parameters and the data computed b$ the selector e8pressions, To determine what the selectors produce! we read the data de)inition )or the structure, "et us return to our )irst e8ample! chec-:
!define"!chec-"a-st.dent"a-teacher#" ""!cond """"9!s2m8o+&A"!st.dent-teacher"a-st.dent#"a-teacher#" """""!st.dent-+ast"a-st.dent#: """"9else"'none:##

This particular )unction uses two o) the three selector e8pressions )rom the template, Speci)icall$! it compares the result o) the selector e8pression !st.dent-teacher"a-st.dent# with a-teacher and! i) the$ are e?ual!

produces the result o) !st.dent-+ast"a-st.dent#, Just naming the results o) the selector e8pressions and reading the problem statement ma.es the de)inition ob+ious, Similarl$! the transfer )unction is eas$ to de)ine using the template and the e8amples:
!define"!transfer"a-st.dent"a-teacher#" ""!ma-e-st.dent"!st.dent-+ast"a-st.dent#" """"""""""""""""!st.dent-first"a-st.dent# a-teacher##

This second )unction uses the same two selector e8pressions as the )irst e8ample! but in a di))erent wa$, The .e$ obser+ation! howe+er! is that the template reminds us o) all the in)ormation that we ha+e a+ailable, @hen 3e define the function, 3e must use and combine the a1ailable information< Figure (& presents the recipe )or compound data in tabular )orm, In practice! though! a )unction contains man$ )unctions that all wor. on the same class o) input data, It is there)ore normal to reuse the template man$ times! which means that e8amples are o)ten constructed a)ter the template is set up, Compare it with the design recipes in )igures 6 and 9,

Phase Data Anal$sis and Design Contract Purpose and Header

=oal to )ormulate a data de)inition

#8amples

Template

Bod$

Test

Acti+it$ determine how man$ pieces o) data describe the DDinterestingCC aspects o) the obFects mentioned in the problem statement add a structure de)inition and a data de)inition /)or each class o) problem obFect0 to name the name the )unction! the classes o) input data! the )unctionE class o) output data! and speci)$ its purpose: to speci)$ its EE name : in1 in2 ...22S o t classes o) EE to compute ... )rom +1 ... input data and /define /name +1 +2 ...0 ...0 its class o) output dataE to describe its purposeE to )ormulate a header to characteri*e search the problem statement )or e8amples wor. the input2 through the e8amples +alidate the results! i) output possible ma.e up e8amples relationship +ia e8amples to )ormulate an )or those parameters that stand )or compound outline +alues! annotate the bod$ with selector e8pressions i) the )unction is conditional! annotate all appropriate branches to de)ine the de+elop a Scheme e8pression that uses SchemeCs )unction primiti+e operations! other )unctions! selector e8pressions! and the +ariables to disco+er appl$ the )unction to the inputs o) the e8amples mista.es chec. that the outputs are as predicted /DDt$posCC and logic0

Figure 12' Designing a )unction )or compound data /Re)ines the recipe in )igure 6 /pg, 700 E ercise &<$<1< De+elop templates )or )unctions that consume the )ollowing structures: (, !define-struct"mo0ie"!tit+e"prod.cer## &, !define-struct"8o2friend"!name"hair"e2es"phone##

5, !define-struct"cheer+eader"!name"n.m8er## 6, !define-struct"7D"!artist"tit+e"price##

7, !define-struct"sweater"!materia+"si@e"prod.cer## ,

Solution

E ercise &<$<2< De+elop the )unction time-/seconds! which consumes a time structure /see e8ercise 9,6,&0 and produces the number o) seconds since midnight that the time structure represents, #8ample:
!time-/seconds"!ma-e-time"12"3%"2##"" 66"e*pected"0a+.e:" 45%%2"

#8plain the e8ample,

Solution

-#- E,tended E,ercise. /oving Circles and Rectangles


Ase draw.ss Implementing a computer game o)ten re?uires mo+ing a picture across a computer monitor, In )igure (5! )or e8ample! a simplistic )ace is mo+ed )rom the le)t part o) the can+as toward the right border, For simplicit$! our pictures consist o) man$ colored circles and rectangles, From section 9,&! we alread$ .now! )or e8ample! how to draw and erase a circle, Here we learn to translate a circle! that is! to mo+e its representation along some line, In sections ;,6! (',5! and &(,6 we learn to mo+e entire pictures with compact programs,&(

Figure 1!' A mo+ing )ace Following the design recipe! we start with structure and data de)initions! then mo+e on to templates! and )inall$ write the necessar$ )unctions, The )irst se?uence o) e8ercises co+ers circlesE the second one is about rectangles, + First Note on Iterati1e 0efinement: This method o) de+eloping large programs is our )irst taste o) IT#RATI4# R#FI-#M#-T, The basic idea behind iterati+e re)inement is to start with a simple +ersion o) the program! that is! a +ersion that deals with the most important part o) the problem, In this section! we start with )unctions that mo+e the most basic shapes: circles and rectangles, Then we re)ine the program to deal with more and more comple8 situations, For e8ample! in section (',5 we learn to deal with pictures that consist o) an arbitrar$ number o) circles and rectangles, @nce we ha+e a complete program! we edit it so that others can easil$ read and modi)$ it! too, Section &(,6 co+ers this aspect o) the e8ample, Re)ining a program in this manner is the most pre+alent method o) designing comple8 programs, @) course! we must .now the e+entual goal )or this method to succeed! and we must alwa$s .eep it in mind, It is there)ore a good idea to write down an action plan! and to reconsider the plan a)ter each re)inement step, 1e will discuss this process again in section (9, E ercise &<&<1< Pro+ide a structure de)inition and a data de)inition )or representing colored circles, A circ!e is characteri*ed b$ three pieces o) in)ormation: its center! its radius! and the color o) its perimeter, The )irst is a posn structure! the second a number! and the third a /color0 s$mbol, De+elop the template f.n-for-circ+e! which outlines a )unction that consumes circ+es, Its result is undetermined, Solution

E ercise &<&<2< Ase f.n-for-circ+e to de+elop draw-a-circ+e, The )unction consumes a circ+e structure and draws the corresponding circle on the screen, Ase !start"3%%"3%%# to create the can+as be)ore testing the )unction, Solution E ercise &<&<!< Ase the template f.n-for-circ+e to de+elop in-circ+eA, The )unction consumes a circ+e structure and a posn and determines whether or not the pi8el is inside the circle, All pi8els whose distance to the center is less or e?ual to the radius are inside the circleE the others are outside, Consider the circle in )igure (6, The circleCs center is !ma-e-posn" "2#! its radius is 1, The pi8el labeled '! located at !ma-e-posn" "1.5#! is inside the circle, The pi8el labeled (! located at !ma-e-posn"$" #! is outside, Solution E ercise &<&<#< Ase the template f.n-for-circ+e to de+elop trans+ate-circ+e, The )unction consumes a circ+e structure and a number de+ta, The result is a circ+e whose center is de+ta pi8els to the right o) the input, The function has no effect on the can1as< 4eometric Translation: Mo+ing a geometric shape along a straight line is re)erred to as a trans!ation, Solution E ercise &<&<$< Ase the template f.n-for-circ+e to de+elop c+ear-a-circ+e, The )unction consumes a circ+e structure and clears the corresponding circle on the can+as, Solution E ercise &<&<&< De)ine the )unction draw-and-c+ear-circ+e! which draws a circ+e structure! waits )or a short time! and clears it, To implement a waiting period! the teachpac. draw.ss pro+ides the )unction s+eep-for-a-whi+e, It consumes a number and puts the program to sleep )or that man$ secondsE its result is tr.e, For e8ample! !s+eep-for-a-whi+e"1# waits )or one second, Solution The )ollowing )unction is the .e$ ingredient )or mo+ing a circle across a can+as! one step at a time:
66"mo0e-circ+e":"n.m8er"circ+e""-/""circ+e 66"to"draw"and"c+ear"a"circ+e<"trans+ate"it"82"de+ta"pi*e+s !define"!mo0e-circ+e"de+ta"a-circ+e# ""!cond """"9!draw-and-c+ear-circ+e"a-circ+e#"!trans+ate-circ+e"a-circ+e de+ta#: """"9else"a-circ+e:##

It draws and clears the circle on the can+as and then produces the new circ+e structure so that another draw2and2clear e))ect displa$s the circle at a new position:

!start"2%%"1%%# !draw-a-circ+e" ""!mo0e-circ+e"1% """"!mo0e-circ+e"1% """"""!mo0e-circ+e"1% !mo0e-circ+e"1%"..."a"circ+e"...#####

This e8pression mo+es the circle )our times! b$ (' pi8els each! and also shows this mo+ement on the can+as, The last draw-a-circ+e is necessar$ because we wouldnCt otherwise see the last mo+e on the screen,

Figure 1#' Circles! rectangles! and pi8els E ercise &<&<(< Pro+ide a structure de)inition and a data de)inition )or representing colored rectangles, A rectang!e is characteri*ed b$ )our pieces o) in)ormation: its upper2 le)t corner! its width! its height! and its )ill color, The )irst is a posn structure! the second and third ?uantities are plain numbers! and the last one is a color, De+elop the template f.n-for-rect! which outlines a )unction that consumes rectang+es, Its result is undetermined, Solution E ercise &<&<)< Ase the template f.n-for-rect to de+elop draw-a-rectang+e, The )unction consumes a rectang+e structure and draws the corresponding rectangle on the screen, In contrast to circles! the entire rectangle is painted in the matching color, Remember to use !start"3%%"3%%# to create the can+as be)ore testing the )unction, Solution E ercise &<&<-< Ase the template f.n-for-rect to de+elop in-rectang+eA, The )unction consumes a rectang+e structure and a posn and determines whether or not the pi8el is inside the rectangle, A pi8el is within a rectangle i) its hori*ontal and +ertical distances to the upper2le)t corner are positi+e and smaller than the width and height o) the rectangle! respecti+el$,

Consider the rectangle in )igure (6, This rectangleCs .e$ parameters are !ma-e-posn"2 3#! 3! and 2, The pi8el labeled 7 is inside o) the rectangle! ( is outside, Solution E ercise &<&<1.< Ase the template f.n-for-rect to de+elop trans+ate-rectang+e, The )unction consumes a rectang+e structure and a number de+ta, The result is a rectang+e whose upper2le)t corner is de+ta pi8els to the right o) the input, The function has no effect on the can1as< Solution E ercise &<&<11< Ase the template f.n-for-rect to de+elop c+ear-a-rectang+e, It consumes a rectang+e structure and clears the corresponding rectangle on the can+as, Solution E ercise &<&<12< Here is the mo0e-rectang+e )unction:
66"mo0e-rectang+e":"n.m8er"rectang+e""-/""rectang+e 66"to"draw"and"c+ear"a"rectang+e<"trans+ate"it"82"de+ta"pi*e+s !define"!mo0e-rectang+e"de+ta"a-rectang+e# ""!cond """"9!draw-and-c+ear-rectang+e"a-rectang+e#" """""!trans+ate-rectang+e"a-rectang+e"de+ta#: """"9else"a-rectang+e:##

It draws and clears a rectangle circle on the can+as and then produces a translated +ersion, De+elop draw-and-c+ear-rectang+e! which draws a rectangle! sleeps )or a while! and then clears the rectangle, Finall$! create a rectangle and use the )unctions o) this e8ercise set to mo+e it )our times, Solution

-#0 E,tended E,ercise. 1angman


Ase draw.ss!
hangman.ss

Figure 1$' Three stages o) the hangman picture Hangman is a two2pla$er! word2guessing game, @ne pla$er thin.s o) a three2letter&& word and draws the noose o) a gallows /see )igure (70E the other pla$er tries to guess the word! one letter at a time, For e+er$ wrong guess! the )irst pla$er adds another part to the drawing /see )igure (70: )irst the head! then the bod$! the arms! and the legs, I)! howe+er! a guess agrees with one or two letters in the chosen word! the )irst pla$er re+eals the position/s0 where this letter occurs, The game is o+er when the second pla$er guesses the complete word or when the )irst pla$er has completed the stic. )igure, "etCs design a program that pla$s the role o) the )irst pla$er, The program consists o) two parts: one )or drawing the )igure! and another )or determining whether a guess occurs in the chosen word and where, E ercise &<(<1< De+elop the )unction draw-ne*t-part! which draws the pieces o) a hangman )igure, The )unction consumes one o) the se+en s$mbols:
'right-+eg 'noose '+eft-+eg '+eft-arm 'right-arm '8od2 'head

It alwa$s returns tr.e and draws the matching part o) the )igure, See )igure (7 )or three snapshots o) intermediate stages,&5 >ints' Add !start"2%%"2%%# to the top o) the de)inition window, Start with the noose and de+elop one component at a time, I) a component o) the stic. )igure re?uires more than one drawing operation! combine the operations using an and2e8pression! which e+aluates the two e8pressions and ensure that both results are tr.e, Solution

The second tas. o) the )irst pla$er is to determine whether a guess is among the letters o) the chosen word and! i) so! where it occurs, @ur recipe re?uires that! be)ore we design a )unction )or this tas.! we need to anal$*e our data and pro+ide data de)initions, The .e$ obFects o) the game are words and letters, A -ord consists o) three letters, A !etter is represented with the s$mbols 'a through '@, Asing Fust those letters! howe+er! is not enough because the program also needs to maintain a word that records how much the second pla$er has guessed, The solution is to add one e8tra DDletterCC to our alphabet that is distinct )rom the othersE the hangman teachpac. uses 'V )or this purpose, E ercise &<(<2< Pro+ide a structure de)inition and a data de)inition )or representing three2letter words, Solution E ercise &<(<!< De+elop the )unction re0ea+, It consumes three arguments: (, the chosen word! which is the word that we ha+e to guessE &, the stat s word! which shows which portion o) the word has been re+ealed so )arE and 5, a letter! which is our current g ess, The )unction produces a new status word! that is! a word that contains ordinar$ letters and 'V, The )ields in the new status word are determined b$ comparing the guess with each pair o) letters )rom the status word and the chosen word: (, I) the guess is e?ual to the letter in the chosen word! the guess is the corresponding letter in the new status word, &, @therwise! the new letter is the corresponding letter )rom the status word, Test the )unction with the )ollowing e8amples:
!re0ea+"!ma-e-word"'t"'e"'a#"!ma-e-word"'V"'e"'V#"'.# 66"e*pected"0a+.e !ma-e-word"'V"'e"'V# !re0ea+"!ma-e-word"'a"'+"'e#"!ma-e-word"'a"'V""'V#"'e# 66"e*pected"0a+.e:" !ma-e-word"'a"'V"'e# !re0ea+"!ma-e-word"'a"'+"'+#"!ma-e-word"'V"'V"'V#"'+# 66"e*pected"0a+.e !ma-e-word"'V"'+"'+#

The )irst one shows what happens when the g.ess does not occur in the wordE the second one shows what happens when it does occurE and the last one shows what happens when it occurs twice, >ints' /(0 Remember to de+elop au8iliar$ )unctions when a de)inition becomes too large or too comple8 to manage, /&0 The )unction re0ea+ consumes two structures and one atomic +alue /a letter0, This suggests that we use the design recipe )or compound data /)igure (&0, For the template! it is best to write down the selector e8pressions in a two2column )ormat! one column per word, Solution 1hen the )unctions draw-ne*t-part and re0ea+ are properl$ tested! set teachpac. to hangman.ss and pla$ the game b$ e+aluating
!hangman"ma-e-word"re0ea+"draw-ne*t-part#

The hangman )unction chooses a three2letter word randoml$ and displa$s a window with a pop2up menu )or letters, Choose letters and! when read$! clic. the 7hec- button to see whether the guess is correct, Comment out the test cases )or e8ercise 9,;,( so that their drawing e))ects donCt inter)ere with those o) hangman, An alternati+e terminolog$ is DDto access the )ields o) a record,CC 1e pre)er to thin. o) structure +alues as containers )rom which we can e8tract other +alues,
(<

(>

For more documentation! see DrSchemeCs Help Des.,

DrScheme pro+ides an optional tool that permits programmers to chec. whether users and programmers respect the data de)inition )or a particular structure, To do so! a programmer must state data de)initions in a special language, Although chec.ing the adherence to data de)initions is important )or large programs! an introductor$ course can a+oid this topic,
&'

&(

This series o) sections was inspired b$ Ms, aren Buras and her son,

In realit$! we would want to pla$ the game with words o) arbitrar$ length! but a game based on three2letter words is easier to implement )or now, 1e return to the problem in e8ercise (;,9,&,
&&

&5

Than.s to Mr, John Clements )or the artistic +ersion o) dra--ne+t-part,

Section ( The "arieties of Data


The pre+ious section signi)icantl$ e8pands our world o) data, 1e must now deal with a uni+erse that contains booleans! s$mbols! and structures o) man$ .inds, "etCs bring some order to this world, Ap to this point! our )unctions ha+e alwa$s processed subclasses o) )our di))erent .inds o) data:&6 numbers' representations o) numeric in)ormationE booleans' truth and )alsit$E s%mbols' representations o) s$mbolic in)ormationE and structures' representations o) compounds o) in)ormation, @n occasion! howe+er! a )unction must process a class o) data that includes both numbers and structures or structures o) se+eral di))erent .inds, 1e learn to design such )unctions in this section, In addition! we learn how to protect )unctions )rom bad uses, Here a bad use means that some user can accidentall$ appl$ a )unction )or drawing circles to a rectangle, Although we ha+e agreed that such users +iolate our data de)initions! we should ne+ertheless .now how to protect our )unctions against such uses! when necessar$,

0#$ /i,ing and Distinguishing Data


In the preceding section! we used posn structures with e8actl$ two components to represent pi8els, I) man$ o) the pi8els are on the + a8is! we can simpli)$ the representation b$ using plain numbers )or those pi8els and posn structures )or the remaining ones, Figure (9 contains a sample collection o) such points, Three o) the )i+e points! namel$! 2! 0! and )! are on the + a8is, @nl$ two points re?uire two coordinates )or an accurate description: , and 1, @ur new idea )or representing points permits us to describe this class o) points succinctl$: !ma-e-posn" " # )or 'E !ma-e-posn"1"2# )or (E and (! &! and 5 )or 7! D! and 5! respecti+el$,

I) we now wish to de)ine the )unction distance-to-%! which consumes such point representations and produces their distance to the origin! we are con)ronted with a problem, The )unction ma$ be applied to a number or a posn, Depending on the class to which the input belongs! distance-to-% must emplo$ a di))erent method to calculate the distance to the origin, Thus we need to use a cond2e8pression to distinguish the two cases, An)ortunatel$! we donCt ha+e an$ operations to )ormulate the appropriate conditions,

Figure 1&' A small collection o) points To accommodate this .ind o) )unction! Scheme pro+ides PR#DICAT#S! which are operations that recogni*e a particular )orm o) data, The predicates )or the classes o) data we .now are:
n.m8erA!

which consumes an arbitrar$ +alue and produces tr.e i) the +alue is a number and fa+se otherwiseE 8oo+eanA! which consumes an arbitrar$ +alue and produces tr.e i) the +alue is a boolean +alue and fa+se otherwiseE s2m8o+A! which consumes an arbitrar$ +alue and produces tr.e i) the +alue is a s$mbol and fa+se otherwiseE str.ctA! which consumes an arbitrar$ +alue and produces tr.e i) the +alue is a structure and fa+se otherwise, For each structure de)inition! Scheme also introduces a separate predicate so that we can distinguish between distinct classes o) structures, Suppose the Definitions window contains the )ollowing structure de)initions:&7
!define-struct"posn"!*"2## !define-struct"star"!+ast"first"do8"ssn## !define-struct"airp+ane"!-ind"ma*-speed"ma*-+oad"price##

Then! Scheme also .nows the )ollowing three predicates:

posnA! which consumes an arbitrar$ +alue and produces tr.e i) the +alue is a posn structure and fa+se otherwiseE starA! which consumes an arbitrar$ +alue and produces tr.e i) the +alue is a star structure and fa+se otherwiseE airp+aneA! which consumes an arbitrar$ +alue and produces tr.e i) the +alue a airp+ane structure and fa+se otherwise,

is

Hence a )unction can distinguish a structure )rom a number as well as a posn structure )rom an airp+ane structure, E ercise (<1<1< #+aluate the )ollowing e8pressions b$ hand: (, !n.m8erA"!ma-e-posn"2"3## &, !n.m8erA"!+"12"1%## 5, !posnA"23# 6, !posnA"!ma-e-posn"23"3## 7, !starA"!ma-e-posn"23"3## Chec. the answers in DrScheme, Solution

-ow we can de+elop distance-to-%, "etCs start with a data de)inition: A pi+e!-2 is either (, a n.m8er! or &, a posn structure, Stating the contract! purpose! and header is straight)orward:
66"distance-to-%":"pi*e+-2""-/""n.m8er 66"to"comp.te"the"distance"of"a-pi*e+"to"the"origin !define"!distance-to-%"a-pi*e+#"...#

As mentioned be)ore! the )unction must distinguish between its two .inds o) inputs! which can be accomplished with a cond2e8pression:
!define"!distance-to-%"a-pi*e+# ""!cond """"9!n.m8erA"a-pi*e+#"...: """"9!posnA"a-pi*e+#"...:##

The two conditions match the two possible inputs o) the new distance-to-% )unction, I) the )irst one holds! the input is a pi8el on the + a8is, @therwise the pi8el is a posn structure, For the second cond2line! we also .now that the input contains two items: the + and y coordinates, To remind oursel+es! we annotate the template with two selector e8pressions:
!define"!distance-to-%"a-pi*e+# ""!cond """"9!n.m8erA"a-pi*e+#"...: """"9!posnA"a-pi*e+#"..."!posn-*"a-pi*e+#"..."!posn-2"a-pi*e+#"... :##

Completing the )unction is eas$, I) the input is a number! it is the distance to the origin, I) it is a structure! we use the old )ormula )or determining the distance to the origin:
!define"!distance-to-%"a-pi*e+# ""!cond """"9!n.m8erA"a-pi*e+#"a-pi*e+: """"9!posnA"a-pi*e+#"!s)rt """""""!+"!s)r"!posn-*"a-pi*e+## ""!s)r"!posn-2"a-pi*e+####:##

"et us consider a second e8ample, Suppose we are to write )unctions that deal with geometric shapes, @ne )unction might ha+e to compute the area co+ered b$ a shape! another one the perimeter! and a third could draw the shape, For the sa.e o) simplicit$! letCs assume that the class o) shapes includes onl$ s?uares and circles and that their description includes their location /a posn0 and their si*e /a n.m8er0, In)ormation about both shapes must be represented with structures! because both ha+e se+eral attributes, Here are the structure de)initions:
!define-struct"square"!nw"length## !define-struct"circ+e"!center"radi.s##

and the matching data de)inition: A shape is either (, a circle structure:


2. " """!ma-e-circ+e"p"s# ""

where p is a posn and s is a numberE or 5, a s?uare structure:


4. " """!ma-e-s).are"p"s# ""

where p is a posn and s is a number, Together! the two classes ma.e up the class o) shapes: The ne8t step o) our design recipe re?uires that we ma.e up e8amples, "etCs start with input e8amples: (, !ma-e-s).are"!ma-e-posn"2%"2%#"3#! &, !ma-e-s).are"!ma-e-posn"2"2%#"3#! and 5, !ma-e-circ+e"!ma-e-posn"1%",,#"1#, To ma.e up e8amples o) input2output relationships! we need to .now the purpose o) the )unction, So suppose we need the )unction perimeter! which computes the perimeter o) a shape, From geometr$! we .now that the perimeter o) a s?uare is )our times its side! and the perimeter o) a circle is times the diameter! which is twice the radius,&9 Thus! the perimeter o) the abo+e three e8amples are: 12! 12! and /roughl$0 .2$! respecti+el$, Following the design recipe and the precedent o) distance-to-%! we start with the )ollowing s.eleton o) the )unction:
66"perimeter":"shape""-/""n.m8er 66"to"comp.te"the"perimeter"of"a-shape !define"!perimeter"a-shape# ""!cond """"9!s).areA"a-shape#"...": """"9!circ+eA"a-shape#"...":##

because the )unction must )irst determine to which class a-shape belongs, Furthermore! each possible input is a structure! so we can also add two selector e8pressions to each cond2clause:
66"perimeter":"shape""-/""n.m8er 66"to"comp.te"the"perimeter"of"a-shape !define"!perimeter"a-shape# ""!cond

""""9!s).areA"a-shape#" """""..."!s).are-nw"a-shape#"..."!s).are-+ength"a-shape#"...: """"9!circ+eA"a-shape# """""..."!circ+e-center"a-shape#"..."!circ+e-radi.s"ashape#"...:##

The selector e8pressions remind us o) the a+ailable data, -ow we are read$ to )inish the de)inition, 1e )ill the gaps in the two answers b$ translating the mathematical )ormulae into Scheme notation:
!define"!perimeter"a-shape# ""!cond """"9!s).areA"a-shape#"!*"!s).are-+ength"a-shape#"4#: """"9!circ+eA"a-shape#"!*"!*"2"!circ+e-radi.s"a-shape##"pi#:##

Since the position o) a shape does not a))ect its perimeter! the templateCs selector e8pressions )or nw and center disappear, E ercise (<1<2< Test perimeter with the e8amples, Solution

E ercise (<1<!< De+elop the )unction area! which consumes either a circle or a s?uare and computes the area, Is it possible to reuse the template )or perimeter b$ changing the name to areaH Solution

0#" Designing +unctions for /i,ed Data


The )unction de+elopment in the preceding section suggests some amendments to our design recipe, Speci)icall$! the data anal$sis step! the template construction step! and the de)inition o) the )unctionCs bod$ re?uire adFustments, Data +nal%sis and Design' 1hen we anal$*e a problem statement! our )irst tas. is to determine whether it mentions distinct classes o) data 22 which we call MIN#D DATA and which is also .nown as the A-I@- o) data classes, In other words! the data anal$sis must ta.e into account se+eral aspects now, First! we must determine how man$ distinct classes o) obFects are mentioned in the problem and what their important attributes are, I) there are se+eral di))erent classes o) obFects! we are mi8ing data, Second! we must understand whether the +arious obFects ha+e se+eral properties, I) an obFect has se+eral attributes! we use compound data )or its representation, As a result! the resulting data de)inition ma$ ha+e se+eral clauses that enumerate se+eral possibilities, Indeed! we will see that the data anal$sis ma$ $ield a hierarch$ o) data de)initions, The e8ample o) the preceding section deals with two distinct .inds o) shapes! each o) which has se+eral properties, 1e captured this idea with the )ollowing data de)inition:

A shape is either (, a circle structure:


2. " """!ma-e-circ+e"p"s# ""

where p is a posn and s is a numberE or 5, a s?uare structure:


4. " """!ma-e-s).are"p"s# ""

where p is a posn and s is a number, It speci)ies that e+er$ shape belongs to one o) two subclasses o) data, For a data de)inition to ma.e sense! it must be possible to )ormulate conditions that distinguish the +arious subclasses in a de)inition, That is! i) * stands )or a piece o) data in the de)ined class! we must be able to use built2in and user2 de)ined predicates to distinguish the enumerated subclasses )rom each other, In our running e8ample! the two conditions would be !s).areA"*# and !circ+eA *#, Template' Recall that the template is a translation o) the input data de)inition into Scheme, Thus! imagine that we ha+e a data de)inition that enumerates se+eral distinct possibilities, The )irst step is to write down a cond2e8pression with as man$ clauses as there are enumerated possibilities in the data de)inition, The second step is to add a condition to each line, #ach condition should hold i) the input belongs to the corresponding subclass o) data mentioned in the data de)inition, Here is the template )or our running e8ample:
66"f":"shape""-/""AAA !define"!f"a-shape# ""!cond """"9!s).areA"a-shape#"...: """"9!circ+eA"a-shape#"...:##

The output speci)ication and the purpose statement are missing to emphasi*e that a template has no connection to the output or the purpose o) a )unction, @nce we ha+e )ormulated the template )or the conditional! we re)ine the template )urther! cond2line b$ cond2line, I) the purpose o) a line is to process atomic in)ormation! we are done, I) a line processes compound data! we enrich the template with appropriate selector e8pressions,

"etCs illustrate the idea with our running e8ample again:


!define"!f"a-shape# ""!cond """"9!s).areA"a-shape#" """""..."!s).are-nw"a-shape#"..."!s).are-+ength"ashape#"...: """"9!circ+eA"a-shape# """""..."!circ+e-center"a-shape#"..."!circ+e-radi.s"a-shape# ...:##

5od%' Asing the conditional template! we split the tas. into simpler tas.s, Speci)icall$! we can )ocus on each cond2line separatel$! simpl$ considering the ?uestion what is the output i) we are gi+en this .ind o) input, All other cases are ignored as we wor. out one particular clause, Suppose we want to de)ine a )unction that computes the perimeter o) a shape, Then we start )rom the template and )ill in the gaps:
66"perimeter":"shape""-/""n.m8er 66"to"comp.te"the"perimeter"of"a-shape !define"!perimeter"a-shape# ""!cond """"9!s).areA"a-shape#"!*"!s).are-+ength"a-shape#"4#: """"9!circ+eA"a-shape#"!*"!*"2"!circ+e-radi.s"a-shape## pi#:##

Figure (; summari*es the de+elopment o) our running e8ample, The remaining steps o) the recipes in )igures 6! 9! and (& should be )ollowed on an as2is basis, Figure (< summari*es the design recipe! with all steps included,

66"Data"Definition: !define-struct"circ+e"!center"radi.s## !define-struct"square"!nw"length## 66"'"shape"is"either 66"1."a"str.ct.re:"!ma-e-circ+e"p"s# 66""""where"p"is"a"posn<"s"a"n.m8er6 66"2."a"str.ct.re:"!ma-e-s).are"p"s# 66""""where"p"is"a"posn<"s"a"n.m8er. 66"7ontract<"3.rpose<"=eader:" 66"perimeter":"shape""-/""n.m8er 66"to"comp.te"the"perimeter"of"a-shape 66"5*amp+es:"see"tests 66";emp+ate: 66"!define"!f"a-shape# 66"""!cond 66"""""9!s).areA"a-shape# 66"""""..."!s).are-nw"a-shape#"..."!s).are-+ength"a-shape#"...: 66"""""9!circ+eA"a-shape# 66"""""..."!circ+e-center"a-shape#"..."!circ+e-radi.s"ashape#"...:## 66"Definition:" !define"!perimeter"a-shape# ""!cond """"9!circ+eA"a-shape# """""!*"!*"2"!circ+e-radi.s"a-shape##"pi#: """"9!s).areA"a-shape# """""!*"!s).are-+ength"a-shape#"4#:## 66";ests:"!same"as"e*amp+es# !&"!perimeter"!ma-e-s).are"..."3##"12#

/O /perimeter /ma.e2circle ,,, (00 /T & pi00 Figure 1(' The design recipe )or mi8ed data: A complete e8ample

Phase Data Anal$sis and Design

=oal to )ormulate a data de)inition

Contract Purpose and Header

#8amples

Template

Bod$ Test

Acti+it$ determine how man$ distinct classes o) DDobFectsCC ma.e up the classes o) problem data enumerate the alternati+es in a data de)inition )ormulate a data de)inition )or each alternati+e! i) it is a )orm o) compound data to name the name the )unction! the classes o) input data! the )unctionE class o) output data! and speci)$ its purpose: to speci)$ its EE name : in1 in2 ...22S o t classes o) EE to compute ... )rom +1 ... input data and /define /name +1 +2 ...0 ...0 its class o) output dataE to describe its purposeE to )ormulate a header to characteri*e create e8amples o) the input2output relationship the input2 ma.e sure there is at least one e8ample per subclass output relationship +ia e8amples to )ormulate an introduce a cond2e8pression with one clause per outline subclass )ormulate a condition )or each case! using built2in and prede)ined predicates to de)ine the de+elop a Scheme e8pression )or each cond2line /an )unction answer0! assuming that the condition holds to disco+er appl$ the )unction to the inputs o) the e8amples mista.es chec. that the outputs are as predicted /DDt$posCC and logic0

Figure 1)' Designing a )unction )or mi8ed data /Re)ines the recipes in )igures 6 /pg, 70 and (& /pg, >00 #+en a cursor$ comparati+e reading o) the design recipes in sections &,7! 6,6! 9,7! and the current one suggests that the data anal$sis and the template design steps are becoming more and more important, I) we do not understand what .ind o) data a )unction consumes! we cannot design it and organi*e it properl$, I)! howe+er! we do understand the structure o) the data de)inition and organi*e our template properl$! it is eas$ to modi)$ or to e8tend a )unction, For e8ample! i) we add new in)ormation to the representation o) a circ+e! then onl$ those cond2clauses related to circles ma$ re?uire changes, Similarl$! i) we add a new .ind o) shape to our data de)inition! sa$! rectangles! we must add new cond2clauses to our )unctions,

E ercise (<2<1< De+elop structure and data de)initions )or a collection o) *oo animals, The collection includes spiders, whose rele+ant attributes are the number o) remaining legs /we assume that spiders can lose legs in accidents0 and the space the$ need in case o) transportE elephants, whose onl$ attributes are the space the$ need in case o) transportE mon6e%s, whose attributes are intelligence and space needed )or transportation, Then de+elop a template )or )unctions that consume *oo animals, De+elop the )unction fitsA, The )unction consumes a *oo animal and the +olume o) a cage, It determines whether the cage is large enough )or the animal, Solution E ercise (<2<2< The administrators o) metropolitan transportation agencies manage )leets o) +ehicles, De+elop structure and data de)initions )or a collection o) such +ehicles, The collection should include at least buses! limos! cars! and subwa$s, Add at least two attributes per class o) +ehicle,

Then de+elop a template )or )unctions that consume +ehicles,

Solution

0#( Composing +unctions2 Revisited


As we anal$*e a problem statement! we might wish to de+elop the data representation in stages, This is especiall$ true when the problem statement mentions se+eral di))erent .inds o) obFects, It is easier to understand se+eral smaller data de)initions than one larger one, "etCs return to our shape problem again, Instead o) the class o) shapes in a single data de)inition! we could start with two data de)initions! one )or each basic shape: A circ!e is a structure:
!ma-e-circ+e"p"s#

where p is a posn and s is a number, A s& are is a structure:


!ma-e-s).are"p"s#

where p is a posn and s is a number,

@nce we ha+e de+eloped and understood the basic data de)initions! possibl$ b$ pla$ing with e8amples and b$ writing simple )unctions! we can introduce data de)initions that combine them, For e8ample! we can introduce a data de)inition )or a class o) shapes that re)ers to the two abo+e: A shape is either (, a circ+e! or &, a square, -ow suppose we need a )unction that consumes shapes, First! we )orm a cond2 e8pression with conditions )or each part o) the data de)inition:
66"f":"shape""-/""AAA !define"!f"a-shape# ""!cond """"9!circ+eA"a-shape#"...: """"9!s).areA"a-shape#"...:##

=i+en our guideline concerning the composition o) )unctions )rom section 5,( and gi+en that the data de)inition re)ers to two other data de)initions! the natural second step is to pass the argument to au8iliar$ )unctions:
!define"!f"a-shape# ""!cond """"9!circ+eA"a-shape#"!f-for-circ+e"a-shape#: """"9!s).areA"a-shape#"!f-for-s).are"a-shape#:##

This! in turn! re?uires that we de+elop the two au8iliar$ )unctions! f-for-circ+e and f-for-s).are! including their templates,

66"Data"Definition: !define-struct"circ+e !center"radi.s## !define-struct"square !nw"length## 66"'"shape"is"either 66"1."a"str.ct.re: !ma-e-circ+e"p"s# 66""""where"p"is"a posn<"s"a"n.m8er6 66"2."a"str.ct.re: !ma-e-s).are"p"s# 66""""where"p"is"a posn<"s"a"n.m8er.

66"Data"Definitions: !define-struct circ+e"!center radi.s## 66"'"circle"is"a str.ct.re: 66""""""""""!ma-ecirc+e"p"s# 66""""where"p"is"a posn<"s"a"n.m8er6 !define-struct square"!nw"length## 66"'"square"is"a str.ct.re: 66""""""""""!ma-es).are"p"s# 66""""where"p"is"a posn<"s"a"n.m8er. 66"'"shape"is"either 66"1."a"circ+e<"or 66"2."a"s).are."

66">ina+"Definition:" 66"perimeter":"shape "-/""n.m8er 66"to"comp.te"the perimeter"of"a-shape !define"!perimeter"ashape# ""!cond """"9!circ+eA"ashape# """""!*"!*"2"!circ+eradi.s"a-shape##"pi#: """"9!s).areA"ashape# """""!*"!s).are+ength"a-shape#"4#:##

66">ina+ Definitions:" 66"perimeter":"shape "-/""n.m8er 66"to"comp.te"the perimeter"of"a-shape !define"!perimeter a-shape# ""!cond """"9!circ+eA"ashape# """""!perimetercirc+e"a-shape#: """"9!s).areA"ashape# """""!perimeters).are"a-shape#:## 66"perimeter-circ+e :"circ+e""-/""n.m8er 66"to"comp.te"the perimeter"of"acirc+e !define"!perimetercirc+e"a-circ+e# ""!*"!*"2"!circ+eradi.s"a-circ+e## pi## 66"perimeter-s).are :"s).are""-/""n.m8er

I) we )ollow this suggestion! we arri+e at a collection o) three )unctions! one per data de)inition, The essential points o) the program de+elopment are summari*ed in the right column o) )igure (>, For a comparison! the le)t column contains the corresponding pieces o) the original program de+elopment, In each case! we ha+e as man$ )unctions as there are data de)initions, Furthermore! the re)erences between the )unctions in the right column directl$ match the re)erences among the corresponding data de)initions, 1hile this s$mmetr$ between data de)initions and )unctions ma$ seem tri+ial now! it becomes more and more important as we stud$ more comple8 wa$s o) de)ining data, E ercise (<!<1< Modi)$ the two +ersions o) perimeter so that the$ also process rectangles, For our purposes! the description o) a rectangle includes its upper2le)t corner! its width! and its height, Solution

0#) E,tended E,ercise. /oving Shapes


In section 9,9! we de+eloped )unctions )or drawing! translating! and clearing circles and rectangles, As we ha+e Fust seen! we should thin. o) the two classes o) data as subclasses o) a class o) shapes so that we can Fust draw! translate! and clear shapes, E ercise (<#<1< Pro+ide a data de)inition )or a general class o) shapes, The class should at least subsume the classes o) colored circles and rectangles )rom section 9,9, De+elop the template f.n-for-shape! which outlines )unctions that consume shapes, Solution E ercise (<#<2< Ase the template f.n-for-shape to de+elop draw-shape, The )unction consumes a shape and draws it on the can+as, Solution E ercise (<#<!< Ase the template f.n-for-shape to de+elop trans+ate-shape, The )unction consumes a shape and a number de+ta! and produces a shape whose .e$ position is mo+ed b$ de+ta pi8els in the + direction, Solution E ercise (<#<#< Ase the template f.n-for-shape to de+elop c+ear-shape, The )unction consumes a shape! erases it )rom the can+as! and returns tr.e, Solution E ercise (<#<$< De+elop the )unction draw-and-c+ear-shape, The )unction consumes a shape! draws it! sleeps )or a while! and clears it, I) all the e))ects wor. out! it produces tr.e, Solution

E ercise (<#<&< De+elop mo0e-shape! which mo+es a shape across the can+as, The )unction consumes a number /delta0 and a shape, The )unction should draw2and2clear the shape and return a new shape that has been translated b$ delta pi8els, Ase this )unction se+eral times to mo+e a shape across the can+as, Solution

0#* 3nput Errors


Recall our )irst )unction:
66"area-of-dis-":"n.m8er""-/""n.m8er 66"to"comp.te"the"area"of"a"dis-"with"radi.s"r !define"!area-of-dis-"r#" ""!*"3.14"!*"r"r###

Clearl$! our )riends ma$ wish to use this )unction! especiall$ )or some o) their geometr$ homewor., An)ortunatel$! when our )riends use this )unction! the$ ma$ accidentall$ appl$ it to a s$mbol rather than a number, 1hen that happens! the )unction stops with a whimsical and unin)ormati+e error message:
/"!area-of-dis-"'m2-dis-# *:"e*pects"t2pe"?n.m8er/"as"1st"arg.ment,"gi0en:"'m2-dis-6"..."

Asing predicates! we can do better, To pre+ent this .ind o) accident! we should de)ine chec.ed +ersions o) our )unctions! when we wish to hand them to our )riends, In general! a CH#C #D FA-CTI@- inputs an arbitrar$ Scheme +alue: a number! a boolean! a s$mbol! or a structure, For all those +alues that are in the class o) +alues )or which the original )unction is de)ined! the chec.ed +ersion applies the latterE )or all others! it signals an error, Concretel$! chec-ed-area-of-dis- consumes an arbitrar$ Scheme +alue! uses area-of-dis- to compute the area o) the a dis. i) the input is a number! and stops with an error message otherwise, Based on the enumeration o) SchemeCs classes o) +alues! the template )or a chec.ed )unction is as )ollows:
66"f":"Ccheme-0a+.e""-/""AAA !define"!f"0# ""!cond """"9!n.m8erA"0#"...: """"9!8oo+eanA"0#"...: """"9!s2m8o+A"0#"...: """"9!str.ctA"0#"...:##

#ach line corresponds to one possible class o) input, I) we need to distinguish between the structures! we e8pand the last line appropriatel$,

The )irst clause is the onl$ one where we can use area-of-dis-, For the others! howe+er! we must signal an error, In Scheme we use the operation error to do so, It consumes a s$mbol and a string, Here is an e8ample:
!error"'chec-ed-area-of-dis-"1n.m8er"e*pected1#

Hence the )ull de)inition o) chec-ed-area-of-dis- is:


!define"!chec-ed-area-of-dis-"0# ""!cond """"9!n.m8erA"0#"!area-of-dis-"0#: """"9!8oo+eanA"0#"!error"'chec-ed-area-of-dis-"1n.m8er"e*pected1#: """"9!s2m8o+A"0#"!error"'chec-ed-area-of-dis-"1n.m8er"e*pected1#: """"9!str.ctA"0#"!error"'chec-ed-area-of-dis-"1n.m8er e*pected1#:##

Asing else we can greatl$ simpli)$ the )unction:


66"chec-ed-area-of-dis-":"Ccheme-0a+.e""-/""n.m8er 66"to"comp.te"the"area"of"a"dis-"with"radi.s"0<" 66"if"0"is"a"n.m8er !define"!chec-ed-area-of-dis-"0# ""!cond """"9!n.m8erA"0#"!area-of-dis-"0#: """"9else"!error"'chec-ed-area-of-dis-"1n.m8er"e*pected1#:##

@) course! such a simpli)ication ma$ not alwa$s be possible and ma$ re?uire a reordering o) the cond2clauses )irst, 1riting chec.ed )unctions and simpli)$ing them is important i) we distribute the programs to others, Designing programs that wor. properl$! howe+er! is )ar more important, The boo. there)ore )ocuses on the design process )or the program proper and deemphasi*es writing chec.ed +ersions, E ercise (<$<1< A chec.ed +ersion o) area-of-dis- can also en)orce that the arguments to the )unction are positi+e numbers! not Fust arbitrar$ numbers, Modi)$ chec-ed-area-of-dis- in this wa$, Solution E ercise (<$<2< De+elop chec.ed +ersions o) the )unctions profit /)igure 70! is8etween-5- A /section 6,&0! rep+2 /section 70! distance-to-% /section 9,(0! and perimeter /in the le)t column o) )igure (>0, Solution E ercise (<$<!< Ta.e a loo. at these structure and data de)initions:
!define-struct"0ec"!*"2##

A speed-vector /vec0 is a structure:


!ma-e-0ec"*"2#

where both * and 2 are positi+e numbers, De+elop the )unction chec-ed-ma-e-0ec! which should be understood as a chec.ed +ersion o) the primiti+e operation ma-e-0ec, It ensures that the arguments to ma-e-0ec are positi+e numbers! and not Fust arbitrar$ numbers, In other words! chec-ed-ma-e0ec en)orces our in)ormal data de)inition, Solution 1e ha+e also discussed images and strings! but we ignore these )or now,

&6

The posn structure is automaticall$ pro+ided in DrSchemeCs teaching languages and should ne+er be de)ined,
&7

&9

The perimeter o) a circle is also .nown as circ mference,

Section ) Interme**o 1' S%nta and Semantics


Thus )ar we ha+e approached Scheme as i) it were a spo.en language, "i.e toddlers! we learned the +ocabular$ o) the language! we ac?uired an intuiti+e understanding o) its meaning! and we )igured out some basic rules o) how to compose and not to compose sentences, Trul$ e))ecti+e communication! howe+er! in an$ language 22 be it natural li.e #nglish or arti)icial li.e Scheme 22 e+entuall$ re?uires a )ormal stud$ o) its +ocabular$! its grammar! and the meaning o) sentences, A programming language is in man$ wa$s li.e a spo.en language, It has a +ocabular$ and a grammar, The +ocabular$ is the collection o) those DDbasic wordsCC )rom which we can compose DDsentencesCC in our language, A sentence in a programming language is an e8pression or a )unctionE the languageCs grammar dictates how to )orm complete sentences )rom words, Programmers use the terminolog$ S3-TAN to re)er to the +ocabularies and grammars o) programming languages, -ot all grammatical sentences are meaning)ul 22 neither in #nglish nor in a programming language, For e8ample! the #nglish sentence DDthe cat is roundCC is a meaning)ul sentence! but DDthe bric. is a carCC ma.es no sense! e+en though it is completel$ grammatical, To determine whether or not a sentence is meaning)ul! we must stud$ the M#A-I-=! or S#MA-TICS! o) words and sentences, For spo.en languages! we t$picall$ e8plain the meaning o) words with sentences that use simpler

wordsE in the case o) a )oreign language! we sometimes e8plain a word with simple sentences in the )oreign language or we translate words to a .nown language, For programming languages! there are also se+eral wa$s to e8plain the meaning o) indi+idual sentences, In this boo.! we discuss the meaning o) Scheme programs through an e8tension o) the )amiliar laws o) arithmetic and algebra, A)ter all! computation starts with this )orm o) simple mathematics! and we should understand the connection between this mathematics and computing, The )irst three sections present the +ocabular$! grammar! and meaning o) a small! but power)ul subset o) Scheme, The )ourth one resumes our discussion o) run2time errors in Scheme! based on our new understanding o) its meaning, The remaining three sections re+isit and and or e8pressions! +ariable de)initions! and structures,

4#$ The Scheme 'oca&ulary


SchemeCs basic +ocabular$ consists o) )i+e categories o) words, The )i+e lines in )igure &' show how computer scientists discuss the +ocabular$ o) a language,&; All lines emplo$ the same notation, The$ enumerate some simple e8amples separated b$ a bar /DD X CC0, Dots indicate that there are more things o) the same .ind in some categor$, O * X area-of-dis- X perimeter X ... ?con/ O tr.e X fa+se 'a X 'do++ X 's.m X ... 1 X -1 X 3/5 X 1.22 X ... ?prm/ O + X - X ... Figure 2.' (eginning"Ct.dent Scheme: The core +ocabular$
?0ar/

The )irst categor$ is that o) +ariables! which are the names o) )unctions and +alues, The second introduces constants: boolean! s$mbolic! and numeric constants, As indicated be)ore! Scheme has a power)ul number s$stem! which is best introduced graduall$ b$ e8amples, The )inal categor$ is that o) primiti+e operations! which are those basic )unctions that Scheme pro+ides )rom the +er$ beginning, 1hile it is possible to speci)$ this collection in its entiret$! it is best introduced in pieces! as the need arises, For the classi)ication o) Scheme sentences! we also need three -e2words: define! cond! and else, These .e$words ha+e no meaning, Their role resembles that o) punctuation mar.s! especiall$ that o) commas and semicolons! in #nglish writingE the$ help programmers distinguish one sentence )rom another, -o .e$word ma$ be used as a +ariable,

4#" The Scheme 5rammar


=rammar! "a$out! and #diting In contrast to man$ other programming languages! Scheme has a simple grammar, It is shown in its entiret$ in )igure &(,&< The grammar de)ines two categories o) sentences: Scheme de)initions! ?def/! and e8pressions! ?e*p/, 1hile the grammar does not dictate the use o) white space between the items o) sentences! we )ollow the con+ention to put at least one blan. space behind each item unless an item is )ollowed b$ a right parenthesis DD0CC, Scheme is )le8ible concerning blan. space! and we can replace a single blan. space b$ man$ spaces! line brea.s! and page brea.s, O /define /?0ar/ ?0ar/ ...?0ar/0 ?e*p/0 ?e*p/ O ?0ar/ X ?con/ X /?prm/ ?e*p/ ...?e*p/0 X /?0ar/ ?e*p/ ...?e*p/0 X /cond /?e*p/ ?e*p/0 .../?e*p/ ?e*p/00 X /cond /?e*p/ ?e*p/0 .../else ?e*p/00 Figure 21' (eginning"Ct.dent Scheme: The core grammar
?def/

The two grammar de)initions describe how to )orm atomic sentences and compound sentences! which are sentences built )rom other sentences, For e8ample! a )unction de)inition is )ormed b$ using DD/CC! )ollowed b$ the .e$word define! )ollowed b$ another DD/CC! )ollowed b$ a non2empt$ se?uence o) +ariables! )ollowed b$ DD0CC! )ollowed b$ an e8pression! and closed b$ a right parenthesis DD0CC that matches the +er$ )irst one, The .e$word define distinguishes de)initions )rom e8pressions, The categor$ o) e8pressions consists o) si8 alternati+es: +ariables! constants! primiti+e applications! /)unction0 applications! and two +arieties o) conditionals, The last )our are again composed o) other e8pressions, The .e$word cond distinguishes conditional e8pressions )rom primiti+e and )unction applications, Here are three e8amples o) e8pressions: 'a++! *! and !*"*#, The )irst one belongs to the class o) s$mbols and is there)ore an e8pression, The second is a +ariable! and e+er$ +ariable is an e8pression, Finall$! the third is a )unction application! because * is a +ariable, In contrast! the )ollowing parenthesi*ed sentences are not e8pressions: !f"define#! !cond"*#! and !#, The )irst one partiall$ matches the shape o) a )unction application but it uses define as i) it were a +ariable, The second one )ails to be a correct cond2 e8pression because it contains a +ariable as the second item and not a pair o) e8pressions surrounded b$ parentheses, The last one is Fust a pair o) parentheses! but the

grammar re?uires that e+er$ le)t parenthesis is )ollowed b$ something other than a right parenthesis, E ercise )<2<1< 1h$ are the sentences (, * &, !&"2"@# 5, !&"!&"2"@#"%# s$ntacticall$ legal e8pressionsH #8plain wh$ the )ollowing sentences are illegal e8pressions: (, !3"+"4# &, empt2A!+# 5, !*# Solution

E ercise )<2<2< 1h$ are the sentences (, !define"!f"*#"*# &, !define"!f"*#"2# 5, !define"!f"*"2#"3# s$ntacticall$ legal de)initionsH #8plain wh$ the )ollowing sentences are illegal de)initions: (, !define"!f"'*#
*#

&, !define"!f"*"2"@#
!*##

5, !define"!f#"1%# Solution

E ercise )<2<!< Distinguish s$ntacticall$ legal )rom illegal sentences: (, !*# &, !+"1"!not"*## 5, !+"1"2"3# #8plain wh$ the sentences are legal or illegal, Solution

E ercise )<2<#< Distinguish s$ntacticall$ legal )rom illegal sentences: (, !define"!f"*#"'*# &, !define"!f"'*#
*#

5, !define"!f"*"2#"!+"'2"!not
*###

#8plain wh$ the sentences are legal de)initions or wh$ the$ )ail to be legal de)initions, Solution 4rammatical Terminolog%: The components o) compound sentences ha+e names, 1e ha+e introduced some o) these names on an in)ormal basisE )or better communication! we introduce all use)ul ones here, The second component o) a de)inition! that is! the non2empt$ se?uence o) +ariables! is a H#AD#R, Accordingl$! the e8pression component o) a de)inition is called B@D3, The +ariables that )ollow the )irst +ariable in a header are the PARAM#T#RS o) a )unction,

/define /?f.nction-name/ ?parameter/ ...?parameter/0 ?8od2/0 /?f.nction/ ?arg.ment/ ...?arg.ment/0 /cond /?).estion/ ?answer/0 ?cond-c+a.se/ ...0 Figure 22' S$ntactic naming con+entions People who thin. o) de)inition as the de)inition o) a mathematical )unction also use the terminolog$ "#FT2HA-D SID# )or a de)initionCs header and RI=HT2HA-D SID# )or the bod$, For the same reason! the )irst component in an application is called FA-CTI@- and the remaining components are re)erred to as AR=AM#-TS, @ccasionall$! we also use ACTAA" AR=AM#-TS, Finall$! a cond2e8pression consists o) cond2lines or cond2clauses, #ach line consists o) two e8pressions: the BA#STI@- and the A-S1#R, A ?uestion is also called a C@-DITI@-, Figure && pro+ides a summar$ o) the con+entions,

4#( The /eaning of Scheme


Stepper A legal DrScheme program consists o) two items: a se?uence o) )unction de)initions /in the Definitions window0 and a se?uence o) interactions /in the Interactions window0, #ach interaction is a demand )or the e+aluation o) one Scheme e8pression! which t$picall$ re)ers to the )unctions de)ined in the upper part o) DrScheme, 1hen DrScheme e+aluates an e8pression! it uses nothing but the laws o) arithmetic and algebra to con+ert an e8pression into a +alue, In ordinar$ mathematics courses! +alues are Fust numbers, 1e also include s$mbols! booleans! and indeed all constants: O ?con/ The collection o) +alues is thus Fust a subset o) the collection o) e8pressions,
?0a+/

-ow that we ha+e de)ined the set o) +alues! it is eas$ to introduce and to e8plain the e+aluation rules, The rules come in two categories: those that appeal to arithmetic .nowledge and those that rel$ on a small amount o) algebra, First! we need an in)inite number o) rules li.e those o) arithmetic to e+aluate applications o) primiti+es:
!+"1"1#"&"2 !-"2"1#"&"1"

But Scheme DDarithmeticCC is more general than Fust number crunching, It also includes rules )or dealing with boolean +alues! s$mbols! and lists li.e these:

!not"tr.e#"&"fa+se !s2m8o+&A"'a"'8#"&"fa+se !s2m8o+&A"'a"'a#"&"tr.e

Second! we need one rule )rom algebra to understand how the application o) a user2 de)ined )unction ad+ances computation, Suppose the Definitions window contains the de)inition
!define"!f"*-1"..."*-n#" ""e*p#

and f,"*-1,"...,"*-n are +ariables and e*p is some /legal0 e8pression, Then an application o) a )unction is go+erned b$ the law: O e*p with all *-1"..."*-n replaced b$ 0-1"..."0-n where 0-1"..."0-n is a se?uence o) +alues that is as long as *-1"..."*-n,
!f"0-1"..."0-n#

This rule is as general as possible! so it is best to loo. at a concrete e8ample, Sa$ the de)inition is
!define"!po+2"*"2#" ""!+"!e*pt"2"*#"2##

Then the application !po+2"3"5# can be e+aluated as )ollows:


""!po+2"3"5# &"!+"!e*pt"2"3#"5## ""66";his"+ine"is"!+"!e*pt"2"*#"2#"where"*"was"rep+aced"82"3"and"2 82"5". &"!+"$"5# &"13

These last two steps )ollow )rom plain arithmetic, Third and )inall$! we need some rules that help us determine the +alue o) cond2 e8pressions, These rules are algebraic rules but are not a part o) the standard algebra curriculum: condAfalse' when the )irst condition is fa+se:

""!cond" """"9fa+se"...: """"9e*p1"e*p2: """"...# ""&"!cond """"""6";he"first"+ine"disappeared. """"""9e*p1"e*p2: """"""...#

then the )irst cond2line disappearsE condAtrue' when the )irst condition is tr.e:
""!cond"

""""9tr.e"e*p:" """"...#" ""&"e*p

the entire cond2e8pressions is replaced b$ the )irst answerE condAelse' when the onl$ line le)t is the else2line:
""!cond" """"9else"e*p:# ""&"e*p

the cond2e8pressions is replaced b$ the answer in the else2clause, -o other rules are needed to understand cond, Consider the )ollowing e+aluation:
!cond ""9fa+se"1: ""9tr.e"!+"1"1#: ""9else"3:# &"!cond """"9tr.e"!+"1"1#: """"9else"3:# &"!+"1"1# &"2

It )irst eliminates a cond2line and then e?uates the cond2e8pression with !+"1"1#, The rest is plain arithmetic again, The rules are e?uations o) the )orm that we use in arithmetic and algebra on a dail$ basis, Indeed! the same laws appl$ to this s$stem o) e?uations as to those in mathematics, For e8ample! i) a"&"8 and 8"&"c! then we also .now that a"&"c, A conse?uence is that as we get better at hand2e+aluations! we can s.ip ob+ious steps and combine se+eral e?uational in)erences into one, Here is one shorter +ersion o) the pre+ious e+aluation:
""!cond """"9fa+se"1: """"9tr.e"!+"1"1#: """"9else"3:# &"!+"1"1# &"2

#+en more importantl$! we can replace an$ e8pression b$ its e?ual in e+er$ conte8t 22 Fust as in algebra, Here is a another cond2e8pression and its e+aluation:
""!cond """"9! "" &"" 1"" %" #"%: """"9else"!+"1"1#:# ""66";he".nder+ined"e*pression"is"e0a+.ated"first." &"!cond """"9fa+se"%: """"9else"!+"1"1#:# ""66"=ere"condVfa+se"app+ies." &"!cond """"9else"!+"1"1#:# ""66"Psing"condVelse<"we"now"get"an"arithmetic"e*pression." &"!+"1"1# &"2

For the )irst step! we e+aluated the nested! underlined e8pression! which is clearl$ essential here! because no cond rule would appl$ otherwise, @) course! there is nothing unusual about this .ind o) computing, 1e ha+e done this man$ times in algebra and in the )irst )ew sections o) this boo., E ercise )<!<1< #+aluate the )ollowing e8pressions step b$ step:
1."!+"!*"!/"12"$#"2/3#" !-"2%"!s)rt"4### 2."!cond """""""9!&"%"%#"fa+se: """""""9!/"%"1#"!s2m8o+&A"'a"'a#: """""""9else"!&"!/""1"%#",#:# 3."!cond """""""9!&"2"%#"fa+se: """""""9!/"2"1#"!s2m8o+&A"'a"'a#:

Velse /O /K ( &0 >0W0 E


"Co+.tion

E ercise )<!<2< Suppose the Definitions window contains


66"f":"n.m8er"n.m8er""-/""n.m8er !define"!f"*"2# ""!+"!*"3"*#"!*"2"2###

Show how DrScheme e+aluates the )ollowing e8pressions! step b$ step:


1."!+"!f"1"2#"!f"2"1## 2."!f"1"!*"2"3##

5, /) /) ( /T & 500 (>0 E


"Co+.tion

4#) Errors
Parenthesi*ed sentences ma$ or ma$ not belong to Scheme! depending on whether or not the$ are legal according to the grammar in )igure &(, I) DrScheme +eri)ies that a sentence does not belong to the language dubbed (eginning"Ct.dent! it signals a S3-TAN #RR@R, The remaining e8pressions are s$ntacticall$ legal! but some o) those ma$ still pose problems )or our e+aluation rules, 1e sa$ that such legal e8pressions contain "@=ICA" #RR@RS or RA-2TIM# #RR@RS, Consider the simplest e8ample: !/"1"%#, 1e alread$ .now )rom mathematics that

does not ha+e a +alue, Clearl$! since SchemeCs calculations must be consistent with mathematics! it too must not e?uate !/"1"%# with a +alue, In general! i) an e8pression is not a +alue and i) the e+aluation rules allow no )urther simpli)ication! we sa$ that an error occurred or that the )unction raises an error signal, Pragmaticall$ this means that the e+aluation stops immediatel$ with an appropriate error message! such as 1/:"di0ide"82"@ero1 )or di+ision b$ *ero, For an e8ample! consider the )ollowing e+aluation:
""!+"!*"2%"2#"!/"1"!-"1%"1%### &"!+"4%"!/"1"%## &"/:"di0ide"82"@ero

The error eliminates the conte8t !+"4%"...# around !/"1"%#! which represents the remainder o) the computation with respect to the di+ision, To understand how run2time errors are signaled! we must inspect the e+aluation rules again, Consider the )unction
66"m2-di0ide":"n.m8er""-/""n.m8er !define"!m2-di0ide"n# ""!cond """"9!&"n"%#"'inf: """"9else"!/"1"n#:##

-ow suppose we appl$ m2-di0ide to %, Then the )irst step is:


""!m2-di0ide"%# &"!cond """"9!&"%"%#"'inf: """"9else"! "" /"" 1"" %" #" :#

It would ob+iousl$ be wrong to sa$ that the )unction signals the error DDK: di+ide b$ *eroCC now! e+en though an e+aluation o) the underlined sube8pression would demand it, A)ter all! !&"%"%# is tr.e and there)ore the application has a proper result:
""!m2-di0ide"%# &"!cond """"9!&"%"%#"'inf: """"9else"! "" /"" 1"" %" #" :# &"!cond """"9tr.e"'inf: """"9else"! "" /"" 1"" %" #" :# &"'inf

Fortunatel$! our laws o) e+aluation ta.e care o) these situations automaticall$, 1e Fust need to .eep in mind when the laws appl$, For e8ample! in
!+"!*"2%"2#"!/"2%"2##

the addition cannot ta.e place be)ore the multiplication or di+ision, Similarl$! the underlined di+ision in
!cond ""9!&"%"%#"'inf: ""9else"! "" /"" 1"" %" #" :#

cannot be e+aluated until the corresponding line is the )irst condition in the cond2 e8pression, As a rule o) thumb! it is best to .eep the )ollowing in mind:

=uideline on #8pression #+aluation


Simpli)$ the outermost /and le)t2most0 sube8pression that is read$ )or e+aluation, 1hile this guideline is a simpli)ication! it alwa$s e8plains SchemeCs results, In some cases! programmers also want to de)ine )unctions that raise errors, Recall the chec.ed +ersion o) area-of-dis- )rom section 9:
66"chec-ed-area-of-dis-":"Ccheme-0a+.e""-/""8oo+ean 66"to"comp.te"the"area"of"a"dis-"with"radi.s"0<"if"0"is"a"n.m8er !define"!chec-ed-area-of-dis-"0# ""!cond """"9!n.m8erA"0#"!area-of-dis-"0#: """"9else"!error"'chec-ed-area-of-dis-"1n.m8er"e*pected1#:##

I) we were to appl$ chec-ed-area-of-dis- to a s$mbol! we would get the )ollowing e+aluation:

""!-"!chec-ed-area-of-dis-"'a# """""!chec-ed-area-of-dis-"1%## &"!-"!cond """""""9!n.m8erA"'a#"!area-of-dis-"'a#: """""""9else"!error"'chec-ed-area-of-dis-"1n.m8er"e*pected1#:# """""!chec-ed-area-of-dis-"1%## &"!-"!cond """""""9fa+se"!area-of-dis-"'a#: """""""9else"!error"'chec-ed-area-of-dis-"1n.m8er"e*pected1#:# """""!chec-ed-area-of-dis-"1%## &"!-"!error"'chec-ed-area-of-dis-"1n.m8er"e*pected1# """""!chec-ed-area-of-dis-"1%## &"chec-ed-area-of-dis-":"n.m8er"e*pected

In other words! when we e+aluate the error e8pression! we proceed as i) we had encountered a di+ision b$ *ero,

4#* Boolean E,pressions


@ur current de)inition o) the Beginning Student Scheme language omits two )orms o) e8pressions: and and or e8pressions, Adding them pro+ides a case stud$ o) how to stud$ new language construct, 1e must )irst understand their s$nta8! then their semantics! and )inall$ their pragmatics, Here is the re+ised grammar: O /and ?e*p/ ?e*p/0 X /or ?e*p/ ?e*p/0 The grammar sa$s that and and or are .e$words! each )ollowed b$ two e8pressions, At )irst glance! the two loo. li.e /primiti+e or )unction0 applications, To understand wh$ the$ are not! we must loo. at the pragmatics o) these e8pressions )irst,
?e*p/

Suppose we need to )ormulate a condition that determines whether the n2th )raction o) 1 is m:
!and"!not"!&"n"%##" """""!&"!/"1"n#"m##

1e )ormulate the condition as an and combination o) two boolean e8pressions! because we donCt wish to di+ide b$ % accidentall$, -e8t! assume n becomes % during the course o) the e+aluation, Then the e8pression becomes
!and"!not"!&"%"%##" """""!&"!/"1"%#"m##

-ow! i) and were an ordinar$ operation! we would ha+e to e+aluate both sube8pressions! which would trigger an error in the second one, For this reason! and is

not a primiti+e operation! but a special e8pression, In short! we use and and or e8pressions to combine boolean computations that ma$ ha+e to short2cut an e+aluation, @nce we understand how and and or e8pressions should be e+aluated! it is eas$ to )ormulate matching rules, Better still! we can )ormulate e8pressions in our )irst language that are e?ui+alent to these e8pressions:
!and"?e*p-1/"?e*p-2/# & !cond ""9?e*p-1/"?e*p-2/: ""9else"fa+se:#

and
!or"?e*p-1/"?e*p-2/# & !cond ""9?e*p-1/"tr.e: ""9else"?e*p-2/:#

These e?ui+alences simpli)$ what actuall$ ta.es place in DrScheme but the$ are a per)ectl$ appropriate model )or now,

4#- 'aria&le Definitions


Programs consist not onl$ o) )unction de)initions but also +ariable de)initions! but these werenCt included in our )irst grammar, Here is the grammar rule )or +ariable de)initions:
?def/

O /define ?0ar/ ?e*p/0

The shape o) a +ariable de)inition is similar to that o) a )unction de)inition, It starts with a DD/CC! )ollowed b$ the .e$word define! )ollowed b$ a +ariable! )ollowed b$ an e8pression! and closed b$ a right parenthesis DD0CC that matches the +er$ )irst one, The .e$word define distinguishes +ariable de)initions )rom e8pressions! but not )rom )unction de)initions, For that! a reader must loo. at the second component o) the de)inition, -e8t we must understand what a +ariable de)inition means, A +ariable de)inition li.e
!define"Q'DIPC"5#

has a plain meaning, It sa$s that where+er we encounter Q'DIPC during an e+aluation! we ma$ replace it with 5,

1hen DrScheme encounters a de)inition with a proper e8pression on the right2hand side! it must e+aluate that e8pression immediatel$, For e8ample! the right2hand side o) the de)inition
!define"DI'H5;5Q"!*"2"Q'DIPC##

is the e8pression !*"2"Q'DIPC#, Its +alue is 1% because Q'DIPC stands )or 5, Hence we can act as i) we had written
!define"DI'H5;5Q"1%#

In short! when DrScheme encounters a +ariable de)inition! it determines the +alue o) the right2hand side, For that step! it uses all those de)initions that precede the current de)inition but not those that )ollow, @nce DrScheme has a +alue )or the right2hand side! it remembers that the name on the le)t2hand side stands )or this +alue, 1hene+er we e+aluate an e8pression! e+er$ occurrence o) the defined +ariable is replaced b$ its +alue,
!define"Q'DIPC"1%# !define"DI'H5;5Q"!*"2"Q'DIPC## 66"area":"n.m8er""-/""n.m8er 66"to"comp.te"the"area"of"a"dis-"with"radi.s"r !define"!area"r# ""!*"3.14"!*"r"r###

/define AR#A2@F2RADIAS /area RADIAS00 Figure 2!' An e8ample o) +ariable de)initions Consider the se?uence o) de)initions in )igure &5, As DrScheme steps through this se?uence o) de)initions! it )irst determines that Q'DIPC stands )or 1%! DI'H5;5Q )or 2%! and area is the name o) a )unction, Finall$! it e+aluates !area"Q'DIPC# to 314.% and associates 'Q5'-N>-Q'DIPC with that +alue, E ercise )<&<1< Ma.e up )i+e e8amples o) +ariable de)initions, Ase constants and e8pressions on the right2hand side, Solution E ercise )<&<2< #+aluate the )ollowing se?uence o) de)initions
!define"Q'DIPC"1%# !define"DI'H5;5Q"!*"2"Q'DIPC## !define"7IQ7PH>5Q5J75"!*"3.14"DI'H5;5Q##

b$ hand,

Solution

E ercise )<&<!< #+aluate the )ollowing se?uence o) de)initions

!define"3QI75"5# !define"C'L5C-;'R"!*".%$"3QI75## !define";N;'L"!+"3QI75"C'L5C-;'R##

b$ hand,

Solution

4#0 Structure Definitions


1e still ha+e to understand the s$nta8 and semantics o) one more Scheme construct: define-struct, 1hen we de)ine a structure! we reall$ de)ine se+eral primiti+e operations: a constructor! se+eral selectors! and a predicate, Hence! define-struct is b$ )ar the most comple8 Scheme construct we use, A structure de)inition is a third )orm o) de)inition, The .e$word define-struct distinguishes this )orm o) de)inition )rom )unction and +ariable de)initions, The .e$word is )ollowed b$ a name and a se?uence o) names enclosed in parentheses: The names names! though none o) them is used as a )unction /or +ariable0 name, Here is a simple e8ample:
""!define-struct"point"!*"2"@##"." ?def/ O /define-struct ?0ar%/ /?0ar-1/ ... ?0ar-n/00 , in a define-struct de)inition must be chosen as i) the$ were )unction

Since point! *! 2! and @ are +ariables and the parentheses are placed according to the grammatical pattern! it is a proper de)inition o) a structure, In contrast! these two parenthesi*ed sentences
""!define-struct"!point"*"2"@## ""!define-struct"point"*"2"@#

are improper de)initions! because define-struct is not )ollowed b$ a single +ariable name and a se?uence o) +ariables in parentheses, A define-struct de)inition introduces new primiti+e operations, The names o) these operations are )ormed )rom those that occur in the de)inition, Suppose a data structure de)inition has the )ollowing shape:
""!define-struct"c"!s-1"..."s-n##

Then Scheme introduces the )ollowing primiti+e operations: (, ma-e-c: a C@-STRACT@RE

&, c-s-1"..."c-s-n: a series o) S#"#CT@RSE and 5, cA: a PR#DICAT#, These primiti+es ha+e the same status as +! -! or *, Be)ore we can understand the rules that go+ern these new primiti+es! howe+er! we must return to the de)inition o) +alues, A)ter all! the purpose o) define-struct is to introduce a new class o) +alues: structures, Simpl$ put! the set o) +alues no longer consists o) Fust constants! but also o) structures! which compound se+eral +alues into one, In terms o) our grammar o) +alues! we must add one clause per define-struct:
?0a+/

O /ma.e2c ?0a+/ ,,, ?0a+/0

"et us return to the points structures, Since the list o) )ields contains three names! !ma-e-point"."0"w# is a +alue i) .! 0! and w are +alues, -ow we are in a position to understand the e+aluation rules o) the new primiti+es, I) cs-1 is applied to a c structure! it returns the )irst component o) the +alue, Similarl$! the second selector e8tracts the second component! the third selector the third component! and so on, The relationship between the new data constructor and the selectors is best characteri*ed with n e?uations:
!c-s-1"!ma-e-c"W-1"..."W-n##"&"W-1 """""""""""""""""" !c-s-n"!ma-e-c"W-1"..."W-n##"&"W-n

where W-1"..."W-n is a se?uence o) +alues that is as long as s-1"..."s-n, For our running e8ample! we get the e?uations
!point-*"!ma-e-point"W"P"O##"&"W !point-2"!ma-e-point"W"P"O##"&"P !point-@"!ma-e-point"W"P"O##"&"O

In particular! !point-2"!ma-e-point"3"4"5## is e?ual to 4! and !point-*"!ma-epoint"!ma-e-point"1"2"3#"4"5## e+aluates to !ma-e-point"1"2"3# because the latter is also a +alue, The predicate cA can be applied to an$ +alue, It returns tr.e i) the +alue is o) .ind c and fa+se otherwise, 1e can translate both parts into e?uations, The )irst one!
!cA"!ma-e-c"W-1"..."W-n##"&"tr.e","

relates cA and +alues constructed with ma-e-cE the second one!

!cA"W#"&"fa+se6"if"W"is"a"0a+.e"not"constr.cted"with"ma-e-c"<"

relates cA to all other +alues, Again! the e?uations are best understood in terms o) our e8ample, Here are the general e?uations:
!pointA"!ma-e-point"W"P"O##"&"tr.e !pointA"P#"&"fa+se"6"if"P"is"0a+.e<"8.t"not"a"point"str.ct.re.

Thus! !pointA"!ma-e-point"3"4"5## is tr.e and !pointA"3# is fa+se, E ercise )<(<1< Distinguish legal )rom illegal sentences: (, !define-struct"personne+-record"!name"sa+ar2"do8"ssn## &, !define-struct"oops"!## 5, !define-struct"chi+d"!do8"date"!-"date"do8### 6, !define-struct"!chi+d"person#"!do8"date## 7, !define-struct"chi+d"!parents"do8"date## #8plain wh$ the sentences are legal define-struct de)initions or how the$ )ail to be legal define-struct de)initions, Solution E ercise )<(<2< 1hich o) the )ollowing are +aluesH (, !ma-e-point"1"2"3# &, !ma-e-point"!ma-e-point"1"2"3#"4"5# 5, !ma-e-point"!+"1"2#"3"4# Solution

E ercise )<(<!< Suppose the Definitions window contains

!define-struct"8a++"!*"2"speed-*"speed-2##

Determine the results o) the )ollowing e8pressions: (, !n.m8erA"!ma-e-8a++"1"2"3"4## &, !8a++-speed-2"!ma-e-8a++"!+"1"2#"!+"3"3#"2"3## 5, !8a++-2"!ma-e-8a++"!+"1"2#"!+"3"3#"2"3## Also chec. how DrScheme deals with the )ollowing e8pressions: (, !n.m8erA"!ma-e-8a++"1"3"4## &, !8a++-*"!ma-e-posn"1"2## 5, !8a++-speed-2"5# 4eri)$ $our solutions with DrScheme,
?def/

Solution

O /define /?0ar/ ?0ar/ ...?0ar/0 ?e*p/0 X /define ?0ar/ ?e*p/0 X /define-struct ?0ar%/ /?0ar-1/ ...?0ar-n/00 ?e*p/ O ?0ar/ X ?con/ X /?prm/ ?e*p/ ...?e*p/0 X /?0ar/ ?e*p/ ...?e*p/0 X /cond /?e*p/ ?e*p/0 .../?e*p/ ?e*p/00 X /cond /?e*p/ ?e*p/0 .../else ?e*p/00 X /and ?e*p/ ?e*p/0 X /or ?e*p/ ?e*p/0 Figure 2#' (eginning"Ct.dent Scheme: The )ull grammar 1e use di))erent )onts to distinguish the words o) di))erent categories, Constants and primiti+e operations are t$pe set in sans seri)! +ariables in ita!ics! and .e$words in boldface,
&;

This grammar describes onl$ that portion o) Scheme we ha+e used so )ar /minus +ariable and structure de)initions0! which still co+ers a large subset o) the )ull language, Scheme is a bit larger! and we will get to .now more o) it in the remaining parts o) the boo.,
&<

Part II Processing +rbitraril% ,arge Data Section Compound Data, Part 2' ,ists
Structures are one wa$ to represent compound in)ormation, The$ are use)ul when we .now how man$ pieces o) data we wish to combine, In man$ cases! howe+er! we donCt .now how man$ things we wish to enumerate! and in that case we )orm a list, A list can be o) arbitrar$ length! that is! it contains a )inite! but undetermined number o) pieces o) data, Forming lists is something that all o) us do, Be)ore we go grocer$ shopping! we o)ten write down a list o) items that we want to purchase, 1hen we plan out a da$ in the morning! we write down a list o) things to do, During December! man$ children prepare Christmas wish lists, To plan a part$! we list the people we want to in+ite, In short! arranging in)ormation in the )orm o) lists is a ubi?uitous part o) our li)e! and we should learn to represent lists as Scheme data, In this section! we )irst learn to create lists and then mo+e on to de+eloping )unctions that consume lists,

6#$ Lists
1hen we )orm a list! we alwa$s start out with the empt$ list, In Scheme!
empt2

represents the empt$ list, From here! we can construct a longer list with the operation cons, Here is a simple e8ample:
!cons"'Herc.r2"empt2#"

In this e8ample! we constructed a list )rom the empt2 list and the s$mbol 'Herc.r2, Figure &7 presents this list in the same pictorial manner we used )or structures, The bo8

)or cons has two )ields: first and rest, In this speci)ic e8ample the first )ield contains 'Herc.r2 and the rest )ield contains empt2, /cons CMercur$ empt$0 /cons C4enus /cons CMercur$ empt$00 /cons C#arth /cons C4enus /cons CMercur$ empt$000 CMercur$ empt$ C4enus CMercur$ empt$ C#arth C4enus CMercur$ empt$

Figure 2$' Building a list @nce we ha+e a list with one item on it! we can construct lists with two items b$ using cons again:
!cons"'Wen.s"!cons"'Herc.r2"empt2##

The middle row o) )igure &7 shows how we should imagine the second list, It is also a bo8 o) two )ields! but this time the rest )ield contains a bo8, Indeed! it contains the bo8 )rom the top row o) the same )igure, Finall$! we construct a list with three items:
!cons"'5arth"!cons"'Wen.s"!cons"'Herc.r2"empt2###

The last row o) )igure &7 illustrates the list with three items, Its rest )ield contains a bo8 that contains a bo8 again, So! as we create lists we put bo8es into bo8es into bo8es! etc, 1hile this ma$ appear strange at )irst glance! it is Fust li.e a set o) Chinese gi)t bo8es or a set o) nested drin.ing cups! which we sometimes get )or our earl$ birthda$s, The onl$ di))erence is that Scheme programs can nest lists much deeper than an$ artist could nest ph$sical bo8es, E ercise -<1<1< Create Scheme lists that represent (, the list o) all planets in our solar s$stemE &, the )ollowing meal: stea.! pommes2)rites! beans! bread! water! Fuice! brie2cheese! and ice2creamE and 5, the list o) basic colors,

S.etch bo8 representations o) these lists! similar to those in )igure &7,

Solution

1e can also ma.e lists o) numbers, As be)ore! empt2 is the list without an$ items, Here is a list with (' numbers:
!cons"% ""!cons"1 """"!cons"2 """"""!cons"3 """"""""!cons"4 """"""""""!cons"5 """"""""""""!cons" """"""""""""""!cons"7 """"""""""""""""!cons"$ """"""""""""""""""!cons","empt2##########

To build it re?uires (' list constructions and one empt2 list, In general a list does not ha+e to contain +alues o) one .ind! but ma$ contain arbitrar$ +alues:
!cons"'Qo882Qo.nd ""!cons"3" """"!cons"tr.e """"""empt2###

Here the )irst item is a s$mbol! the second one is a number! and the last one a boolean, 1e could thin. o) this list as the representation o) a personnel record that includes the name o) the emplo$ee! the number o) $ears spent at the compan$! and whether the emplo$ee has health insurance through the compan$ plan, -ow suppose we are gi+en a list o) numbers, @ne thing we might wish to do is add up the numbers on the list, To ma.e this more concrete! let us assume that we are onl$ interested in lists o) three numbers: A !ist-of-3-n mbers is
!cons"*"!cons"2"!cons"@"empt2###

where *! 2! and @ are numbers, 1e write down the contract! purpose! header! and e8amples as be)ore:
66"add-.p-3":"+ist-of-3-n.m8ers""-/""n.m8er 66"to"add".p"the"three"n.m8ers"in"a-+ist-of-3-n.m8ers 66"e*amp+es"and"tests:" 66"""!&"!add-.p-3"!cons"2"!cons"1"!cons"3"empt2####" # 66"""!&"!add-.p-3"!cons"%"!cons"1"!cons"%"empt2####"1# !define"!add-.p-3"a-+ist-of-3-n.m8ers#"...#

To de)ine the bod$! howe+er! presents a problem, A constructed list is li.e a structure, Hence we should la$out a template with selector e8pressions ne8t, An)ortunatel$! we donCt .now how to select items )rom a list,

In analog$ to structure selectors! Scheme implements operations )or e8tracting the )ields )rom a constructed list: first and rest,&> The first operation e8tracts the item that we used to construct a listE the rest operation e8tracts the list )ield, To describe how first! rest! and cons are related! we can use e?uations that are similar to the e?uations that go+ern addition and subtraction and structure creation and )ield e8traction:
""! """ first"! " ""cons "" """" 1%""" " empt2## " "" &"1% ""! """ rest"! " ""cons "" """" 1%""" " empt2## " "" &"empt2 ""!first"! """ rest"! " ""cons "" """"! 1%""cons " "" """" 22""" " empt2### " "" # &"! """ first"! " ""cons "" """" 22""" " empt2## " "" &"22

The last one demonstrates how to e+aluate nested e8pressions, The .e$ is to thin. o) !cons"a-0a+.e"a-+ist# as a +alue, And! as alwa$s! we start with the e+aluation o) the innermost parenthesi*ed e8pressions that can be reduced! Fust as in arithmetic, In the abo+e calculations! the e8pressions that are about to be reduced ne8t are underlined, Asing first and rest we can now write down a template )or add-.p-3:
66"add-.p-3":"+ist-of-3-n.m8ers""-/""n.m8er 66"to"add".p"the"three"n.m8ers"in"a-+ist-of-3-n.m8ers !define"!add-.p-3"a-+ist-of-3-n.m8ers#" ""..."!first"a-+ist-of-3-n.m8ers#"..." ""..."!first"!rest"a-+ist-of-3-n.m8ers##"... ""..."!first"!rest"!rest"a-+ist-of-3-n.m8ers###"..."#

The three e8pressions remind us that the input! called a-+ist-of-3-n.m8ers! contains three components and how to e8tract them, E ercise -<1<2< "et + be the list
!cons"1%"!cons"2%"!cons"5"empt2###

1hat are the +alues o) the )ollowing e8pressionsH (, !rest"+# &, !first"!rest"+## 5, !rest"!rest"+##

6, !first"!rest"!rest"+### 7, !rest"!rest"!rest"+### Solution

E ercise -<1<!< Finish the de+elopment o) add-.p-3! that is! de)ine the bod$ and test the complete )unction on some e8amples, A list o) three numbers is one possible representation )or 52dimensional points, The distance o) a 52dimensional point to the origin o) the coordinate grid is computed in the same manner as that o) &2dimensional point: b$ s?uaring the numbers! adding them up! and ta.ing the s?uare root, Ase the template )or add-.p-3 to de+elop distance-to-%-for-3! which computes the distance o) a 52dimensional point to the origin, Solution E ercise -<1<#< Pro+ide a data de)inition )or lists o) two s$mbols, Then de+elop the )unction contains-2-do++A! which consumes a list o) two s$mbols and determines whether one o) them is 'do++, Solution :n the Precise 0elationship bet3een Cons and Structures: The discussion o) cons! first! and rest suggests that cons creates a structure and first and rest are ordinar$ selectors:
!define-struct"pair"!+eft"right## !define"!o.r-cons"a-0a+.e"a-+ist#"!ma-e-pair"a-0a+.e"a-+ist## !define"!o.r-first"a-pair#"!pair-+eft"a-pair## !define"!o.r-rest"a-pair#"!pair-right"a-pair## !define"!o.r-consA"*#"!pairA"*##

Although these de)initions are a good )irst appro8imation! the$ are inaccurate in one important point, DrSchemeCs +ersion o) cons is reall$ a chec.ed +ersion o) ma-e-pair, Speci)icall$! the cons operation ensures that the right )ield is alwa$s a list! that is! constructed or empt2, This suggests the )ollowing re)inement:
!define"!o.r-cons"a-0a+.e"a-+ist# ""!cond """"9!empt2A"a-+ist#"!ma-e-pair"a-0a+.e"a-+ist#: """"9!o.r-consA"a-+ist#"!ma-e-pair"a-0a+.e"a-+ist#: """"9else"!error"'o.r-cons"1+ist"as"second"arg.ment"e*pected1#:##

The de)initions )or o.r-first! o.r-rest! and o.r-consA remain the same, Finall$! we must also promise not to use ma-e-pair directl$ so that we donCt accidentall$ build a bad list,

6#" Data Definitions for Lists of


)irst! rest

r&itrary Length

Suppose we wish to represent the in+entor$ o) a to$ store that sells such things as dolls! ma.e2up sets! clowns! bows! arrows! and soccer balls, To ma.e an in+entor$! a store owner would start with an empt$ sheet o) paper and slowl$ write down the names o) the to$s on the +arious shel+es, Representing a list o) to$s in Scheme is straight)orward, 1e can simpl$ use SchemeCs s$mbols )or to$s and then construct lists )rom them, Here are a )ew short samples:
empt2 !cons"'8a++"empt2# !cons"'arrow"!cons"'8a++"empt2## !cons"'c+own"empt2# !cons"'8ow"!cons"'arrow"empt2## !cons"'c+own"!cons"'do++"!cons"'arrow"!cons"'8a++"empt2####

For a real store! the list will contain man$ more items! and the list will grow and shrin. o+er time, In an$ case! we cannot sa$ in ad+ance how man$ items these in+entor$ lists will contain, Hence! i) we wish to de+elop a )unction that consumes such lists! we cannot simpl$ sa$ that the input is a list with either one! two! three! or )our items, 1e must be prepared to thin. about lists o) arbitrar$ length, In other words! we need a data de)inition that precisel$ describes the class o) lists that contain an arbitrar$ number o) s$mbols, An)ortunatel$! the data de)initions we ha+e seen so )ar can onl$ describe classes o) data where each item is o) a )i8ed si*e! such as a structure with a speci)ic number o) components or a list with a speci)ic number o) items, So how can we describe a class o) lists o) arbitrar$ si*eH "oo.ing bac. we see that all our e8amples )all into one o) two categories, The store owner starts with an empt$ list and constructs longer and longer lists, The construction proceeds b$ constructing together a to$ and another list o) to$s, Here is a data de)inition that re)lects this process: A !ist-of-symbo!s is either (, the empt$ list! empt2! or &, !cons"s"+os# where s is a s$mbol and +os is a list o) s$mbols,

This de)inition is unli.e an$ o) the de)initions we ha+e seen so )ar or that we encounter in high school #nglish or mathematics, Those de)initions e8plain a new idea in terms o) old! well2understood concepts, In contrast! this de)inition re)ers to itse!f in the item labeled &! which implies that it e8plains what a list o) s$mbols is in terms o) lists o) s$mbols, 1e call such de)initions S#"F2R#F#R#-TIA" or R#CARSI4#, At )irst glance! a de)inition that e8plains or speci)ies something in terms o) itsel) does not seem to ma.e much sense, This )irst impression! howe+er! is wrong, A recursi+e de)inition! such as the one abo+e! ma.es sense as long as we can construct some elements )rom itE the de)inition is correct i) we can construct all intended elements,5' "etCs chec. whether our speci)ic data de)inition ma.es sense and contains all the elements we are interested in, From the )irst clause we immediatel$ .now that empt2 is a list o) s$mbols, From the second clause we .now that we can create larger lists with cons )rom a s$mbol and a list o) s$mbols, Thus !cons"'8a++"empt2# is a list o) s$mbols because we Fust determined that empt2 is one and we .now that 'do++ is a s$mbol, There is nothing special about 'do++, An$ other s$mbol could ser+e e?uall$ well to )orm a number o) one2item lists o) s$mbols:
!cons"'ma-e-.p-set"empt2# !cons"'water-g.n"empt2# ...

@nce we ha+e lists that contain one s$mbol! we can use the same method to build lists with two items:
!cons"'(ar8ie"!cons"'ro8ot"empt2## !cons"'ma-e-.p-set"!cons"'water-g.n"empt2## !cons"'8a++"!cons"'arrow"empt2## ...

From here! it is eas$ to see how we can )orm lists that contain an arbitrar$ number o) s$mbols, More important still )or our problem! all possible in+entories are ade?uatel$ described b$ our data de)inition, E ercise -<2<1< Show that all the in+entor$ lists discussed at the beginning o) this section belong to the class +ist-of-s2m8o+s, Solution E ercise -<2<2< Do all lists o) two s$mbols also belong to the class +ist-of-s2m8o+sH Pro+ide a concise argument, Solution E ercise -<2<!< Pro+ide a data de)inition )or the class o) list o) booleans, The class contains all arbitraril$ large lists o) booleans, Solution

6#( Processing Lists of


8nnatural Recursions

r&itrary Length

A real store will want to ha+e a large in+entor$ on2line! that is! put into a computer! so that an emplo$ee can ?uic.l$ determine whether a to$ is a+ailable or not, For simplicit$! assume that we need contains-do++A! a )unction that chec.s whether the store has a 'do++, Translated into Scheme terminolog$! the )unction determines whether 'do++ occurs on some list o) s$mbols, Because we alread$ ha+e a rigorous de)inition o) contains-do++ACs input! we turn to the contract! header! and purpose statement:
66"contains-do++A":"+ist-of-s2m8o+s""-/""8oo+ean 66"to"determine"whether"the"s2m8o+"'do++"occ.rs"on"a-+ist-ofs2m8o+s !define"!contains-do++A"a-+ist-of-s2m8o+s#"...#

Following the general design recipe! we ne8t ma.e up some e8amples that illustrate contains-do++A purpose, First! we clearl$ need to determine the output )or the simplest input: empt2, Since the list does not contain an$ s$mbol! it certainl$ does not contain 'do++! and the answer should be fa+se:
!8oo+ean&A"!contains-do++A"empt2#" """""""""""fa+se#

-e8t! we consider lists with a single item, Here are two e8amples:
!8oo+ean&A"!contains-do++A"!cons"'8a++"empt2##" """""""""""fa+se# !8oo+ean&A"!contains-do++A"!cons"'do++"empt2## """""""""""tr.e#

In the )irst case! the answer is fa+se because the single item on the list is not 'do++E in the second case! the item is 'do++! and the answer is tr.e, Finall$! here are two more general e8amples! with lists o) se+eral items:
!8oo+ean&A"!contains-do++A"!cons"'8ow"!cons"'a*"!cons"'8a++ empt2#### """""""""""fa+se# !8oo+ean&A"!contains-do++A"!cons"'arrow"!cons"'do++"!cons"'8a++ empt2#### """""""""""tr.e#

Again! the answer in the )irst case must be fa+se because the list does not contain 'do++! and in the second case it must be tr.e because 'do++ is one o) the items on the list pro+ided to the )unction,

The ne8t step is to design a )unction template that matches the data de)inition, Since the data de)inition )or lists o) s$mbols has two clauses! the )unctionCs bod$ must be a cond2 e8pression, The cond2e8pression determines which o) the two .inds o) lists the )unction recei+ed: the empt2 list or a constructed list:
!define"!contains-do++A"a-+ist-of-s2m8o+s# ""!cond """"9!empt2A"a-+ist-of-s2m8o+s#"...: """"9!consA"a-+ist-of-s2m8o+s#"...:##

Instead o) !consA"a-+ist-of-s2m8o+s#! we can use else in the second clause, 1e can add one more hint to the template b$ stud$ing each clause o) the cond2 e8pression in turn, Speci)icall$! recall that the design recipe suggests annotating each clause with selector e8pressions i) the corresponding class o) inputs consists o) compounds, In our case! we .now that empt2 does not ha+e compounds! so there are no components, @therwise the list is constructed )rom a s$mbol and another list o) s$mbols! and we remind oursel+es o) this )act b$ adding !first"a-+ist-of-s2m8o+s# and !rest"a-+ist-of-s2m8o+s# to the template:
!define"!contains-do++A"a-+ist-of-s2m8o+s# ""!cond """"9!empt2A"a-+ist-of-s2m8o+s#"...: """"9else"..."!first"a-+ist-of-s2m8o+s#"..."!rest"a-+ist-ofs2m8o+s#"...:##

-ow that we ha+e a template based on our design recipes )or mi8ed and compound data! we turn to the de)inition o) the )unctionCs bod$! dealing with each cond2clause separatel$, I) !empt2A"a-+ist-of-s2m8o+s# is true! the input is the empt$ list! in which case the )unction must produce the result fa+se, In the second case! !consA"a+ist-of-s2m8o+s# is true, The annotations in the template remind us that there is a )irst s$mbol and the rest o) the list, So let us consider an e8ample that )alls into this categor$:
!cons"'arrow" ""!cons"... """"""..."empt2###

The )unction! Fust li.e a human being! must clearl$ compare the )irst item with 'do++, In this e8ample! the )irst s$mbol is 'arrow and not 'do++! so the comparison will $ield fa+se, I) we had considered some other e8ample instead! sa$!
!cons"'do++ ""!cons"... """"""..."empt2###

the )unction would determine that the )irst item on the input is 'do++! and would there)ore respond with tr.e, All o) this implies that the second line in the cond2 e8pression should contain another cond2e8pression:
!define"!contains-do++A"a-+ist-of-s2m8o+s# ""!cond """"9!empt2A"a-+ist-of-s2m8o+s#"fa+se:

""""9else"!cond """"""""""""9!s2m8o+&A"!first"a-+ist-of-s2m8o+s#"'do++#" """""""""""""tr.e: """"""""""""9else """""""""""""..."!rest"a-+ist-of-s2m8o+s#"...:#:##

Furthermore! i) the comparison o) !first"a-+ist-of-s2m8o+s# $ields tr.e! the )unction is done and produces tr.e! too, I) the comparison $ields fa+se! we are le)t with another list o) s$mbols: !rest"a+ist-of-s2m8o+s#, Clearl$! we canCt .now the )inal answer in this case! because depending on what DD...CC represents! the )unction must produce tr.e or fa+se, Put di))erentl$! i) the )irst item is not 'do++! we need some wa$ to chec. whether the rest o) the list contains 'do++, Fortunatel$! we ha+e Fust such a )unction: contains-do++A! which according to its purpose statement determines whether a list contains 'do++, The purpose statement implies that i) + is a list o) s$mbols! !contains-do++A"+# tells us whether + contains the s$mbol 'do++, Similarl$! !contains-do++A"!rest"+## determines whether the rest o) + contains 'do++, And in the same +ein! !contains-do++A"!rest"a-+ist-ofs2m8o+s## determines whether or not 'do++ is in !rest"a-+ist-of-s2m8o+s#! which is precisel$ what we need to .now now, Here is the complete de)inition o) the )unction:
!define"!contains-do++A"a-+ist-of-s2m8o+s# ""!cond """"9!empt2A"a-+ist-of-s2m8o+s#"fa+se: """"9else"!cond """"""""""""9!s2m8o+&A"!first"a-+ist-of-s2m8o+s#"'do++#"tr.e: """"""""""""9else"!contains-do++A"!rest"a-+ist-of-s2m8o+s##:#:##

It consumes a list o) s$mbols and determines whether or not it is empt$, I) it is! the result is fa+se, @therwise! the list is not empt$ and the result o) the )unction depends on the )irst item o) the list, I) the )irst item is 'do++! the result is tr.eE i) not! the )unctionCs result is the result o) searching the rest o) the input list 22 whate+er it is, E ercise -<!<1< Ase DrScheme to test the de)inition o) contains-do++A on our e8amples:
empt2 !cons"'8a++"empt2# !cons"'arrow"!cons"'do++"empt2## !cons"'8ow"!cons"'arrow"!cons"'8a++"empt2###

Solution

E ercise -<!<2< Another wa$ o) )ormulating the second cond2clause in the )unction contains-do++A is to understand
!contains-do++A"!rest"a-+ist-of-s2m8o+s##

as a condition that e+aluates to either tr.e or fa+se! and to combine it appropriatel$ with the condition
!s2m8o+&A"!first"a-+ist-of-s2m8o+s#"'do++#

Re)ormulate the de)inition o) contains-do++A according to this obser+ation, Solution E ercise -<!<!< De+elop the )unction containsA! which consumes a s$mbol and a list o) s$mbols and determines whether or not the s$mbol occurs in the list, Solution

6#) Designing +unctions for Self7Referential Data Definitions


At )irst glance! sel)2re)erential data de)initions seem to be )ar more comple8 than those )or compound or mi8ed data, But! as the e8ample in the preceding subsection shows! our design recipes still wor., -e+ertheless! in this section we discuss a new design recipe that wor.s better )or sel)2re)erential data de)initions, As implied b$ the preceding section! the new recipe generali*es those )or compound and mi8ed data, The new parts concern the process o) disco+ering when a sel)2re)erential data de)inition is needed! deri+ing a template! and de)ining the )unction bod$: Data +nal%sis and Design' I) a problem statement discusses compound in)ormation o) arbitrar$ si*e! we need a recursi+e or sel)2re)erential data de)inition, At this point! we ha+e onl$ seen one such class! +ist-of-s2m8o+s! but it is eas$ to imagine other! $et similar classes o) lists, 1e will get to .now man$ other e8amples in this and the )ollowing part,5( For a recursi+e data de)inition to be +alid! it must satis)$ two conditions, First! it must contain at least two clauses, Second! at least one o) the clauses must not re)er bac. to the de)inition, It is good practice to identi)$ the sel)2re)erences e8plicitl$ with arrows )rom the re)erences in the data de)inition bac. to its beginning, @ur running e8ample )or this section are )unctions that consume lists o) s$mbols:

Template' A sel)2re)erential data de)inition speci)ies a mi8ed class o) data! and one o) the clauses should speci)$ a subclass o) compound data, Hence the design o) the template can proceed according to the recipes in sections 9,7 and ;,&, Speci)icall$! we )ormulate a cond2e8pression with as man$ cond2clauses as there are clauses in the data de)inition! match each recogni*ing condition to the corresponding clause in the data de)inition! and write down appropriate selector e8pressions in all cond2lines that process compound +alues, In addition! we inspect each selector e8pression, For each that e8tracts a +alue o) the same class o) data as the input! we draw an arrow bac. to the )unction parameter, At the end! we must ha+e as man$ arrows as we ha+e in the data de)inition, "etCs return to the running e8ample, The template )or a list2processing )unction contains a cond2e8pression with two clauses and one arrow:

For simplicit$! this boo. will use a te8tual alternati+e to arrows, Instead o) drawing an arrow! the templates contain sel)2applications o) the )unction to the selector e8pression/s0:
!define"!f.n-for-+os"a-+ist-of-s2m8o+s# ""!cond """"9!empt2A"a-+ist-of-s2m8o+s#"...: """"9else"..."!first"a-+ist-of-s2m8o+s#"... """"""..."!f.n-for-+os"!rest"a-+ist-of-s2m8o+s##"...:##

1e re)er to these sel)2applications as -ATARA" R#CARSI@-S, 5od%' For the design o) the bod$ we start with those cond2lines that do not contain natural recursions, The$ are called BAS# CAS#S, The corresponding answers are t$picall$ eas$ to )ormulate or are alread$ gi+en b$ the e8amples,

Then we deal with the sel)2re)erential cases, 1e start b$ reminding oursel+es what each o) the e8pressions in the template line computes, For the recursi+e application we assume that the )unction alread$ wor.s as speci)ied in our purpose statement, The rest is then a matter of combining the 1arious 1alues< Suppose we wish to de)ine the )unction how-man2! which determines how man$ s$mbols are on a list o) s$mbols, Assuming we ha+e )ollowed the design recipe! we ha+e the )ollowing:
66"how-man2":"+ist-of-s2m8o+s""-/""n.m8er 66"to"determine"how"man2"s2m8o+s"are"on"a-+ist-of-s2m8o+s !define"!how-man2"a-+ist-of-s2m8o+s# ""!cond """"9!empt2A"a-+ist-of-s2m8o+s#"...: """"9else"..."!first"a-+ist-of-s2m8o+s#"..." """"""..."!how-man2"!rest"a-+ist-of-s2m8o+s##"...:##

The answer )or the base case is % because the empt$ list contains nothing, The two e8pressions in the second clause compute the first item and the number o) s$mbols on the !rest"a-+ist-of-s2m8o+s#, To compute how man$ s$mbols there are on all o) a-+ist-of-s2m8o+s! we Fust need to add 1 to the +alue o) the latter e8pression:
!define"!how-man2"a-+ist-of-s2m8o+s# ""!cond """"9!empt2A"a-+ist-of-s2m8o+s#"%: """"9else"!+"!how-man2"!rest"a-+ist-of-s2m8o+s##"1#:##

Combining "alues' In man$ cases! the combination step can be e8pressed with SchemeCs primiti+es! )or e8ample! +! and! or cons, I) the problem statement suggests that we as. ?uestions about the )irst item! we ma$ need a nested cond2statement, Finall$! in some cases! we ma$ ha+e to de)ine au8iliar$ )unctions, Figure &9 summari*es this discussion in the usual )ormatE those design steps that we didnCt discuss are per)ormed as be)ore, The )ollowing section discusses se+eral e8amples in detail,

Phase Data Anal$sis and Design Contract Purpose and Header

=oal to )ormulate a data de)inition

#8amples

Template

Bod$

Test

Acti+it$ de+elop a data de)inition )or mi8ed data with at least two alternati+es one alternati+e must not re)er to the de)inition e8plicitl$ identi)$ all sel)2re)erences in the data de)inition to name the name the )unction! the classes o) input data! the )unctionE class o) output data! and speci)$ its purpose: to speci)$ its EE name : in1 in2 ...22S o t classes o) EE to compute ... )rom +1 ... input data and /define /name +1 +2 ...0 ...0 its class o) output dataE to describe its purposeE to )ormulate a header to characteri*e create e8amples o) the input2output relationship the input2 ma.e sure there is at least one e8ample per subclass output relationship +ia e8amples to )ormulate an de+elop a cond2e8pression with one clause per outline alternati+e add selector e8pressions to each clause annotate the bod$ with nat ra! rec rsions T#ST: the sel)2re)erences in this template and the data de)inition matchL to de)ine the )ormulate a Scheme e8pression )or each simple )unction cond2line e8plain )or all other cond2clauses what each natural recursion computes according to the purpose statement to disco+er appl$ the )unction to the inputs o) the e8amples mista.es chec. that the outputs are as predicted /DDt$posCC and logic0

Figure 2&' Designing a )unction )or sel)2re)erential data /Re)ines the recipes in )igures 6 /pg, 70! (& /pg, >0! and (< /pg, ('00

6#* /ore on Processing Simple Lists


"et us now loo. at another aspect o) in+entor$ management: the cost o) an in+entor$, In addition to a list o) the a+ailable to$s! a store owner should also maintain a list o) the cost o) each item, The cost list permits the owner to determine how much the current in+entor$ is worth or! gi+en the in+entor$ at the beginning o) the $ear and that o) the end o) the $ear! how much pro)it the store ma.es,

A list o) costs is most easil$ represented as a list, For e8ample:


empt2 !cons"1.22"empt2# !cons"2.5,"empt2# !cons"1.22"!cons"2.5,"empt2## !cons"17.%5"!cons"1.22"!cons"2.5,"empt2###

Again! )or a real store! we cannot place an arbitrar$ limit on the si*e o) such a list! and )unctions that process such cost lists must be prepared to consume lists o) arbitrar$ si*e, Suppose the to$ store needs a )unction that computes the +alue o) an in+entor$ )rom the cost o) the indi+idual to$s, 1e call this )unction s.m, Be)ore we can de)ine s.m! we must )igure out how to describe all possible lists o) numbers that the )unction ma$ consume, In short! we need a data de)inition that precisel$ de)ines what an arbitraril$ large list o) numbers is, 1e can obtain this de)inition b$ replacing DDs$mbolCC with DDnumberCC in the de)inition o) lists o) s$mbols: A !ist-of-n mbers is either (, the empt$ list! empt2! or &, !cons"n"+on# where n is a number and +on is a list o) numbers, =i+en that this data de)inition is sel)2re)erential again! we must )irst con)irm that it actuall$ de)ines some lists and that it de)ines all those in+entories that we wish to represent, All o) the e8amples abo+e are lists o) numbers, The )irst one! empt2! is included e8plicitl$, The second and third are constructed b$ adding the numbers 1.22 and 2.5,! respecti+el$! to the empt$ list, The others are lists o) numbers )or similar reasons, As alwa$s! we start the de+elopment o) the )unction with a contract! header! and purpose statement:
66"s.m":"+ist-of-n.m8ers""-/""n.m8er 66"to"comp.te"the"s.m"of"the"n.m8ers"on"a-+ist-of-n.ms !define"!s.m"a-+ist-of-n.ms#"...#

Then we continue with )unction e8amples:


!&"!s.m"empt2#" """%# !&"!s.m"!cons"1.%%"empt2## """1.%# !&"!s.m"!cons"17.%5"!cons"1.22"!cons"2.5,"empt2#### """2%.$ #

I) s.m is applied to empt2! the store has no in+entor$ and the result should be %, I) the input is !cons"1.%%"empt2#! the in+entor$ contains onl$ one to$! and the cost o) the to$ is the cost o) the in+entor$, Hence the result is 1.%%, Finall$! )or !cons"17.%5 !cons"1.22"!cons"2.5,"empt2###! s.m should $ield

For the design o) s.mCs template! we )ollow the design recipe! step b$ step, First! we add the cond2e8pression:
!define"!s.m"a-+ist-of-n.ms# ""!cond """"9!empt2A"a-+ist-of-n.ms#"...: """"9!consA"a-+ist-of-n.ms#"...:##

The second clause indicates with a comment that it deals with constructed lists, Second! we add the appropriate selector e8pressions )or each clause:
!define"!s.m"a-+ist-of-n.ms# ""!cond """"9!empt2A"a-+ist-of-n.ms#"...: """"9!consA"a-+ist-of-n.ms# """""..."!first"a-+ist-of-n.ms#"..."!rest"a-+ist-of-n.ms#"...:##

Finall$! we add the natural recursion o) s.m that re)lects the sel)2re)erence in the data de)inition:
!define"!s.m"a-+ist-of-n.ms# ""!cond """"9!empt2A"a-+ist-of-n.ms#"...: """"9else"..."!first"a-+ist-of-n.ms#"..."!s.m"!rest"a-+ist-ofn.ms##"...:##

The )inal template re)lects almost e+er$ aspect o) the data de)inition: the two clauses! the construction in the second clauses! and the sel)2re)erence o) the second clauses, The onl$ part o) the data de)inition that the )unction template does not re)lect is that the )irst item o) a constructed input is a number, -ow that we ha+e a template! let us de)ine the answers )or the cond2e8pression on a clause2b$2clause basis, In the )irst clause! the input is empt2! which means that the store has no in+entor$, 1e alread$ agreed that in this case the in+entor$ is worth nothing! which means the corresponding answer is %, In the second clause o) the template! we )ind two e8pressions: (, !first"a-+ist-of-n.ms#! which e8tracts the cost o) the )irst to$E and &, !s.m"!rest"a-+ist-of-n.ms##! which! according to the purpose statement o) s.m! computes the sum o) !rest"a-+ist-of-n.ms#,

From these two reminders o) what the e8pressions alread$ compute )or us! we see that the e8pression
!+"!first"a-+ist-of-n.ms#"!s.m"!rest"a-+ist-of-n.ms###

computes the answer in the second cond2clause, Here is the complete de)inition o) s.m:
!define"!s.m"a-+ist-of-n.ms# ""!cond """"9!empt2A"a-+ist-of-n.ms#"%: """"9else"!+"!first"a-+ist-of-n.ms#"!s.m"!rest"a-+ist-ofn.ms###:##

A comparison o) this de)inition with the template and the data de)inition shows that the step )rom the data de)inition to the template is the maFor step in the )unction de+elopment process, @nce we ha+e deri+ed the template )rom a solid understanding o) the set o) possible inputs! we can )ocus on the creati+e part: combining +alues, For simple e8amples! this step is eas$E )or others! it re?uires rigorous thin.ing, 1e will see in )uture sections that this relationship between the shape o) the data de)inition and the )unction is not a coincidence, De)ining the class o) data that a )unction consumes alwa$s determines to a large e8tent the shape o) the )unction, E ercise -<$<1< Ase DrScheme to test the de)inition o) s.m on the )ollowing sample lists o) numbers:
empt2" !cons"1.%%"empt2# !cons"17.%5"!cons"1.22"!cons"2.5,"empt2###

Compare the results with our speci)ications, Then appl$ s.m to the )ollowing e8amples:
empt2 !cons"2.5,"empt2# !cons"1.22"!cons"2.5,"empt2##

First determine what the result sho !d beE then use DrScheme to e+aluate the e8pressions, Solution E ercise -<$<2< De+elop the )unction how-man2-s2m8o+s! which consumes a list o) s$mbols and produces the number o) items in the list, De+elop the )unction how-man2-n.m8ers! which counts how man$ numbers are in a list o) numbers, How do how-man2-s2m8o+s and how-man2-n.m8ers di))erH Solution

E ercise -<$<!< De+elop the )unction do++ar-storeA! which consumes a list o) prices /numbers0 and chec.s whether all o) the prices are below 1, For e8ample! the )ollowing e8pressions should e+aluate to tr.e:
!do++ar-storeA"empt2# !not"!do++ar-storeA"!cons".75"!cons"1.,5"!cons".25"empt2##### !do++ar-storeA"!cons".15"!cons".%5"!cons".25"empt2####

=enerali*e the )unction so that it consumes a list o) prices /numbers0 and a threshold price /number0 and chec.s that all prices in the list are below the threshold, Solution E ercise -<$<#< De+elop the )unction chec--range1A! which consumes a list o) temperature measurements /represented as numbers0 and chec.s whether all measurements are between 7o2 and >7o2, =enerali*e the )unction to chec--rangeA! which consumes a list o) temperature measurements and a legal inter+al and chec.s whether all measurements are within the legal inter+al, Solution E ercise -<$<$< De+elop the )unction con0ert, It consumes a list o) digits and produces the corresponding number, The )irst digit is the least signi)icant! and so on, Also de+elop the )unction chec--g.ess-for-+ist, It implements a general +ersion o) the number2guessing game o) e8ercise 7,(,5, The )unction consumes a list o) digits! which represents the pla$erCs g.ess! and a number! which represents the randoml$ chosen and hidden number, Depending on how the con0erted digits relate to target! chec--g.ess-for-+ist produces one o) the )ollowing three answers: ';ooCma++! '3erfect! or ';ooLarge, The rest o) the game is implemented b$ guess.ss, To pla$ the game! use the teachpac. to guess.ss and e+aluate the e8pression
!g.ess-with-g.i-+ist"5"chec--g.ess-for-+ist#

after the )unctions ha+e been thoroughl$ de+eloped,

Solution

E ercise -<$<&< De+elop the )unction de+ta! which consumes two price lists! that is! lists o) numbers, The )irst represents the in+entor$ at the beginning o) a time period! the second one the in+entor$ at the end, The )unction outputs the di))erence in +alue, I) the +alue o) the in+entor$ has increased! the result is positi+eE i) the +alue has decreased! it is negati+e, Solution

E ercise -<$<(< De)ine the )unction a0erage-price, It consumes a list o) to$ prices and computes the a+erage price o) a to$, The a+erage is the total o) all prices di+ided b$ the number o) to$s, Iterati1e 0efinement: First de+elop a )unction that wor.s on non2empt$ lists, Then produce a chec.ed )unction /see section ;,70 that signals an error when the )unction is applied to an empt$ list, Solution E ercise -<$<)< De+elop the )unction draw-circ+es! which consumes a posn p and a list o) numbers, #ach number o) the list represents the radius o) some circle, The )unction draws concentric red circles around p on a can+as! using the operation drawcirc+e, Its result is tr.e! i) it can draw all o) themE otherwise an error has occurred and the )unction does not need to produce a +alue, Ase the teachpac. draw.ssE create the can+as with !start"3%%"3%%#, Recall that draw.ss pro+ides the structure de)inition )or posn /see section ;,(0, Solution The traditional names are car and cdr! but we will not use these nonsensical names,

&>

It is common that a data de)inition describes a class o) data that contains more than the intended elements, This limitation is inherent and is Fust one o) the man$ s$mptoms o) the limits o) computing,
5'

-umbers also seem to be arbitraril$ large, For ine8act numbers! this is an illusion, For precise integers! this is indeed the case! and we will discuss them later in this part,
5(

Section 1. /ore on Processing ,ists


The )unctions in section > consume lists that contain atomic data! especiall$ numbers! s$mbols! and booleans, But )unctions must also be able to produce such lists, Furthermore! the$ must be able to consume and produce lists that contain structures, 1e discuss these cases in this section! and we continue practicing the use o) the design recipe,

$8#$ +unctions that Produce Lists


Recall the )unction wage )rom section &,5:
66"wage":"n.m8er""-/""n.m8er 66"to"comp.te"the"tota+"wage"!at"X12"per"ho.r# 66"of"someone"who"wor-ed"for"h"ho.rs !define"!wage"h# ""!*"12"h##

The wage )unction consumes the number o) hours some emplo$ee wor.ed and produces the wee.l$ wage pa$ment, For simplicit$! we assume that all emplo$ees earn the same hourl$ rate! namel$! Q(&, A compan$! howe+er! isnCt interested in a )unction li.e wage! which computes the wage o) a single emplo$ee, Instead! it wants a )unction that computes the wages )or all o) its emplo$ees! especiall$ i) there are a lot o) them, Call this new )unction hours-/wages, It consumes a list that represents how man$ hours the emplo$ees o) the compan$ wor.ed and must produce a list o) the wee.l$ wages the$ earned, 1e can represent both the input and the output as Scheme lists o) numbers, Since we alread$ ha+e a data de)inition )or the inputs and outputs! we can immediatel$ start our )unction de+elopment:
66"hours-/wages":"+ist-of-n.m8ers""-/""+ist-of-n.m8ers 66"to"create"a"+ist"of"wee-+2"wages"from"a"+ist"of"wee-+2"ho.rs !a+on# !define"!hours-/wages"a+on#"...#

-e8t we need some e8amples o) inputs and the corresponding outputs:


empt2 !cons"2$"empt2# !cons"4%"!cons"2$"empt2## empt2 !cons"33 "empt2# !cons"4$%"!cons"33 "empt2##

The outputs are obtained b$ calculating the wage )or each item on the list to the le)t, =i+en that hours-/wages consumes the same class o) data as! sa$! the )unction s.m! and gi+en that the shape o) a )unction template depends onl$ on the shape o) the data de)inition! we can reuse the +ist-of-n.m8ers template:
!define"!hours-/wages"a+on# ""!cond """"9!empt2A"a+on#"...: """"9else"..."!first"a+on#"..."!hours-/wages"!rest"a+on##"...:##

Starting with this template! we can turn to the most creati+e step o) )unction de+elopment: the de)inition o) the )unction bod$, Following our recipe! we consider each cond2line in isolation! starting with the simpler case, First! assume !empt2A"a+on# is true! which means that the input is empt2, The answer in this case is empt2:
!define"!hours-/wages"a+on#

""!cond """"9!empt2A"a+on#"empt2: """"9else"..."!first"a+on#"..."!hours-/wages"!rest"a+on##"...:##

Second! assume that a+on was constructed )rom a number and a list o) numbers, The e8pressions in the second line remind us o) this assumption! and the recipe tells us that we should state e8plicitl$ what the$ compute: (, !first"a+on# $ields the )irst number on a+on! which is the )irst number o) hours wor.edE and &, !hours-/wages"!rest"a+on## reminds us that !rest"a+on# is a list and can be processed b$ the +er$ )unction we are de)ining, According to the purpose statement! the e8pression computes the list o) wages )or the rest o) the list o) hours! and we ma$ assume this relationship in our construction 22 e+en though the )unction is not $et completel$ de)ined, From here it is a short step to the complete )unction de)inition, Since we alread$ ha+e the list o) wages )or all but the )irst item o) a+on! the )unction must do two things to produce an output )or the entire list o) hours: (, Compute the wee.l$ wage )or the )irst number o) hours, &, Construct a list that represents all wee.l$ wages )or a+on! using the )irst wee.l$ wage and the list o) wee.l$ wages )or !rest"a+on#, For the )irst part! we reuse wage, For the second! we cons the two pieces o) in)ormation together into one list:
!cons"!wage"!first"a+on##"!hours-/wages"!rest"a+on###

And with that! we ha+e a complete )unction, It is shown in )igure &;, To )inish the design o) the )unction! we must still test it,

66"hours-/wages":"+ist-of-n.m8ers""-/""+ist-of-n.m8ers 66"to"create"a"+ist"of"wee-+2"wages"from"a"+ist"of"wee-+2"ho.rs !a+on# !define"!hours-/wages"a+on# ""!cond """"9!empt2A"a+on#"empt2: """"9else"!cons"!wage"!first"a+on##"!hours-/wages"!rest"a+on###:## 66"wage":"n.m8er""-/""n.m8er 66"to"comp.te"the"tota+"wage"!at"X12"per"ho.r# 66"of"someone"who"wor-ed"for"h"ho.rs !define"!wage"h#

/T (& h00 Figure 2(' Computing wee.l$ wages E ercise 1.<1<1< How do we ha+e to change the )unction in )igure &; i) we want to gi+e e+er$one a raise to Q(6H Solution E ercise 1.<1<2< -o emplo$ee could possibl$ wor. more than ('' hours per wee., To protect the compan$ against )raud! the )unction should chec. that no item o) the input list o) hours-/wages e8ceeds ('', I) one o) them does! the )unction should immediatel$ signal the error 1too"man2"ho.rs1, How do we ha+e to change the )unction in )igure &; i) we want to per)orm this basic realit$ chec.H Solution E ercise 1.<1<!< De+elop con0ert>7, The )unction con+erts a list o) Fahrenheit measurements to a list o) Celsius measurements, Solution E ercise 1.<1<#< De+elop the )unction con0ert-e.ro! which con+erts a list o) A,S, dollar amounts into a list o) euro amounts, Assume the e8change rate is (,&& euro )or each dollar, =enerali*e con0ert-e.ro to the )unction con0ert-e.ro-1! which consumes an e8change rate and a list o) dollar amounts and con+erts the latter into a list o) euro amounts, Solution E ercise 1.<1<$< De+elop the )unction e+iminate-e*p to eliminate e8pensi+e to$s, The )unction consumes a number! called .a! and a list o) to$ prices! called +otp! and produces a list o) all those prices in +otp that are below or e?ual to .a, For e8ample!5&

!e+iminate-e*p"1.%"!cons"2.,5"!cons".,5"!cons"1.%"!cons"5 empt2##### 66"e*pected"0a+.e:" !cons".,5"!cons"1.%"empt2##

Solution E ercise 1.<1<&< De+elop the )unction name-ro8ot! which consumes a list o) to$ descriptions /names0 and produces an e?ui+alent list o) more accurate descriptions, Speci)icall$! it replaces all occurrences o) 'ro8ot with 'r2d2 and otherwise retains the to$ descriptions in the same order, =enerali*e name-ro8ot to the )unction s.8stit.te, The new )unction consumes two s$mbols! called new and o+d! and a list o) s$mbols, It produces a new list o) s$mbols b$ substituting all occurrences o) o+d b$ new, For e8ample!
!s.8stit.te"'(ar8ie"'do++"!cons"'ro8ot"!cons"'do++"!cons"'dress empt2#### 66"e*pected"0a+.e:" !cons"'ro8ot"!cons"'(ar8ie"!cons"'dress"empt2###

Solution E ercise 1.<1<(< De+elop the )unction reca++ to eliminate speci)ic to$s )rom a list, The )unction consumes the name o) a to$! called t2! and a list o) names! called +on! and produces a list o) names that contains all components o) +on with the e8ception o) t2, For e8ample!
!reca++"'ro8ot"!cons"'ro8ot"!cons"'do++"!cons"'dress"empt2#### 66"e*pected"0a+.e:" !cons"'do++"!cons"'dress"empt2##

Solution E ercise 1.<1<)< De+elop ).adratic-roots! which sol+es ?uadratic e?uations: see e8ercises 6,6,6 and 7,(,6, The )unction accepts the coe))icients a! 8! and c, The computations it per)orms depend on the input: (, i) a O '! its output is 'degenerate, &, i) b& U 6 P a P c! the ?uadratic e?uation has no solutionE ).adratic-roots produces 'none in this case, 5, i) b& O 6 P a P c! the e?uation has one solution:

the solution is the answer, 6, i) b& S 6 P a P c! the e?uation has two solutions:

and

the result is a list o) two numbers: the )irst solution )ollowed b$ the second solution, Test the )unction with the e8amples )rom e8ercises 6,6,6 and 7,(,6, First decide the answer )or each e8ample! then determine it with DrScheme, Solution E ercise 1.<1<-< The cash registers at man$ grocer$ stores tal. to customers, The registerCs computer recei+es the number o) cents that the customer must pa$ and then builds a list with the )ollowing )i+e items: (, the dollar amountE &, the s$mbol 'do++ar i) the dollar amount is 1 and 'do++ars otherwiseE 5, the s$mbol 'andE 6, the cent amountE and 7, the s$mbol 'cent i) the cent amount is ( and 'cents otherwise, De+elop the )unction contro++er! which consumes a number and produces a list according to the abo+e description, For e8ample! i) the amount is Q(,'5! then the cash register e+aluates !contro++er"1%3#:
!contro++er"1%3# 66"e*pected"0a+.e:" !cons"1"!cons"'do++ar"!cons"'and"!cons"3"!cons"'cents"empt2#####

>int: Scheme pro+ides the arithmetic operations ).otient and remainder! which produce the ?uotient and remainder o) the e8pression nKm )or integers n and m! respecti+el$,

Sound Files @nce the controller returns the correct list )or amounts whose dollar and cent amounts are between ' and &'! test the controller with a computer that can spea., Set the teachpac. to sound.ss! which ma.es two operations a+ailable: spea--word and spea--+ist, The )irst accepts a s$mbol or a number! the second a list o) s$mbols and numbers, Both pronounce the s$mbols the$ consume, #+aluate the )ollowing e8pressions !spea--word"1#! !spea--+ist"!cons"1"!cons"'do++ar"empt2###! and !spea--+ist"!cons"'8ea.tif.+"!cons"'+ad2"empt2### to understand how the operations operate, Simple Challenge: The sound teachpac. contains onl$ the sounds )or the numbers % through 2% and 3%! 4%! 5%! %! 7%! $%! and ,%, Because o) this restriction! this challenge problem wor.s onl$ on amounts with cents and dollars between % to 2%, Implement a controller that deals with arbitrar$ amounts between ' and >>,>>, Solution

$8#" Lists that Contain Structures


The representation o) an in+entor$ as a list o) s$mbols or a list o) prices is nai+e, A sales cler. in a to$ store needs to .now not onl$ the name o) the to$! but also its price! and possibl$ other attributes li.e warehouse a+ailabilit$! deli+er$ time! or e+en a picture o) the item, Similarl$! representing the personnelCs wor. wee. as a list o) hours is a bad choice, #+en the printing o) a pa$chec. re?uires more in)ormation about the emplo$ee than the hours wor.ed per wee., Fortunatel$! the items o) lists do not ha+e to be atomic +alues, "ists ma$ contain whate+er +alues we want! especiall$ structures, "etCs tr$ to ma.e our to$ store in+entor$ )unctions more realistic, 1e start with the structure and the data de)inition o) a class o) in+entor$ records:
!define-struct"ir"!name"price##

An inventory-record /short: ir0 is a structure:


!ma-e-ir"s"n#

where s is a s$mbol and n is a /positi+e0 number, Most important! we can de)ine a class o) lists that represent in+entories much more realisticall$:

An inventory is either (, empt2 or &, !cons"ir"in0# where ir is an in+entor$ record and in0 is an in+entor$, 1hile the shape o) the list de)inition is the same as be)ore! its components are de)ined in a separate data de)inition, Since this is our )irst such data de)inition! we should ma.e up some e8amples be)ore we proceed, The simplest e8ample o) an in+entor$ is empt2, To create a larger in+entor$! we must create an in+entor$ record and cons it onto another in+entor$:
!cons"!ma-e-ir"'do++"17.,5# ""empt2#

From here! we can create $et a larger in+entor$ listing:


!cons"!ma-e-ir"'ro8ot"22.%5# ""!cons"!ma-e-ir"'do++"17.,5# """"empt2##

-ow we can adapt our in+entor$2processing )unctions, First loo. at s.m! the )unction that consumes an in+entor$ and produces its total +alue, Here is a restatement o) the basic in)ormation about the )unction:
66"s.m":"in0entor2""-/""n.m8er 66"to"comp.te"the"s.m"of"prices"on"an-in0 !define"!s.m"an-in0#"...#

For our three sample in+entories! the )unction should produce the )ollowing results: %! 17.,5! and 4%.%, Since the data de)inition o) in+entories is basicall$ that o) lists! we can again start )rom the template )or list2processing )unctions:
!define"!s.m"an-in0# ""!cond """"9!empt2A"an-in0#"...: """"9else"..."!first"an-in0#"..."!s.m"!rest"an-in0##"...:##

Following our recipe! the template onl$ re)lects the data de)inition o) the input! not that o) its constituents, There)ore the template )or s.m here is indistinguishable )rom that in section >,7,

For the de)inition o) the )unction bod$! we consider each cond2line in isolation, First! i) !empt2A"an-in0# is true! s.m is supposed to produce %, Hence the answer e8pression in the )irst cond2line is ob+iousl$ %,
!define"!s.m"an-in0# ""!cond """"9!empt2A"an-in0#"%:

Velse /I /ir2price /)irst an2in+00 /sum /rest an2in+000W00 Figure 2)' Computing the +alue o) an in+entor$ Second! i) !empt2A"an-in0# is )alse! in other words! i) s.m is applied to a constructed in+entor$! the recipe re?uires us to understand the purpose o) two e8pressions: (, !first"an-in0#! which e8tracts the )irst item o) the listE and &, !s.m"!rest"an-in0##! which e8tracts the rest o) an-in0 and then computes its cost with s.m, To compute the total cost o) the entire input an-in0 in the second case! we must determine the cost o) the )irst item, The cost o) the )irst item ma$ be obtained +ia the selector ir-price! which e8tracts the price )rom an in+entor$ record, -ow we Fust add the cost o) the )irst item and the cost o) the rest o) the in+entor$:
!+"!ir-price"!first"an-in0## """!s.m"!rest"an-in0###

The complete )unction de)inition is contained in )igure &<, E ercise 1.<2<1< Adapt the )unction contains-do++A so that it consumes in+entories instead o) lists o) s$mbols:
66"contains-do++A":"in0entor2""-/""8oo+ean 66"to"determine"whether"an-in0"contains"a"record"for"'do++ !define"!contains-do++A"an-in0#"...#

Also adapt the )unction containsA! which consumes a s$mbol and an in+entor$ and determines whether an in+entor$ record with this s$mbol occurs in the in+entor$:
66"containsA":"s2m8o+"in0entor2""-/""8oo+ean 66"to"determine"whether"in0entor2"contains"a"record"for"as2m8o+ !define"!containsA"as2m8o+"an-in0#"...#

Solution

Item Price

Image

robot &>,>7

robot &>,>7

robot &>,>7 Figure 2-' A table o) to$s E ercise 1.<2<2< Pro+ide a data de)inition and a structure de)inition )or an in+entor$ that includes pictures with each obFect, Show how to represent the in+entor$ listing in )igure &>,55 De+elop the )unction show-pict.re, The )unction consumes a s$mbol! the name o) a to$! and one o) the new in+entories, It produces the picture o) the named to$ or fa+se i) the desired item is not in the in+entor$, Pictures o) to$s are a+ailable on the 1eb, Solution E ercise 1.<2<!< De+elop the )unction price-of! which consumes the name o) a to$ and an in+entor$ and produces the to$Cs price, Solution E ercise 1.<2<#< A phone director$ combines names with phone numbers, De+elop a data de)inition )or phone records and directories, Asing this data de)inition de+elop the )unctions (, whose-n.m8er! which determines the name that goes with some gi+en phone number and phone director$! and

&, phone-n.m8er! which determines the phone number that goes with some gi+en name and phone director$,

Solution Suppose a business wishes to separate all those items that sell )or a dollar or less )rom all others, The goal might be to sell these items in a separate department o) the store, To per)orm this split! the business also needs a )unction that can e8tract these items )rom its in+entor$ listing! that is! a )unction that produces a list o) structures, "et us name the )unction e*tract1 because it creates an in+entor$ )rom all those in+entor$ records whose price item is less than or e?ual to 1.%%, The )unction consumes an in+entor$ and produces one with items o) appropriate prices, Thus the contract )or e*tract1 is eas$ to )ormulate:
66"e*tract1":"in0entor2""-/""in0entor2 66"to"create"an"in0entor2"from"an-in0"for"a++ 66"those"items"that"cost"+ess"than"X1 !define"!e*tract1"an-in0#"...#

1e can reuse our old in+entor$ e8amples to ma.e e8amples o) e*tract1Cs input2output relationship, An)ortunatel$! )or these three e8amples it must produce the empt$ in+entor$! because all prices are abo+e one dollar, For a more interesting input2output e8ample! we need an in+entor$ with more +ariet$:
!cons"!ma-e-ir"'dagger".,5# """"""!cons"!ma-e-ir"'(ar8ie"17.,5# """"""""""""!cons"!ma-e-ir"'-e2-chain".55# """"""""""""""""""!cons"!ma-e-ir"'ro8ot"22.%5# """"""""""""""""""""""""empt2####

@ut o) the )our items in this new in+entor$! two ha+e prices below one dollar, I) gi+en to e*tract1! we should get the result
!cons"!ma-e-ir"'dagger".,5# """"""!cons"!ma-e-ir"'-e2-chain".55# """"""""""""empt2##

The new listing enumerates the items in the same order as the original! but contains onl$ those items whose prices match our condition, The contract also implies that the template )or e*tract1 is identical to that o) s.m! e8cept )or a name change:
!define"!e*tract1"an-in0# ""!cond """"9!empt2A"an-in0#"...: """"9else"..."!first"an-in0#"..."!e*tract1"!rest"an-in0##"...:##

As alwa$s! the di))erence in outputs between s.m and e*tract1 does not a))ect the template deri+ation,
66"e*tract1":"in0entor2""-/""in0entor2 66"to"create"an"in0entor2"from"an-in0"for"a++ 66"those"items"that"cost"+ess"than"X1 !define"!e*tract1"an-in0# ""!cond """"9!empt2A"an-in0#"empt2: """"9else"!cond """"""""""""9!?&"!ir-price"!first"an-in0##"1.%%# """""""""""""!cons"!first"an-in0#"!e*tract1"!rest"an-in0###:

Velse /e8tract( /rest an2in+00W0W00 Figure !.' #8tracting dollar items )rom an in+entor$ For the de)inition o) the )unction bod$! we again anal$*e each case separatel$, First! i) !empt2A"an-in0# is true! then the answer is clearl$ empt2! because no item in an empt$ store costs less than one dollar, Second! i) the in+entor$ is not empt$! we )irst determine what the e8pressions in the matching cond2clause compute, Since e*tract1 is the )irst recursi+e )unction to produce a list o) structures! let us loo. at our interesting e8ample:
!cons"!ma-e-ir"'dagger".,5# """"""!cons"!ma-e-ir"'(ar8ie"17.,5# """"""""""""!cons"!ma-e-ir"'-e2-chain".55# """"""""""""""""""!cons"!ma-e-ir"'ro8ot"22.%5# """"""""""""""""""""""""empt2####

I) an-in0 stands )or this in+entor$!


!first"an-in0#"&"!ma-e-ir"'dagger".,5# !rest"an-in0#"&"!cons"!ma-e-ir"'(ar8ie"17.,5# """""""""""""""""""""!cons"!ma-e-ir"'-e2-chain".55# """""""""""""""""""""""""""!cons"!ma-e-ir"'ro8ot"22.%5# """""""""""""""""""""""""""""empt2###

Assuming e*tract1 wor.s correctl$! we also .now that


!e*tract1"!rest"an-in0##"&"!cons"!ma-e-ir"'-e2-chain".55# """""""""""""""""""""""""""""empt2#

In other words! the recursi+e application o) e*tract1 produces the appropriate selection )rom the rest o) an-in0! which is a list with a single in+entor$ record, To produce an appropriate in+entor$ )or all o) an-in0! we must decide what to do with the )irst item, Its price ma$ be more or less than one dollar! which suggests the )ollowing template )or the second answer:
..."!cond" """"""9!?&"!ir-price"!first"an-in0##"1.%%#"...: """"""9else"...:#"...

I) the )irst itemCs price is one dollar or less! it must be included in the )inal output and! according to our e8ample! should be the )irst item on the output, Translated into Scheme! the output should be a list whose )irst item is !first"an-in0# and the rest o) which is whate+er the recursion produces, I) the price is more than one dollar! the item should not be included, That is! the result should be whate+er the recursion produces )or the rest o) an-in0 and nothing else, The complete de)inition is displa$ed in )igure 5', E ercise 1.<2<$< De)ine the )unction e*tract/1! which consumes an in+entor$ and creates an in+entor$ )rom those records whose prices are abo+e one dollar, Solution E ercise 1.<2<&< De+elop a precise data de)inition )or in+entor$(! which are in+entor$ listings o) one2dollar stores, Asing the new data de)inition! the contract )or e*tract1 can be re)ined:
66"e*tract1":"in0entor2""-/""in0entor21 !define"!e*tract1"an-in0#"...#

Does the re)ined contract a))ect the de+elopment o) the )unction abo+eH

Solution

E ercise 1.<2<(< De+elop the )unction raise-prices! which consumes an in+entor$ and produces an in+entor$ in which all prices are raised b$ 7R, Solution E ercise 1.<2<)< Adapt the )unction reca++ )rom e8ercise (',(,; )or the new data de)inition o) in+entor$, The )unction consumes the name o) a to$ t2 and an in+entor$ and produces an in+entor$ that contains all items o) the input with the e8ception o) those labeled t2, Solution E ercise 1.<2<-< Adapt the )unction name-ro8ot )rom e8ercise (',(,9 )or the new data de)inition o) in+entor$, The )unction consumes an in+entor$ and produces an in+entor$ with more accurate names, Speci)icall$! it replaces all occurrences o) 'ro8ot with 'r2d3, =enerali*e name-ro8ot to the )unction s.8stit.te, The new )unction consumes two s$mbols! called new and o+d! and an in+entor$, It produces a new in+entor$ b$ substituting all occurrences o) o+d with new and lea+ing all others alone, Solution

$8#( E,tended E,ercise. /oving Pictures


In sections 9,9 and ;,6! we studied how to mo+e indi+idual shapes, A picture! howe+er! isnCt Fust a single shape but a whole collection o) them, Considering that we ha+e to draw! translate! and clear pictures! and that we ma$ wish to change a picture or manage se+eral pictures at the same time! it is best to collect all o) the parts o) a picture into a

single piece o) data, Because pictures ma$ consist o) a +ar$ing number o) items! a list representation )or pictures naturall$ suggests itsel), E ercise 1.<!<1< Pro+ide a data de)inition that describes the class o) lists o) shapes, The class o) shapes was de)ined in e8ercise ;,6,(, Create a sample list that represents the )ace o) )igure (',5,9 and name it >'75, Its basic dimensions are gathered in the )ollowing table: shape circle rectangle rectangle rectangle rectangle position si*e/s0 color /7'!7'0 6' red /5'!&'0 7 Y 7 blue /97!&'0 7 Y 7 blue /6'!;70 &' Y (' red /67!570 (' Y 5' blue

The table assumes a can+as o) si*e 5'' b$ ('', De+elop the template f.n-for-+osh! which outlines )unctions that consume a +istof-shapes, Solution E ercise 1.<!<2< Ase the template f.n-for-+osh to de+elop the )unction draw-+osh, It consumes a +ist-of-shapes! draws each item on the list! and returns tr.e, Remember to use !start"n"m# to create the can+as be)ore the )unction is used, Solution E ercise 1.<!<!< Ase the template f.n-for-+osh to de+elop trans+ate-+osh, The )unction consumes a +ist-of-shapes and a number de+ta, The result is a list o) shapes where each o) them has been mo+ed b$ de+ta pi8els in the + direction, The function has no effect on the can1as< Solution E ercise 1.<!<#< Ase the template f.n-for-+osh to de+elop c+ear-+osh, The )unction consumes a +ist-of-shapes! erases each item on the list )rom the can+as! and returns tr.e, Solution E ercise 1.<!<$< De+elop the )unction draw-and-c+ear-pict.re, It consumes a pict.re, Its e))ect is to draw the picture! sleep )or a while! and to clear the picture, Solution E ercise 1.<!<&< De+elop the )unction mo0e-pict.re, It consumes a number /de+ta0 and a pict.re, It draws the picture! sleeps )or a while! clears the picture and then produces a translated +ersion, The result should be mo+ed b$ de+ta pi8els,

Test the )unction with e8pressions li.e these:


!start"5%%"1%%# !draw-+osh ""!mo0e-pict.re"-5" """"!mo0e-pict.re"23 """"""!mo0e-pict.re"1%">'75#### !stop#"

This mo+es >'75 /see e8ercise (',5,(0 b$ 1%! 23! and -5 pi8els in the + direction, Solution 1hen the )unction is )ull$ tested! use the teachpac. arrow.ss and e+aluate the e8pression:
!start"5%%"1%%# !contro+-+eft-right">'75"1%%"mo0e-pict.re"draw-+osh#

The last one creates a graphical user inter)ace that permits users to mo+e the shape >'75 b$ clic.ing on arrows, The shape then mo+es in increments o) 1%% /right0 and -1%% /le)t0 pi8els, The teachpac. also pro+ides arrow controls )or other directions, Ase them to de+elop other mo+ing pictures, Since we donCt .now $et how to compare two lists with a )unction! we use the old st$le o) speci)$ing e8amples and tests,
5&

55

Than.s to Mr, John Clements )or drawing these pictures,

Section 11 Natural Numbers


The onl$ sel)2re)erential data de)initions we ha+e seen thus )ar in+ol+ed cons and lists o) arbitrar$ length, 1e needed such data de)initions because the classes o) lists that we wanted to process were o) arbitrar$ si*e, -atural numbers are another class o) data whose elements are o) arbitrar$ si*eE a)ter all! there is no limit on how large a natural number can be! and! at least in principle! a )unction should be able to process them all, In this section! we stud$ how to describe natural numbers with sel)2re)erential data de)initions and how to de+elop )unctions that process natural numbers in a s$stematic )ashion, Since such )unctions come in man$ )la+ors! we stud$ se+eral di))erent )la+ors o) de)initions,

$$#$ Defining %atural %um&ers


People normall$ introduce natural numbers +ia enumeration: %! 1! 2! etc,56 The abbre+iation DDetc,CC at the end sa$s that the series continues in this manner, Mathematicians and mathematics teachers o)ten use dots )or the same purpose, For us! howe+er! neither the DDetc,CC nor the dots is good enough! i) we wish to design )unctions on natural numbers s$stematicall$, So! the ?uestion is what it means to write down DDetc,!CC or put di))erentl$! what a complete! sel)2contained description o) the natural numbers is, The onl$ wa$ to remo+e the in)ormal DDetc,CC )rom the enumeration is to describe the collection o) numbers with a sel)2re)erential description, Here is a )irst attempt: ' is a natural number, I) n is a natural number! then one more than n is one! too, 1hile this description is still not ?uite rigorous!57 it is a good starting point )or a Scheme2st$le data description: A nat ra!-n mber is either (, % or &, !add1"n# i) n is a natural number,

The operation add1 adds 1 to a natural number, @) course! we could use !+"..."1# but add1 stands out and signals DDnatural number!CC as opposed to arbitrar$ number! to the reader o) a data de)inition and a )unction, Although we are )amiliar with natural numbers )rom school! it is instructi+e to construct e8amples )rom the data de)inition, Clearl$!
%

is the )irst natural number! so


!add1"%#

is the ne8t one, From here! it is eas$ to see the pattern:


!add1"!add1"%## !add1"!add1"!add1"%### !add1"!add1"!add1"!add1"%####

The e8amples should remind us o) the lists construction process, 1e built lists b$ starting with empt2 and b$ constructing on more items, -ow we build natural natural numbers b$ starting with % and b$ adding on 1, In addition! natural numbers come with centur$2old abbre+iations, For e8ample! !add1"%# is abbre+iated as 1! !add1"!add1 %## as 2! and so on, A )unction on natural numbers must e8tract the number that went into the construction o) a positi+e natural number Fust li.e a )unction on lists must e8tract the list that went into a constructed list, The operation that per)orms this DDe8tractionCC is called s.81, It satis)ies the law
!s.81"!add1"n##"&"n"

Fust as the rest operation satis)ies the law


!rest"!cons"a-0a+.e"a-+ist##"&"a-+ist

@) course! !-"n"1# would also wor.! but s.81 stands out and signals that the )unction processes natural numbers,

$$#" Processing %atural %um&ers of

r&itrary Si9e

"et us de+elop the )unction he++os, It consumes a natural number n and produces a list o) n copies o) 'he++o, 1e can write the contract )or this )unction:
66"he++os":"N""-/""+ist-of-s2m8o+s 66"to"create"a"+ist"of"n"copies"of"'he++o !define"!he++os"n#"...#

And we can ma.e up e8amples:

!he++os"%#" 66"e*pected"0a+.e:" empt2 !he++os"2# 66"e*pected"0a+.e:" !cons"'he++o"!cons"'he++o"empt2##

The design o) a template )or he++os )ollows the design recipe )or sel)2re)erential data de)initions, 1e immediatel$ see that he++os is a conditional )unction! that its cond2 e8pression has two clauses! and that the )irst clause must distinguish % )rom other possible inputs:
!define"!he++os"n# ""!cond """"9!@eroA"n#"...: """"9else"...:##

Furthermore! the data de)inition sa$s that % is an atomic +alue! and e+er$ other natural number is a compound +alue that DDcontainsCC the predecessor to which 1 was added, Hence! i) n is not %! we subtract 1 )rom n, The result is also a natural number! so according to the design recipe we wrap the e8pression with !he++os"...#:
!define"!he++os"n# ""!cond """"9!@eroA"n#"...: """"9else"..."!he++os"!s.81"n##"...":##

-ow we ha+e e8ploited e+er$ hint in the data de)inition and are read$ to proceed with the de)inition, Assume !@eroA"n# e+aluates to true, Then the answer must be empt2! as the e8amples illustrate, So assume the input is greater than %, For concreteness! let us sa$ it is 2, According to the suggestion in the template! he++os should use !he++os"1# to compute a part o) the answer, The purpose statement speci)ies that !he++os"1# produces !cons 'he++o"empt2#! a list with one 'he++o, In general! !he++os"!s.81"n## produces a list that contains n - ( occurrences o) 'he++o, Clearl$! to produce a list with n occurrences! we must cons another 'he++o onto this list:
!define"!he++os"n# ""!cond """"9!@eroA"n#"empt2: """"9else"!cons"'he++o"!he++os"!s.81"n###:##

As usual! the )inal de)inition is Fust the template with a )ew e8tras, "etCs test he++os with some hand2e+aluations:
""!he++os"%# &"!cond """"9!@eroA"%#"empt2: """"9else"!cons"'he++o"!he++os"!s.81"%###:# &"!cond

""""9tr.e"empt2: """"9else"!cons"'he++o"!he++os"!s.81"%###:# &"empt2

It con)irms that he++os wor.s properl$ )or the )irst e8ample, Here is another e8ample:
""!he++os"1# &"!cond """"9!@eroA"1#"empt2: """"9else"!cons"'he++o"!he++os"!s.81"1###:# &"!cond """"9fa+se"empt2: """"9else"!cons"'he++o"!he++os"!s.81"1###:# &"!cons"'he++o"!he++os"!s.81"1### &"!cons"'he++o"! """ he++os"" " %" #" # &"!cons"'he++o"empt2#

For the last step in the calculation! we can e8ploit that we alread$ .now that !he++os %# e+aluates to empt2 and replace the /underlined0 e8pression with its result, The last hand2e+aluation shows that the )unction wor.s )or the second e8ample:
""!he++os"2# &"!cond """"9!@eroA"2#"empt2: """"9else"!cons"'he++o"!he++os"!s.81"2###:# &"!cond """"9fa+se"empt2: """"9else"!cons"'he++o"!he++os"!s.81"2###:# &"!cons"'he++o"!he++os"!s.81"2### &"!cons"'he++o"! """ he++os"" " 1" #" # &"!cons"'he++o"!cons"'he++o"empt2##

1e can again e8ploit what we .now about !he++os"1#! which greatl$ shortens the hand2e+aluation, E ercise 11<2<1< =enerali*e he++os to repeat! which consumes a natural number n and a s$mbol and produces a list with n occurrences o) the s$mbol, Solution E ercise 11<2<2< De+elop the )unction ta8.+ate-f! which tabulates the +alues o)

66"f":"n.m8er""-/""n.m8er !define"!f"*# ""!+"!*"3"!*"*"*##" """""!+"!*"- "*# """"""""-1###

)or some natural numbers, Speci)icall$! it consumes a natural number n and produces a list o) n posns, The )irst one combines n with !f"n#! the second one n-1 with !f"n-1#! etc, Solution E ercise 11<2<!< De+elop app+2-n, The )unction consumes a natural number! n, It applies the )unction mo0e )rom e8ercise (',5,9 n times to >'75! the list o) shapes )rom e8ercise (',5,(, #ach application should translate the shape b$ one pi8el, The purpose o) the )unction is to simulate a continuousl$ mo+ing shape on a can+as! the last missing piece o) the e8tended e8ercise (',5, Solution E ercise 11<2<#< "ists ma$ contain lists that contain lists and so on, Here is a data de)inition that ta.es this idea to an e8treme: A deep-!ist is either (, s where s is some s$mbol or &, !cons"d+"empt2#! where d+ is a deep list, De+elop the )unction depth! which consumes a deep list and determines how man$ times cons was used to construct it, De+elop the )unction ma-e-deep! which consumes a s$mbol s and a natural number and produces a deep list containing s and constructed with n conses, Solution

$$#( E,tended E,ercise. Creating Lists2 Testing +unctions


1e o)ten encounter situations where we would li.e to create lists o) data that in+ol+e numbers, For e8ample! we ma$ wish to create large lists o) numbers to test a )unction li.e e*tract1 in section (',& on large lists instead o) hand2coded small ones, Sometimes we would li.e to +isuali*e randoml$ pic.ed data, 1e can create such )unctions using recursion on natural numbers and a random number generator, E ercise 11<!<1< Scheme pro+ides the operation random, It consumes a natural number n greater than (! and produces a random integer between % and n"-"1:

66"random":""N""-/""N 66"to"comp.te"a"nat.ra+"n.m8er"8etween"%"and"n-1 !define"!random"n#"...#

Two successi+e uses o) !random"n# ma$ produce two distinct results, -ow consider the )ollowing de)inition:
66"random-n-m":"integer"integer""-/""integer 66"..." 66"'ss.me:"n"?"m !define"!random-n-m"n"m# ""!+"!random"!-"m"n##"n##

Formulate a succinct and precise purpose statement )or random-n-m, Ase a number line with an inter+al to e8plain the result o) !random"n#, Ase a s$mbolic e+aluation to support $our e8planation, Solution E ercise 11<!<2< De+elop the )unction tie-d2ed, It consumes a natural number and produces a list o) that man$ numbers! each randoml$ chosen in the range )rom 2% and 12%, Ase tie-d2ed to appl$ draw-circ+es )rom e8ercise >,7,<, Solution E ercise 11<!<!< De+elop the )unction create-temps, It consumes a natural number n and two integers! called +ow and high, It produces a list o) n integers that are between +ow and high, Ase create-temps to test chec--range )rom e8ercise >,7,6, Finall$! discuss the )ollowing ?uestions, Can we simpl$ )eed the result o) createtemps into chec--range or do we need to .now the list that create-temps producedH Are there +alues )or +ow and high such that we donCt need to .now the result o) create-temps and $et we can predict the result o) the testH 1hich )unction tests whichH 1hat does this tell us about testing with automaticall$ generated test dataH Solution E ercise 11<!<#< De+elop the )unction create-prices! which consumes a natural number and produces a list with a corresponding number o) prices between Q,(' and Q(','' with increments o) a dime, Ase create-prices to test do++ar-storeA )rom e8ercise >,7,5,

>int' How man$ dimes are there between Q,(' and Q(',''H

Solution

E ercise 11<!<$< De+elop a program that +isuali*es a student riot, In preparation o) a student riot! a small group o) students meets to ma.e paint2)illed balloons, The t$pical riot uses 'red onl$, Then! on the e+ening o) the riot! the students enter a uni+ersit$Cs progressi+e theater with the balloons and throw them all o+er the seats, The programCs onl$ input should be a natural number! which represents the number o) balloons thrown, The +isuali*ation should use a can+as that contains a blac. grid and the positions o) the balls:

Assume a random distribution o) the balls o+er the theaterCs seats, #ach bo8 in the grid represents a seat, Con)igure the program so the change o) one +ariable de)inition changes the number o) columns in the grid and a change to another changes the number o) rows, >int' De+elop au8iliar$ )unctions that draw some gi+en number o) lines in the +ertical and the hori*ontal direction, Solution

$$#)

lternative Data Definitions for %atural %um&ers

Asing the abo+e! standard data de)inition )or natural numbers ma.es it eas$ to de+elop all .inds o) )unctions on numbers, Consider! )or e8ample! a )unction that multiplies the )irst n numbers, Put di))erentl$! it consumes a natural number n and multiplies all numbers between % /e8clusi+e0 and n /inclusi+e0, The )unction is called )actorial and has the mathematical notation D, Its contract is eas$ to )ormulate:
66"D":"N""-/""N 66"to"comp.te"n""B""!n"-"1#""B""...""B""2""B""1 !define"!D"n#"...#

It consumes a natural number and produces one, Speci)$ing its input2output relationship is a bit more tric.$, 1e .now! o) course! what the product o) 1! 2! and 3 is! so we should ha+e
!&"!D"3# """ # and<"simi+ar+2<" !&"!D"1%# """3 2$$%%#

The real ?uestion is what to do with the input %, According to the in)ormal description o) the tas.! D is supposed to produce the product o) all numbers between % /e8clusi+e0 and n /inclusi+e0! the argument, Since n is %! this re?uest is rather strange because there are no numbers between % /e8clusi+e0 and % /inclusi+e0, 1e sol+e the problem b$ )ollowing mathematical con+ention and set that !D"%# e+aluates to 1, From here! the rest is straight)orward, The template )or D is clearl$ that o) a natural number processing )unction:
!define"!D"n# ""!cond """"9!@eroA"n#"...: """"9else"..."!D"!s.81"n##"...:##

The answer in the )irst cond2clause is gi+en: 1, In the second clause! the recursion produces the product o) the )irst n"-"1 numbers, To get the product o) the )irst n numbers! we Fust need to multipl$ the /+alue o) the0 recursion b$ n, Figure 5( contains the complete de)inition o) D, E ercise 11<#<1< Determine the +alue o) !D"2# b$ hand and with DrScheme, Also test D with 1%! 1%%! and 1%%%, Note: The results o) these e8pressions are large numbers! well be$ond the nati+e capacities o) man$ other programming languages, Solution -ow suppose we wish to design the )unction prod.ct-from-2%! which computes the product )rom 2% /e8clusi+e0 to some number n /inclusi+e0 that is greater or e?ual to 2%, 1e ha+e se+eral choices here, First! we could de)ine a )unction that computes !D"n# and !D"2%# and di+ides the )ormer b$ the latter, A simple mathematical argument shows that this approach indeed $ields the product o) all numbers between 2% /e8clusi+e0 and n /inclusi+e0:

E ercise 11<#<2< Ase the idea to de)ine prod.ct! a )unction that consumes two natural numbers! n and m! with m"/"n! and that produces the product o) the numbers between n /e8clusi+e0 and m /inclusi+e0, Solution Second! we can )ollow our design recipe! starting with a precise characteri*ation o) the )unctionCs input, @b+iousl$! the inputs belong to the natural numbers! but we .now more than that, It belongs to the )ollowing collection o) numbers: 2%! 21! 22! ..., B$ now we .now how to describe such a set precisel$ with a data de)inition: A nat ra! n mber [>= 20] is either

(, 2% or &, !add1"n# i) n is a natural number 9/&"2%:, -otation: In contracts! we use N"9/&"2%: instead o) DDnatural numbers 9/&"2%:,CC Asing the new data de)inition! we can )ormulate a contract )or prod.ct-from-2%:
66"prod.ct-from-2%:"N"9/&"2%:""-/""N 66"to"comp.te"n""B""!n"-"1#""B""...""B""21""B""1 !define"!prod.ct-from-2%"n-a8o0e-2%#"...#

Here is a )irst e8ample )or prod.ct-from-2%Cs input2output speci)ication:


!&"!prod.ct-from-2%"21# """21#

Since the )unction multiplies all numbers between 2% /e8clusi+el$0 and its input! !prod.ct-from-2%"21# must produce 21! which is the onl$ number in the inter+al, Similarl$!
!&"!prod.ct-from-2%"22# """4 2#

)or the same reason, Finall$! we again )ollow mathematical con+ention and agree that
!&"!prod.ct-from-2%"2%# """1#

The template )or prod.ct-from-2% is a straight)orward adaptation o) the template )or D! or an$ natural number2processing )unction:
!define"!prod.ct-from-2%"n-a8o0e-2%# ""!cond """"9!&"n-a8o0e-2%"2%#"...: """"9else"..."!prod.ct-from-2%"!s.81"n-a8o0e-2%##"...:##

The input n-a8o0e-2% is either 2% or larger, I) it is 2%! it does not ha+e an$ components according to the data de)inition, @therwise! it is the result o) adding 1 to a natural number 9/&"2%:! and we can reco+er this DDcomponentCC b$ subtracting 1, The +alue o) this selector e8pression belongs to the same class o) data as the input and is thus a candidate )or natural recursion, Completing the template is e?uall$ straight)orward, As speci)ied! the result o) !prod.ct-from-2%"2%# is 1! which determines the answer )or the )irst cond2clause, @therwise! !prod.ct-from-2%"!s.81"n-a8o0e-2%## alread$ produces the product o) all the numbers between 2% /e8clusi+e0 and n-a8o0e-2%"-"1, The onl$ number not included in this range is n-a8o0e-2%, Hence !*"n-a8o0e-2%"!prod.ct-from-2%

is the correct answer in the second clause, Figure 5( contains the complete de)inition o) prod.ct-from-2%,
!s.81"n-a8o0e-2%###

E ercise 11<#<!< De+elop prod.ct-from-min.s-11, The )unction consumes an integer n greater or e?ual to -11 and produces the product o) all the integers between -11 /e8clusi+e0 and n /inclusi+e0, Solution E ercise 11<#<#< In e8ercise ((,&,&! we de+eloped a )unction that tabulates some mathematical )unction f )or an inter+al o) the shape /'!nW, De+elop the )unction ta8.+ate-f2%! which tabulates the +alues o) f )or natural numbers greater than 2%, Speci)icall$! the )unction consumes a natural number n greater or e?ual to 2% and produces a list o) posns! each o) which has the shape !ma-e-posn"n !f"n## )or some n between 2% /e8clusi+e0 and n /inclusi+e0, Solution
66"D":"N""-/""N 66"to"comp.te"n""B""!n"-"1#""B""...""B""2""B""1 !define"!D"n# ""!cond """"9!@eroA"n#"1: """"9else"!*"n"!D"!s.81"n###:## 66"prod.ct-from-2%:"N"9/&"2%:""-/""N 66"to"comp.te"n""B""!n"-"1#""B""...""B""21""B""1 !define"!prod.ct-from-2%"n-a8o0e-2%# ""!cond """"9!&"n-a8o0e-2%"2%#"1: """"9else"!*"n-a8o0e-2%"!prod.ct-from-2%"!s.81"n-a8o0e-2%###:## 66"prod.ct:"N9+imit:"N9/&"+imit:""-/""N 66"to"comp.te"n""B""!n"-"1#""B""...""B""!limit"+"1#""B""1 !define"!prod.ct"+imit"n# ""!cond """"9!&"n"+imit#"1:

Velse /T n /product limit /sub( n000W00 Figure !1' Computing )actorial! product2)rom2&'! and product A comparison o) D and prod.ct-from-2% suggests the natural ?uestion o) how to design a )unction that multiplies a!! natural numbers in some range, Roughl$ spea.ing! prod.ct is li.e prod.ct-from-2% e8cept that the limit is not a part o) the )unction de)inition, Instead! it is another input! which suggests the )ollowing contract:
66"prod.ct:"N"N""-/""N 66""to"comp.te"n""B""!n"-"1#""B""...""B""!limit"+"1#""B""1 !define"!prod.ct"+imit"n#"...#

The intention is that prod.ct! li.e prod.ct-from-2%! computes the product )rom +imit /e8clusi+e0 to some number n /inclusi+e0 that is greater or e?ual to +imit,

An)ortunatel$! prod.ctCs contract! in contrast with prod.ct-from-2%Cs! is rather imprecise, In particular! it does not describe the collection o) numbers that prod.ct consumes as the second input, =i+en its )irst input! +imit! we .now that the second input belongs to +imit! !add1"+imit#! !add1"!add1"+imit##! etc, 1hile it is eas$ to enumerate the possible second inputs! it also shows that the description o) the collection depends on the first inp t 22 an unusal situation that we ha+e not encountered be)ore, Still! i) we assume limit is some number! the data description )or the second input is nearl$ ob+ious: "et +imit be a natural number, A nat ra! n mber [>= limit] /N9/&+imit:0 is either (, +imit or &, !add1"n# i) n is a natural number 9/&"+imit:, In other words! the data de)inition is li.e that )or natural numbers 9/&"+imit: with 2% replaced b$ a +ariable +imit, @) course! in high school! we re)er to N9/&%: as the natural numbers! and N9/&1: as the positi+e integers, 1ith this new data de)inition! we speci)$ the contract )or prod.ct as )ollows:
66"prod.ct:"N9+imit:"N"9/&"+imit:""-/""N 66""to"comp.te"n""B""!n"-"1#""B""...""B""!limit"+"1#""B""1 !define"!prod.ct"+imit"n#"...#

That is! we name the )irst input! a natural number! with the notation 9+imit: and speci)$ the second input using the name )or the )irst one, The rest o) the program de+elopment is straight)orward, It is basicall$ the same as that )or prod.ct-from-2% with 2% replaced b$ +imit throughout, The onl$ modi)ication concerns the natural recusion in the )unction template, Since the )unction consumes a +imit and a N"9/&"+imit:! the template must contain an application o) prod.ct to +imit and !s.81"n#:
!define"!prod.ct"+imit"n# ""!cond """"9!&"n"+imit#"...: """"9else"..."!prod.ct"+imit"!s.81"n##"...:##

@therwise things remain the same, The )ull )unction de)inition is contained in )igure 5(,

E ercise 11<#<$< In e8ercises ((,&,& and ((,6,6! we de+eloped )unctions that tabulate f )rom some natural number or natural number 9/&"2%: down to % or 2% /e8clusi+e0! respecti+el$, De+elop the )unction ta8.+ate-f-+im! which tabulates the +alues o) f in an analogous manner )rom some natural number n down to some other natural number +imit, Solution E ercise 11<#<&< In e8ercises ((,&,&! ((,6,6! and ((,6,7! we de+eloped )unctions that tabulate the mathematical )unction f in +arious ranges, In both cases! the )inal )unction produced a list o) posns that was ordered in descending order, That is! an e8pression li.e !ta8.+ate-f"3# $ields the list
!cons"!ma-e-posn"3"2.4# ""!cons"!ma-e-posn"2"3.4# """"!cons"!ma-e-posn"1"3. # """"""!cons"!ma-e-posn"%"3.%# """"""""empt2####

I) we pre)er a list o) posns in ascending order! we must loo. at a di))erent data collection! natural numbers up to a certain point in the chain: A nat ra! n mber [<= 20] /N9?&2%:0 is either (, 2% or &, !s.81"n# i) n is a natural number 9?&"2%:, @) course! in high school! we re)er to N9?&-1: as the negati+e integers, De+elop the )unction
66"ta8.+ate-f-.p-to-2%":"N"9?&"2%:""-/""N !define"!ta8.+ate-f-.p-to-2%"n-8e+ow-2%#"...#

which tabulates the +alues o) f )or natural numbers less than 2%, Speci)icall$! it consumes a natural number n less than or e?ual to 2% and produces a list o) posns! each o) which has the shape !ma-e-posn"n"!f"n## )or some n between % and n /inclusi+el$0, Solution E ercise 11<#<(< De+elop the )unction is-not-di0isi8+e-82?&i, It consumes a natural number 9/&"1:! i! and a natural number m! with i"?"m, I) m is not di+isible b$

an$ number between 1 /e8clusi+e0 and i /inclusi+e0! the )unction produces tr.eE otherwise! its output is fa+se, Ase is-not-di0isi8+e-82?&i to de)ine primeA! which consumes a natural number and determines whether or not it is prime, Solution

$$#* /ore on the %ature of %atural %um&ers


The natural numbers are a small subset o) SchemeCs numbers! not all o) them, Hence the )unction template abo+e cannot be used )or processing arbitrar$ numbers! in particular! ine8act numbers, Still! the template is a good starting point )or )unctions whose de)initions in+ol+e both natural numbers and other Scheme numbers, To illustrate this point! let us design the )unction add-to-pi! which consumes a natural number n and produces n"+"3.14 without using +, Following the design recipe! we start with
66"add-to-pi":"N""-/""n.m8er 66"to"comp.te"n"+"3.14"witho.t".sing"+ !define"!add-to-pi"n#"...#

Another eas$ step is to determine the output )or a )ew sample inputs:
!&"!add-to-pi"%#"3.14# !&"!add-to-pi"2#"5.14# !&"!add-to-pi" #",.14#

The di))erence between he++osCs contract /see e8ercise ((,&,(0 and that o) add-to-pi is the output! but as we ha+e seen this does not a))ect the template design, 1e obtain the template )or add-to-pi b$ renaming he++os appropriatel$:
!define"!add-to-pi"n# ""!cond """"9!@eroA"n#"...: """"9else"..."!add-to-pi"!s.81"n##"...":###

In combination with the e8amples! the template immediatel$ suggests how to complete the )unction, I) the input is %! add-to-piCs answer is 3.14, @therwise! !add-to-pi !s.81"n## produces !-"n"1#"+"3.14E since the correct answer is 1 more than this +alue! the answer e8pression in the second cond2line is !add1"!add-to-pi"!s.81 n###, Figure 5& contains the complete )unction de)inition, E ercise 11<$<1< De)ine add! which consumes two natural numbers! n and *! and produces n"+"* without using SchemeCs +, Solution E ercise 11<$<2< De+elop the )unction m.+tip+2-82-pi! which consumes a natural number and multiplies it b$ 3.14 without using *, For e8ample!

!&"!m.+tip+2-82-pi"%#"%# !&"!m.+tip+2-82-pi"2#" .2$# !&"!m.+tip+2-82-pi"3#",.42#

De)ine m.+tip+2! which consumes two natural numbers! n and *! and produces n"*"* without using SchemeCs *, #liminate + )rom this de)inition! too, >int' Recall that multipl$ing * b$ n means adding * to itsel) n times, Solution

E ercise 11<$<!< De+elop the )unction e*ponent! which consumes a natural number n and a number * and computes

#liminate * )rom this de)inition! too, >int' Recall that e8ponentiating * b$ n means multipl$ing * with itsel) n times, Solution E ercise 11<$<#< Deep lists /see e8ercise ((,&,60 are another representation )or natural numbers, Show how to represent %! 3! and $, De+elop the )unction addDL! which consumes two deep lists! representing the natural numbers n and m! and produces a deep list representing n"+"m, Solution
66"add-to-pi":"N""-/""n.m8er 66"to"comp.te"n"+"3.14"witho.t".sing"+ !define"!add-to-pi"n# ""!cond """"9!@eroA"n#"3.14:

Velse /add( /add2to2pi /sub( n000W00 Figure !2' Adding a natural number to pi

It is important to start counting at ' so that we can use the natural numbers )or counting the number o) items on a list or the members o) a )amil$ tree,
56

57

For that! we need to de)er to a course on mathematical sets,

Section 12 Composing Functions, 0e1isited +gain


In section 5 we said that programs were collections o) )unction de)initions and possibl$ some +ariable de)initions! too, To guide the di+ision o) labor among )unctions! we also introduced a rough guideline: Formulate au8iliar$ )unction de)initions )or e+er$ dependenc$ between ?uantities in the problem statement, So )ar the guideline has been reasonabl$ e))ecti+e! but it is now time to ta.e a second loo. at it and to )ormulate some additional guidance concerning au8iliar$ )unctions, In the )irst subsection! we re)ine our original guideline concerning au8iliar$ programs, The suggestions mostl$ put into words the e8periences that we made with the e8ercises, The second and third one illustrate two o) the ideas in more depthE the last one is an e8tended e8ercise,

$"#$ Designing Comple, Programs


1hen we de+elop a program! we ma$ hope to implement it with a single )unction de)inition but we should alwa$s be prepared to write au8iliar$ )unctions, In particular! i) the problem statement mentions se+eral dependencies! it is natural to e8press each o) them as a )unction, @thers who read the problem statement and the program can )ollow our reasoning more easil$ that wa$, The mo+ie2theater e8ample in section 5,( is a good e8ample )or this st$le o) de+elopment, @therwise! we should )ollow the design recipe and start with a thorough anal$sis o) the input and output data, Asing the data anal$sis we should design a template and attempt to re)ine the template into a complete )unction de)inition, Turning a template into a complete )unction de)inition means combining the +alues o) the templateCs sube8pressions into the )inal answer, As we do so! we might encounter se+eral situations: (, I) the )ormulation o) an answer re?uires a case anal$sis o) the a+ailable +alues! use a cond2e8pression, &, I) a computation re?uires .nowledge o) a particular domain o) application! )or e8ample! drawing on /computer0 can+ases! accounting! music! or science! use an au8iliar$ )unction,

5, I) a computation must process a list! a natural number! or some other piece o) data o) arbitrar$ si*e! use an au8iliar$ )unction, 6, I) the natural )ormulation o) the )unction isnCt ?uite what we want! it is most li.el$ a generali*ation o) our target, In this case! the main )unction is a short de)inition that de)ers the computation to the generali*ed au8iliar$ program, The last two criteria are situations that we ha+enCt discussed $et, The )ollowing two subsections illustrate them with e8amples, A)ter we determine the need )or an au8iliar$ )unction! we should add a contract! a header! and a purpose statement to a 1ISH "IST o) )unctions,59

=uideline on 1ish "ists


Maintain a list o) )unctions that must be de+eloped to complete a program, De+elop each )unction according to a design recipe, Be)ore we put a )unction on the wish list! we must chec. whether something li.e the )unction alread$ e8ists or is alread$ on the wish list, Scheme pro+ides man$ primiti+e operations and )unctions! and so do other languages, 1e should )ind out as much as possible about our wor.ing language! though onl$ when we settle on one, For beginners! a super)icial .nowledge o) a language is )ine, I) we )ollow these guidelines! we interlea+e the de+elopment o) one )unction with that o) others, As we )inish a )unction that does not depend on an$thing on our wish list! we can test it, @nce we ha+e tested such basic )unctions! we can wor. our wa$ bac.wards and test other )unctions until we ha+e )inished the wish list, B$ testing each )unction rigorousl$ be)ore we test those that depend on it! we greatl$ reduce the e))ort o) searching )or logical mista.es,

$"#" Recursive

u,iliary +unctions

People need to sort things all the time, In+estment ad+isors sort port)olios b$ the pro)it each holding generates, Doctors sort lists o) transplant patients, Mail programs sort messages, More generall$! sorting lists o) +alues b$ some criteria is a tas. that man$ programs need to per)orm, Here we stud$ how to sort a list o) numbers not because it is important )or man$ programming tas.s! but also because it pro+ides a good case stud$ o) the design o) au8iliar$ programs, A sorting )unction consumes a list and produces one, Indeed! the two lists contain the same numbers! though the output list contains them in a di))erent order, This is the essence o) the contract and purpose statement:

66"sort":"+ist-of-n.m8ers""-/""+ist-of-n.m8ers" 66"to"create"a"sorted"+ist"of"n.m8ers"from"a++"the"n.m8ers"in"a+on !define"!sort"a+on#"...#

Here is one e8ample per clause in the data de)inition:


!sort"empt2# 66"e*pected"0a+.e:" empt2 !sort"!cons"12,7.%4"!cons"2%%%%.%%"!cons"-5%5.25"empt2#### 66"e*pected"0a+.e:" !cons"2%%%%.%%"!cons"12,7.%4"!cons"-5%5.25"empt2###

The answer )or the input empt2 is empt2! because empt2 contains the same items /none0 and in sorted order, -e8t we must translate the data de)inition into a )unction template, Again! we ha+e dealt with lists o) numbers be)ore! so this step is eas$:
!define"!sort"a+on# ""!cond """"9!empt2A"a+on#"...: """"9else"..."!first"a+on#"..."!sort"!rest"a+on##"...:##

Asing this template! we can )inall$ turn to the interesting part o) the program de+elopment, 1e consider each case o) the cond2e8pression separatel$! starting with the simple case, I) sortCs input is empt2! then the answer is empt2! as speci)ied b$ the e8ample, So letCs assume that the input is not empt2, That is! letCs deal with the second cond2clause, It contains two e8pressions and! )ollowing the design recipe! we must understand what the$ compute: (, !first"a+on# e8tracts the )irst number )rom the inputE &, !sort"!rest"a+on## produces a sorted +ersion o) !rest"a+on#! according to the purpose statement o) the )unction, Putting together these two +alues means inserting the )irst number into its appropriate spot in the sorted rest o) the list, "etCs loo. at the second e8ample in this conte8t, 1hen sort consumes !cons"12,7.%4 !cons"2%%%%.%%"!cons"-5%5.25"empt2###! then (, !first"a+on# e+aluates to 12,7.%4! &, !rest"a+on# is !cons"2%%%%.%%"!cons"-5%5.25"empt2##! and

5, !sort"!rest"a+on## produces !cons"2%%%%.%%"!cons"-5%5.25"empt2##, To produce the desired answer! we must insert 12,7.%4 between the two numbers o) the last list, More generall$! the answer in the second cond2line must be an e8pression that inserts !first"a+on# in its proper place into the sorted list !sort"!rest"a+on##, Inserting a number into a sorted list isnCt a simple tas., 1e ma$ ha+e to search through the entire list be)ore we .now what the proper place is, Searching through a list! howe+er! can be done onl$ with a )unction! because lists are o) arbitrar$ si*e and processing such +alues re?uires recursi+e )unctions, Thus we must de+elop an au8iliar$ )unction that consumes the )irst number and a sorted list and creates a sorted list )rom both, "et us call this )unction insert and let us )ormulate a wish2list entr$:
66"insert":"n.m8er"+ist-of-n.m8ers""-/""+ist-of-n.m8ers 66"to"create"a"+ist"of"n.m8ers"from"n"and"the"n.m8ers"on"a+on" 66"that"is"sorted"in"descending"order6"a+on"is"a+read2"sorted !define"!insert"n"a+on#"...#

Asing insert! it is eas$ to complete the de)inition o) sort:


!define"!sort"a+on# ""!cond """"9!empt2A"a+on#"empt2: """"9else"!insert"!first"a+on#"!sort"!rest"a+on###:##

The answer in the second line sa$s that in order to produce the )inal result! sort e8tracts the )irst item o) the non2empt$ list! computes the sorted +ersion o) the rest o) the list! and inserts the )ormer into the latter at its appropriate place, @) course! we are not reall$ )inished until we ha+e de+eloped insert, 1e alread$ ha+e a contract! a header! and a purpose statement, -e8t we need to ma.e up )unction e8amples, Since the )irst input o) insert is atomic! letCs ma.e up e8amples based on the data de)inition )or lists, That is! we )irst consider what insert should produce when gi+en a number and empt2, According to insertCs purpose statement! the output must be a list! it must contain all numbers )rom the second input! and it must contain the )irst argument, This suggests the )ollowing:
!insert"5"empt2# 66"e*pected"0a+.e:" !cons"5"empt2#

Instead o) 5! we could ha+e used an$ number, The second e8ample must use a non2empt$ list! but then! the idea )or insert was suggested b$ Fust such an e8ample when we studied how sort should deal with non2 empt$ lists, Speci)icall$! we said that sort had to insert 12,7.%4 into !cons"2%%%%.%% !cons"-5%5.25"empt2## at its proper place:
!insert"12,7.%4"!cons"2%%%%.%%"!cons"-5%5.25"empt2###

66"e*pected"0a+.e:" !cons"2%%%%.%%"!cons"12,7.%4"!cons"-5%5.25"empt2###

In contrast to sort! the )unction insert consumes t-o inputs, But we .now that the )irst one is a number and atomic, 1e can there)ore )ocus on the second argument! which is a list o) numbers and which suggests that we use the list2processing template one more time:
!define"!insert"n"a+on# ""!cond """"9!empt2A"a+on#"...: """"9else""...""!first"a+on#"..."!insert"n"!rest"a+on##"...:##

The onl$ di))erence between this template and the one )or sort is that this one needs to ta.e into account the additional argument n, To )ill the gaps in the template o) insert! we again proceed on a case2b$2case basis, The )irst case concerns the empt$ list, According to the purpose statement! insert must now construct a list with one number: n, Hence the answer in the )irst case is !cons"n empt2#, The second case is more complicated than that, 1hen a+on is not empt$! (, !first"a+on# is the )irst number on a+on! and &, !insert"n"!rest"a+on## produces a sorted list consisting o) n and all numbers on !rest"a+on#, The problem is how to combine these pieces o) data to get the answer, "et us consider an e8ample:
!insert"7"!cons" "!cons"5"!cons"4"empt2####

Here n is 7 and larger than an$ o) the numbers in the second input, Hence it su))ices i) we Fust cons 7 onto !cons" "!cons"5"!cons"4"empt2###, In contrast! when the application is something li.e
!insert"3"!cons" "!cons"2"!cons"1"!cons"-1"empt2##### n

must indeed be inserted into the rest o) the list, More concretel$! (, !first"a+on# is &, !insert"n"!rest"a+on## is !cons"3"!cons"2"!cons"1"!cons"-1 empt2####,

B$ adding onto this last list with cons! we get the desired answer, Here is how we generali*e )rom these e8amples, The problem re?uires a )urther case distinction, I) n is larger than /or e?ual to0 !first"a+on#! all the items in a+on are smaller than nE a)ter all! a+on is alread$ sorted, The result is !cons"n"a+on# )or this case, I)! howe+er! n is smaller than !first"a+on#! then we ha+e not $et )ound the proper place to insert n into a+on, 1e do .now that the )irst item o) the result must be the !first"a+on# and that n must be inserted into !rest"a+on#, The )inal result in this case is
!cons"!first"a+on#"!insert"n"!rest"a+on###

because this list contains n and all items o) a+on in sorted order 22 which is what we need, The translation o) this discussion into Scheme re?uires the )ormulation o) a conditional e8pression that distinguishes between the two possible cases:
!cond ""9!/&"n"!first"a+on##"...: ""9!?""n"!first"a+on##"...:#

From here! we Fust need to put the proper answer e8pressions into the two cond2clauses, Figure 55 contains the complete de)initions o) insert and sort,
66"sort":"+ist-of-n.m8ers""-/""+ist-of-n.m8ers"!sorted# 66"to"create"a"+ist"of"n.m8ers"with"the"same"n.m8ers"as 66"a+on"sorted"in"descending"order !define"!sort"a+on# ""!cond """"9!empt2A"a+on#"empt2: """"9!consA"a+on#"!insert"!first"a+on#"!sort"!rest"a+on###:## 66"insert":"n.m8er"+ist-of-n.m8ers"!sorted#""-/""+ist-of-n.m8ers !sorted# 66"to"create"a"+ist"of"n.m8ers"from"n"and"the"n.m8ers"on 66"a+on"that"is"sorted"in"descending"order6"a+on"is"sorted !define"!insert"n"a+on# ""!cond """"9!empt2A"a+on#"!cons"n"empt2#: """"9else"!cond """"""""""""9!/&"n"!first"a+on##"!cons"n"a+on#:

V/U n /)irst alon00 /cons /)irst alon0 /insert n /rest alon000W0W00 Figure !!' Sorting lists o) numbers

Terminolog%: This particular program )or sorting is .nown as I-S#RTI@- S@RT in the programming literature, E ercise 12<2<1< De+elop a program that sorts lists o) mail messages b$ date, Mail structures are de)ined as )ollows:

!define-struct"mai+"!from"date"message##

A mai!-message is a structure: where name is a string! n is


!ma-e-mai+"name"n"s# a number! and s is a string,

Also de+elop a program that sorts lists o) mail messages b$ name, To compare two strings alphabeticall$! use the string?A primiti+e, Solution E ercise 12<2<2< Here is the )unction search:
66"search":"n.m8er"+ist-of-n.m8ers""-/""8oo+ean !define"!search"n"a+on# ""!cond """"9!empt2A"a+on#"fa+se: """"9else"!or"!&"!first"a+on#"n#"!search"n"!rest"a+on###:##

It determines whether some number occurs in a list o) numbers, The )unction ma$ ha+e to tra+erse the entire list to )ind out that the number o) interest isnCt contained in the list, De+elop the )unction search-sorted! which determines whether a number occurs in a sorted list o) numbers, The )unction must ta.e ad+antage o) the )act that the list is sorted,

Terminolog%: The )unction search-sorted conducts a "I-#AR S#ARCH, Solution

$"#( 5enerali9ing Pro&lems2 5enerali9ing +unctions


Consider the problem o) drawing a po!ygon! that is! a geometric shape with an arbitrar$ number o) corners,5; A natural representation )or a pol$gon is a list o) posn structures: A !ist-of-posns is either (, the empt$ list! empt2! or &, !cons"p"+op# where p is a posn structure and +op is a list o) posns, #ach posn represents one corner o) the pol$gon, For e8ample!
!cons"!ma-e-posn"1%"1%# ""!cons"!ma-e-posn" %" %#

""""!cons"!ma-e-posn"1%" %# """"""empt2###

represents a triangle, The ?uestion is what empt2 means as a pol$gon, The answer is that empt2 does not represent a pol$gon and there)ore shouldnCt be included in the class o) pol$gon representations, A pol$gon should alwa$s ha+e at least one corner! and the lists that represent pol$gons should alwa$s contain at least one posn, This suggest the )ollowing data de)inition: A po!ygon is either (, !cons"p"empt2# where p is a posn! or &, !cons"p"+op# where p is a posn structure and +op is a pol$gon, In short! a discussion o) how the chosen set o) data /lists o) posns0 represents the intended in)ormation /geometric pol$gons0 re+eals that our choice was inade?uate, Re+ising the data de)inition brings us closer to our intentions and ma.es it easier to design the program, Because our drawing primiti+es alwa$s produce tr.e /i) an$thing0! it is natural to suggest the )ollowing contract and purpose statement:
66"draw-po+2gon":"po+2gon""-/""tr.e 66"to"draw"the"po+2gon"specified"82"a-po+2" !define"!draw-po+2gon"a-po+2#"...#

In other words! the )unction draws the lines between the corners and! i) all primiti+e drawing steps wor. out! it produces tr.e, For e8ample! the abo+e list o) posns should produce a triangle, Although the data de)inition is not Fust a +ariant on our well2worn list theme! the template is close to that o) a list2processing )unction:
66"draw-po+2gon":"po+2gon""-/""tr.e 66"to"draw"the"po+2gon"specified"82"a-po+2" !define"!draw-po+2gon"a-po+2# ""!cond """"9!empt2A"!rest"a-po+2##"..."!first"a-po+2#"...: """"9else"..."!first"a-po+2#"..." """"""""..."!second"a-po+2#"... """"""""..."!draw-po+2gon"!rest"a-po+2##"...:##

=i+en that both clauses in the data de)inition use cons! the )irst condition must inspect the rest o) the list! which is empt2 )or the )irst case and non2empt$ )or the second one, Furthermore! in the )irst clause! we can add !first"a-po+2#E and in the second case!

we not onl$ ha+e the )irst item on the list but the second one! too, A)ter all! pol$gons generated according to the second clause consist o) at least two posns, -ow we can replace the DD...CC in the template to obtain a complete )unction de)inition, For the )irst clause! the answer must be tr.e! because we donCt ha+e two posns that we could connect to )orm a line, For the second clause! we ha+e two posns! we can draw a line between them! and we .now that !draw-po+2gon"!rest"a-po+2## draws all the remaining lines, Put di))erentl$! we can write
!draw-so+id-+ine"!first"a-po+2#"!second"a-po+2##

in the second clause because we .now that a-po+2 has a second item, Both !drawso+id-+ine"...# and !draw-po+2"...# produce tr.e i) e+er$thing goes )ine, B$ combining the two e8pressions with and! draw-po+2 draws all lines, Here is the complete )unction de)inition:
!define"!draw-po+2gon"a-po+2# ""!cond """"9!empt2A"!rest"a-po+2##"tr.e: """"9else"!and"!draw-so+id-+ine"!first"a-po+2#"!second"a-po+2## """""""""""""""!draw-po+2gon"!rest"a-po+2###:##

An)ortunatel$! testing it with our triangle e8ample immediatel$ re+eals a )law, Instead o) drawing a pol$gon with three sides! the )unction draws onl$ an open cur+e! connecting all the corners but not closing the cur+e:

Mathematicall$ put! we ha+e de)ined a more general )unction than the one we wanted, The )unction we de)ined should be called DDconnect2the2dotsCC and not draw-po+2gon, To get )rom the more general )unction to what we want! we need to )igure out some wa$ to connect the last dot to the )irst one, There are se+eral wa$s to accomplish this goal! but all o) them mean that we de)ine the main )unction in terms o) the )unction we Fust de)ined or something li.e it, In other words! we de)ine one au8iliar$ )unction in terms o) a more general one,

@ne wa$ to de)ine the new )unction is to add the )irst position o) a pol$gon to the end and to ha+e this new list drawn, A s$mmetric method is to pic. the last one and add it to the )ront o) the pol$gon, A third alternati+e is to modi)$ the abo+e +ersion o) drawpo+2gon so that it connects the last posn to the )irst one, Here we discuss the second alternati+eE the e8ercises co+er the other two, To add the last item o) a-po+2 at the beginning! we need something li.e
!cons"!+ast"a-po+2#"a-po+2#

where +ast is some au8iliar$ )unction that e8tracts the last item )rom a non2empt$ list, Indeed! this e8pression is the de)inition o) draw-po+2gon assuming we de)ine +ast: see )igure 56, Formulating the wish list entr$ )or +ast is straight)orward:
66"+ast":"po+2gon""-/""posn 66"to"e*tract"the"+ast"posn"on"a-po+2 !define"!+ast"a-po+2#"...#

And! because +ast consumes a pol$gon! we can reuse the template )rom abo+e:
!define"!+ast"a-po+2# ""!cond """"9!empt2A"!rest"a-po+2##"..."!first"a-po+2#"...: """"9else"..."!first"a-po+2#"..." """"""""..."!second"a-po+2#"... """"""""..."!+ast"!rest"a-po+2##"...:##

Turning the template into a complete )unction is a short step, I) the list is empt$ e8cept )or one item! this item is the desired result, I) !rest"a-po+2# is not empt$! !+ast !rest"a-po+2## determines the last item o) a-po+2, The complete de)inition o) +ast is displa$ed at the bottom o) )igure 56,

66"draw-po+2gon":"po+2gon""-/""tr.e 66"to"draw"the"po+2gon"specified"82"a-po+2" !define"!draw-po+2gon"a-po+2# ""!connect-dots"!cons"!+ast"a-po+2#"a-po+2### 66"connect-dots":"po+2gon""-/""tr.e 66"to"draw"connections"8etween"the"dots"of"a-po+2 !define"!connect-dots"a-po+2# ""!cond """"9!empt2A"!rest"a-po+2##"tr.e: """"9else"!and"!draw-so+id-+ine"!first"a-po+2#"!second"a-po+2# 'red# """""""""""""""!connect-dots"!rest"a-po+2###:## 66"+ast":"po+2gon""-/""posn 66"to"e*tract"the"+ast"posn"on"a-po+2 !define"!+ast"a-po+2# ""!cond """"9!empt2A"!rest"a-po+2##"!first"a-po+2#:

Velse /last /rest a2pol$00W00 Figure !#' Drawing a pol$gon In summar$! the de+elopment o) draw-po+2gon naturall$ led us to consider a more general problem: connecting a list o) dots, 1e sol+ed the original problem b$ de)ining a )unction that uses /a +ariant o)0 the more general )unction, As we will see again and again! generali*ing the purpose o) a )unction is o)ten the best method to simpli)$ the problem, E ercise 12<!<1< Modi)$ draw-po+2gon so that it adds the )irst item o) a-po+2 to its end, This re?uires a di))erent au8iliar$ )unction: add-at-end, Solution E ercise 12<!<2< Modi)$ connect-dots so that it consumes an additional posn structure to which the last posn is connected, Then modi)$ draw-po+2gon to use this new +ersion o) connect-dots, +ccumulator: The new +ersion o) connect-dots is a simple instance o) an accumulator2st$le )unction, In part 4I we will discuss an entire class o) such problems, Solution

$"#) E,tended E,ercise. Rearranging Words


-ewspapers o)ten contain e8ercises that as. readers to )ind all possible words made up )rom some letters, @ne wa$ to pla$ this game is to )orm all possible arrangements o) the letters in a s$stematic manner and to see which arrangements are dictionar$ words, Suppose the letters DDa!CC DDd!CC DDe!CC and DDrCC are gi+en, There are twent$2)our possible arrangements o) these letters:

ader daer dear dera aedr

eadr edar edra aerd eard

erad erda adre dare drae

drea arde rade rdae rdea

ared raed read reda

The three legitimate words in this list are DDread!CC DDdear!CC and DDdare,CC The s$stematic enumeration o) all possible arrangements is clearl$ a tas. )or a computer program, It consumes a word and produces a list o) the wordCs letter2b$2letter rearrangements, @ne representation o) a word is a list o) s$mbols, #ach item in the input represents a letter: 'a! '8! ...! '@, Here is the data de)inition )or words: A -ord is either (, empt2! or &, !cons"a"w# where a is a s$mbol /'a! '8! ...! '@0 and w is a word, E ercise 12<#<1< Formulate the data de)inition )or lists o) words, S$stematicall$ ma.e up e8amples o) words and lists o) words, Solution "et us call the )unction arrangements,5< Its template is that o) a list2processing )unction:
66"arrangements":"word""-/""+ist-of-words 66"to"create"a"+ist"of"a++"rearrangements"of"the"+etters"in"a-word !define"!arrangements"a-word# ""!cond """"9!empt2A"a-word#"...: """"9else"..."!first"a-word#"..."!arrangements"!rest"aword##"...:##

=i+en the contract! the supporting data de)initions! and the e8amples! we can now loo. at each cond2line in the template: (, I) the input is empt2! there is onl$ one possible rearrangement o) the input: the empt2 word, Hence the result is !cons"empt2"empt2#! the list that contains the empt$ list as the onl$ item,

&, @therwise there is a )irst letter in the word! and !first"a-word# is that letter and the recursion produces the list o) all possible rearrangements )or the rest o) the word, For e8ample! i) the list is
3. !cons"'d"!cons"'e"!cons"'r"empt2###

then the recursion is !arrangements"!cons"'e"!cons"'r"empt2###, It will produce the result


!cons"!cons"'e"!cons"'r"empt2## ""!cons"!cons"'r"!cons"'e"empt2## """"empt2##

To obtain all possible rearrangements )or the entire list! we must now insert the )irst item! 'd in our case! into all o) these words between all possible letters and at the beginning and end, The tas. o) inserting a letter into man$ di))erent words re?uires processing an arbitraril$ large list, So! we need another )unction! call it insert-e0er2where/in-a++-words! to complete the de)inition o) arrangements:
!define"!arrangements"a-word# ""!cond """"9!empt2A"a-word#"!cons"empt2"empt2#: """"9else"!insert-e0er2where/in-a++-words"!first"a-word#" """"""""""""!arrangements"!rest"a-word###:##

E ercise 12<#<2< De+elop the )unction insert-e0er2where/in-a++-words, It consumes a s$mbol and a list o) words, The result is a list o) words li.e its second argument! but with the )irst argument inserted between all letters and at the beginning and the end o) all words o) the second argument, >int' Reconsider the e8ample )rom abo+e, 1e stopped and decided that we needed to insert 'd into the words !cons"'e"!cons"'r"empt2## and !cons"'r"!cons"'e empt2##, The )ollowing is there)ore a natural candidate:
!insert-e0er2where/in-a++-words"'d ""!cons"!cons"'e"!cons"'r"empt2## """"!cons"!cons"'r"!cons"'e"empt2## """"""empt2###

)or the DD)unction e8amplesCC step, eep in mind that the second input corresponds to the se?uence o) /partial0 words DDerCC and DDreCC, Also! use the Scheme operation append! which consumes two lists and produces the concatenation o) the two lists, For e8ample:
""!append"!+ist"'a"'8"'c#"!+ist"'d"'e##" &"!+ist"'a"'8"'c"'d"'e#

1e will discuss the de+elopment o) )unctions such as append in section (;, Solution

59

The term DDwish listCC in this conte8t is due to Dr, John Stone, Mr, Paul C, Fisher inspired this section, The mathematical term is perm tation,

5;

5<

Section 1! Interme**o 2' ,ist +bbre1iations


Intermediate Student Asing cons to create lists is cumbersome i) a list contains man$ items, Fortunatel$! Scheme pro+ides the +ist operation! which consumes an arbitrar$ number o) +alues and creates a list, Here is SchemeCs e8tended s$nta8:
?prm/"&"+ist

The e8tended collection o) +alues is


?0a+/"&"!+ist"?0a+/"..."?0a+/#

A simpler wa$ to understand +ist e8pressions is to thin. o) them as abbre+iations, Speci)icall$! e+er$ e8pression o) the shape
!+ist"e*p-1"..."e*p-n#

stands )or a series o) n cons e8pressions:


!cons"e*p-1"!cons"..."!cons"e*p-n"empt2###

Recall that empt2 is not an item o) the list here! but the rest o) the list, Here are three e8amples:
!+ist"1"2# &"!cons"1"!cons"2"empt2##" !+ist"'=o.ston"'Da++as"'Can'ntonio# &"!cons"'=o.ston"!cons"'Da++as"!cons"'Can'ntonio"empt2###" !+ist"fa+se"tr.e"fa+se"fa+se# &"!cons"fa+se"!cons"tr.e"!cons"fa+se"!cons"fa+se"empt2####

The$ introduce lists with two! three! and )our items! respecti+el$, @) course! we can appl$ +ist not onl$ to +alues but also to e8pressions:
""!+ist"!+"%"1#"!+"1"1## &"!+ist"1"2#

Be)ore the list is constructed! the e8pressions must be e+aluated, I) during the e+aluation o) an e8pression an error occurs! the list is ne+er )ormed:
""!+ist"!/"1"%#"!+"1"1## &"/:"di0ide"82"@ero

In short! +ist beha+es Fust li.e an$ other primiti+e operation, The use o) +ist greatl$ simpli)ies the notation )or lists with man$ items and lists that contains lists or structures, Here is an e8ample:
""!+ist"%"1"2"3"4"5" "7"$",#

This list contains (' items and its )ormation with cons and empt2 would re?uire (' uses o) cons and one instance o) empt2, Similarl$! the list
""!+ist"!+ist"'8o8"%"'a#" """"""""!+ist"'car+"1"'a# !+ist"'dana"2"'8# !+ist"'eri-"3"'c# !+ist"'fran-"4"'a# !+ist"'grant"5"'8# !+ist"'han-" "'c# !+ist"'ian"$"'a# !+ist"'Sohn"7"'d# !+ist"'-are+","'e##

re?uires (( uses o) +ist in contrast to 6' o) cons and (( o) empt2, E ercise 1!<.<!< Ase cons and empt2 to construct the e?ui+alent o) the )ollowing lists: (, !+ist"%"1"2"3"4"5# &, !+ist"!+ist"'adam"%#"!+ist"'e0e"1#"!+ist"'+o.isRIW"2## 5, !+ist"1"!+ist"1"2#"!+ist"1"2"3##, Solution E ercise 1!<.<#< Ase +ist to construct the e?ui+alent o) the )ollowing lists: (, !cons"'a"!cons"'8"!cons"'c"!cons"'d"!cons"'e"empt2##### &, !cons"!cons"1"!cons"2"empt2##"empt2#

5, !cons"'a"!cons"!cons"1"empt2#"!cons"fa+se"empt2###, 6, !cons"!cons"1"!cons"2"empt2##"!cons"!cons"2"!cons"3"empt2##
empt2##

Start b$ determining how man$ items each list and each nested list contains, Solution E ercise 1!<.<$< @n rare occasions! we encounter lists )ormed with cons and +ist, Re)ormulate the )ollowing lists using cons and empt2 e8clusi+el$: (, !cons"'a"!+ist"%"fa+se## &, !+ist"!cons"1"!cons"13"empt2### 5, !+ist"empt2"empt2"!cons"1"empt2## 6, !cons"'a"!cons"!+ist"1#"!+ist"fa+se"empt2###,

Then )ormulate the lists using +ist,

Solution

E ercise 1!<.<&< Determine the +alues o) the )ollowing e8pressions: (, !+ist"!s2m8o+&A"'a"'8#"!s2m8o+&A"'c"'c#"fa+se# &, !+ist"!+"1%"2%#"!*"1%"2%#"!/"1%"2%## 5, !+ist"'dana"'Sane"'mar2"'+a.ra#

Solution E ercise 1!<.<(< Determine the +alues o)


!first"!+ist"1"2"3## !rest"!+ist"1"2"3##

Solution The use o) +ist ma.es it signi)icantl$ easier to e+aluate e8pressions in+ol+ing lists, Here are the recursi+e steps )rom an e8ample )rom section >,7:
""!s.m"!+ist"!ma-e-ir"'ro8ot"22.%5#"!ma-e-ir"'do++"17.,5### &"!+"!ir-price"!first"!+ist"!ma-e-ir"'ro8ot"22.%5#"!ma-e-ir"'do++ 17.,5#### """""!s.m"!rest"!+ist"!ma-e-ir"'ro8ot"22.%5#"!ma-e-ir"'do++ 17.,5##### &"!+"!ir-price"!ma-e-ir"'ro8ot"22.%5## """""!s.m"!+ist"!ma-e-ir"'do++"17.,5#### 't"this"p+ace<"we".se"one"of"the"e).ations"go0erning" the"new"primiti0e"operations"for"the"first"time:" &"!+"22.%5 """""!s.m"!+ist"!ma-e-ir"'do++"17.,5#### &"!+"22.%5 """""!+"!ir-price"!first"!+ist"!ma-e-ir"'do++"17.,5#### """"""""!s.m"!rest"!+ist"!ma-e-ir"'do++"17.,5###### &"!+"22.%5 """""!+"!ir-price"!ma-e-ir"'do++"17.,5## """"""""!s.m"empt2### &"!+"22.%5"!+"17.,5"!s.m"empt2### &"!+"22.%5"!+"17.,5"%##

Since the laws o) first and rest carr$ o+er to +ist +alues in a natural manner! an e+aluation using +ist does not need to e8pand +ist into uses o) cons and empt2, Following an old programming language con+ention!5> we ma$ abbre+iate lists and s$mbols e+en )urther, I) a list is )ormulated with +ist! we can simpl$ agree to drop list and that each opening parenthesis stands )or itsel) and the word +ist, For e8ample!
'!1"2"3# a88re0iates" !+ist"1"2"3# or !cons"1"!cons"2"!cons"3"empt2###".

Similarl$!
'!!1"2#"!3"4#"!5" ## stands"for !+ist"!+ist"1"2#"!+ist"3"4#"!+ist"5" ##,

which can be )urther e8panded into cons and empt2 e8pressions, I) we drop ?uotes in )ront o) s$mbols! writing lists o) s$mbols is a bree*e:
K!a"8"c# ;his"short-hand"is"an"a88re0iation"for !+ist"Ka"K8"Kc#

And! more impressi+el$!

K!?htm+/" """!?tit+e/"H2">irst"Oe8"3age# """!?8od2/"NhD## stands"for !+ist"K?htm+/" ""!+ist"K?tit+e/"KH2"K>irst"KOe8"K3age# ""!+ist"K?8od2/"KNhD##".

E ercise 1!<.<)< Restore +ist and ?uotes where necessar$: (, &, K!1"a"2"8"3"c# 5, 6, 7, 9, ;, <, >, K!!H2">irst"3aper# (', ""!Cean">is+er# ((, ""!Cection"1" (&, """"!C.8section"1"Life"is"diffic.+t# (5, """"!C.8section"2"(.t"+earning"things"ma-es"it"interesting## (6, ""!Cection"2 (7, """"7onc+.sionA"Ohat"conc+.sionA##"" Solution
K!!a+an"1%%%# ""!8ar8"2%%%# ""!car+"15%%# ""!dawn"23%%##

The con+ention is due to "ISP! an earl$ but highl$ ad+anced programming language designed in (>7<, Scheme inherited man$ ideas )rom "ISP! but it is a di))erent language,
5>

Part III /ore on Processing +rbitraril% ,arge Data

Section 1# /ore Self2referential Data Definitions


"ists and natural numbers are two classes o) data whose description re?uires sel)2 re)erential data de)initions, Both data de)initions consist o) two clausesE both ha+e a single sel)2re)erence, Man$ interesting classes o) data! howe+er! re?uire more comple8 de)initions than that, Indeed! there is no end to the +ariations, It is there)ore necessar$ to learn how to )ormulate data de)initions on our own! starting with in)ormal descriptions o) in)ormation, @nce we ha+e those! we can Fust )ollow a slightl$ modi)ied design recipe )or sel)2re)erential data de)initions,

$)#$ Structures in Structures


Medical researchers rel$ on )amil$ trees to do research on hereditar$ diseases, The$ ma$! )or e8ample! search a )amil$ tree )or a certain e$e color, Computers can help with these tas.s! so it is natural to design representations o) )amil$ trees and )unctions )or processing them, @ne wa$ to maintain a )amil$ tree o) a )amil$ is to add a node to the tree e+er$ time a child is born, From the node! we can draw connections to the node )or the )ather and the one )or the mother! which tells us how the people in the tree are related, For those people in the tree whose parents are un.nown! we do not draw an$ connections, The result is a so2called ancestor fami!y tree because! gi+en an$ node in the tree! we can )ind the ancestors o) that person i) we )ollow the arrows but not the descendants, As we record a )amil$ tree! we ma$ also want to record certain pieces o) in)ormation, The birth date! birth weight! the color o) the e$es! and the color o) the hair are the pieces o) in)ormation that we care about, @thers record di))erent in)ormation,

Figure !$' A sample ancestor )amil$ tree See )igure 57 )or a drawing o) an ancestor )amil$ tree, Adam is the child o) Bettina and CarlE he has $ellow e$es and was born in (>7', Similarl$! =usta+ is the child o) #+a and Fred! has brown e$es! and was born in (><<, To represent a child in a )amil$ tree is to combine se+eral pieces o) in)ormation: in)ormation about the )ather! the mother! the name! the birth date! and e$e color, This suggests that we de)ine a new structure:
!define-struct"chi+d"!father"mother"name"date"e2es##

The )i+e )ields o) chi+d structures record the re?uired in)ormation! which suggests the )ollowing data de)inition: A chi+d is a structure:
!ma-e-chi+d"f"m"na"da"ec#

where f and m are chi+d structuresE na and ec are s$mbolsE and da is a number, 1hile this data de)inition is simple! it is un)ortunatel$ also useless, The de)inition re)ers to itsel) but! because it doesnCt ha+e an$ clauses! there is no wa$ to create a chi+d structure, I) we tried to create a chi+d structure! we would ha+e to write
!ma-e-chi+d" ""!ma-e-chi+d """"!ma-e-chi+d" """"""!ma-e-chi+d" """"""""..." """"""""### """..."..."..."...#

without end, It is )or this reason that we demand that all sel)2re)erential data de)initions consist o) se+eral clauses /)or now0 and that at least one o) them does not re)er to the data de)inition, "etCs postpone the data de)inition )or a moment and stud$ instead how we can use chi+d structures to represent )amil$ trees, Suppose we are about to add a child to an e8isting )amil$ tree! and )urthermore suppose that we alread$ ha+e representations )or the

parents, Then we can Fust construct a new chi+d structure, For e8ample! )or Adam we could create the )ollowing chi+d structure:
!ma-e-chi+d"7ar+"(ettina"''dam"1,5%"'2e++ow#

assuming 7ar+ and (ettina stand )or representations o) AdamCs parents, The problem is that we donCt alwa$s .now a personCs parents, In the )amil$ depicted in )igure 57! we donCt .now BettinaCs parents, 3et! e+en i) we donCt .now a personCs )ather or mother! we must still use some Scheme +alue )or the two )ields in a chi+d structure, 1e could use all .inds o) +alues to signal a lac. o) in)ormation /5! fa+se! or 'none0E here! we use empt2, For e8ample! to construct a chi+d structure )or Bettina! we do the )ollowing:
!ma-e-chi+d"empt2"empt2"'(ettina"1,2 "'green#

@) course! i) onl$ one o) the two parents is missing! we )ill Fust that )ield with empt2, @ur anal$sis suggests that a chi+d node has the )ollowing data de)inition: A chi!d node is !ma-e-chi+d"f"m"na"da"ec# where (, f and m are either a, empt2 or b, chi+d nodesE &, na and ec are s$mbolsE 5, da is a number, This de)inition is special in two regards, First! it is a sel)2re)erential data de)inition in+ol+ing structures, Second! the data de)inition mentions two alternati+es )or the )irst and second component, This +iolates our con+entions concerning the shape o) data de)initions, 1e can a+oid this problem b$ de)ining the collection o) nodes in a )amil$ tree instead: A fami!y-tree-node /short: ftn0 is either (, empt2E or

&, !ma-e-chi+d"f"m"na"da"ec# where f and m are ftns! na and ec are s$mbols! and da is a number, This new de)inition satis)ies our con+entions, It consists o) two clauses, @ne o) the clauses is sel)2re)erential! the other is not, In contrast to pre+ious data de)initions in+ol+ing structures! the de)inition o) ftn is not a plain e8planation o) what .ind o) data can show up in which )ield, Instead! it is multi2 clausal and sel)2re)erential, Considering that this is the )irst such data de)inition! let us care)ull$ translate the e8ample )rom )igure 57 and thus reassure oursel+es that the new class o) data can represent the in)ormation o) interest, The in)ormation )or Carl is eas$ to translate into a ftn:
!ma-e-chi+d"empt2"empt2"'7ar+"1,2 "'green#

Bettina and Fred are represented with similar nodes, Accordingl$! the node )or Adam is created with
!ma-e-chi+d"!ma-e-chi+d"empt2"empt2"'7ar+"1,2 "'green#" """"""""""""!ma-e-chi+d"empt2"empt2"'(ettina"1,2 "'green# """"""""""""''dam" """"""""""""1,5%" """"""""""""'2e++ow#

As the e8amples show! a simple2minded! node2b$2node transliteration o) )igure 57 re?uires numerous repetitions o) data, For e8ample! i) we constructed the chi+d structure )or Da+e li.e the one )or Adam! we would get
!ma-e-chi+d"!ma-e-chi+d"empt2"empt2"'7ar+"1,2 "'green#" """"""""""""!ma-e-chi+d"empt2"empt2"'(ettina"1,2 "'green# """"""""""""'Da0e """"""""""""1,55 """"""""""""'8+ac-#

Hence it is a good idea to introduce a +ariable de)inition per node and to use the +ariable therea)ter, To ma.e things eas$! we use 7ar+ to stand )or the chi+d structure that describes Carl! and so on, The complete transliteration o) the )amil$ tree into Scheme can be )ound in )igure 59,

66"N+dest"Generation: !define"7ar+"!ma-e-chi+d"empt2"empt2"'7ar+"1,2 "'green## !define"(ettina"!ma-e-chi+d"empt2"empt2"'(ettina"1,2 "'green## 66"Hidd+e"Generation: !define"'dam"!ma-e-chi+d"7ar+"(ettina"''dam"1,5%"'2e++ow## !define"Da0e"!ma-e-chi+d"7ar+"(ettina"'Da0e"1,55"'8+ac-## !define"50a"!ma-e-chi+d"7ar+"(ettina"'50a"1, 5"'8+.e## !define">red"!ma-e-chi+d"empt2"empt2"'>red"1, "'pin-## 66"Io.ngest"Generation:"

/define =usta+ /ma.e2child Fred #+a ==usta+ (><< =brown00 Figure !&' A Scheme representation o) the sample )amil$ tree The structure de)initions in )igure 59 naturall$ correspond to an image o) deepl$ nested bo8es, #ach bo8 has )i+e compartments, The )irst two contain bo8es again! which in turn contain bo8es in their )irst two compartments! and so on, Thus! i) we were to draw the structure de)initions )or the )amil$ tree using nested bo8es! we would ?uic.l$ be o+erwhelmed b$ the details o) the picture, Furthermore! the picture would cop$ certain portions o) the tree Fust li.e our attempt to use ma-e-chi+d without +ariable de)initions, For these reasons! it is better to imagine the structures as bo8es and arrows! as originall$ drawn in )igure 57, In general! a programmer must )le8ibl$ switch bac. and )orth between both o) these graphical illustrations, For e8tracting +alues )rom structures! the bo8es2in2bo8es image wor.s bestE )or )inding our wa$ around large collections o) interconnected structures! the bo8es2and2arrows image wor.s better, #?uipped with a )irm understanding o) the )amil$ tree representation! we can turn to the design o) )unctions that consume )amil$ trees, "et us )irst loo. at a generic )unction o) this .ind:
66"f.n-for-ftn":"ftn""-/""AAA !define"!f.n-for-ftn"a-ftree#"...#

A)ter all! we should be able to construct the template without considering the purpose o) a )unction, Since the data de)inition )or ftns contains two clauses! the template must consist o) a cond2e8pression with two clauses, The )irst deals with empt2! the second with chi+d structures:
66"f.n-for-ftn":"ftn""-/""AAA !define"!f.n-for-ftn"a-ftree# ""!cond """"9!empt2A"a-ftree#"...: """"9else"6"!chi+dA"a-ftree# """"""...":##

Furthermore! )or the )irst clause! the input is atomic so there is nothing )urther to be done, For the second clause! though! the input contains )i+e pieces o) in)ormation: two other )amil$ tree nodes! the personCs name! birth date! and e$e color:

66"f.n-for-ftn":"ftn""-/""AAA !define"!f.n-for-ftn"a-ftree# ""!cond """"9!empt2A"a-ftree#"...: """"9else """"""..."!f.n-for-ftn"!chi+d-father"a-ftree##"... """"""..."!f.n-for-ftn"!chi+d-mother"a-ftree##"... """"""..."!chi+d-name"a-ftree#"... """"""..."!chi+d-date"a-ftree#"... """"""..."!chi+d-e2es"a-ftree#"...:##

1e also appl$ f.n-for-ftn to the father and mother )ields because o) the sel)2 re)erences in the second clause o) the data de)inition, "et us now turn to a concrete e8ample: 8+.e-e2ed-ancestorA! the )unction that determines whether an$one in some gi+en )amil$ tree has blue e$es:
66"8+.e-e2ed-ancestorA":"ftn""-/""8oo+ean 66"to"determine"whether"a-ftree"contains"a"chi+d 66"str.ct.re"with"'8+.e"in"the"e2es"fie+d !define"!8+.e-e2ed-ancestorA"a-ftree#"...#

Following our recipe! we )irst de+elop some e8amples, Consider the )amil$ tree node )or Carl, He does not ha+e blue e$es! and because he doesnCt ha+e an$ /.nown0 ancestors in our )amil$ tree! the )amil$ tree represented b$ this node does not contain a person with blue e$es, In short!
!8+.e-e2ed-ancestorA"7ar+#

e+aluates to fa+se, In contrast! the )amil$ tree represented b$ G.sta0 contains a node )or #+a who does ha+e blue e$es, Hence
!8+.e-e2ed-ancestorA"G.sta0#

e+aluates to tr.e, The )unction template is li.e that o) f.n-for-ftn! e8cept that we use the name 8+.ee2ed-ancestorA, As alwa$s! we use the template to guide the )unction design, First we assume that !empt2A"a-ftree# holds, In that case! the )amil$ tree is empt$! and nobod$ has blue e$es, Hence the answer must be fa+se, The second clause o) the template contains se+eral e8pressions! which we must interpret: (, !8+.e-e2ed-ancestorA"!chi+d-father"a-ftree##! which determines whether someone in the )atherCs ftn has blue e$esE &, !8+.e-e2ed-ancestorA"!chi+d-mother"a-ftree##! which determines whether someone in the motherCs ftn has blue e$esE

5, !chi+d-name"a-ftree#! which e8tracts the chi+dCs nameE 6, !chi+d-date"a-ftree#! which e8tracts the chi+dCs date o) birthE and 7, !chi+d-e2es"a-ftree#! which e8tracts the chi+dCs e$e color, It is now up to us to use these +alues properl$, Clearl$! i) the chi+d structure contains '8+.e in the e2es )ield! the )unctionCs answer is tr.e, @therwise! the )unction produces tr.e i) there is a blue2e$ed person in either the )atherCs or the motherCs )amil$ tree, The rest o) the data is useless, @ur discussion suggests that we )ormulate a conditional e8pression and that the )irst condition is
!s2m8o+&A"!chi+d-e2es"a-ftree#"'8+.e#

The two recursions are the other two conditions, I) either one produces tr.e! the )unction produces tr.e, The else2clause produces fa+se, In summar$! the answer in the second clause is the e8pression:
!cond ""9!s2m8o+&A"!chi+d-e2es"a-ftree#"'8+.e#"tr.e: ""9!8+.e-e2ed-ancestorA"!chi+d-father"a-ftree##"tr.e: ""9!8+.e-e2ed-ancestorA"!chi+d-mother"a-ftree##"tr.e: ""9else"fa+se:#

The )irst de)inition in )igure 5; pulls e+er$thing together, The second de)inition shows how to )ormulate this cond2e8pression as an e?ui+alent or2e8pression! testing one condition a)ter the ne8t! until one o) them is tr.e or all o) them ha+e e+aluated to fa+se,

66"8+.e-e2ed-ancestorA":"ftn""-/""8oo+ean 66"to"determine"whether"a-ftree"contains"a"chi+d 66"str.ct.re"with"'8+.e"in"the"e2es"fie+d 66"0ersion"1:".sing"a"nested"cond-e*pression !define"!8+.e-e2ed-ancestorA"a-ftree# ""!cond """"9!empt2A"a-ftree#"fa+se: """"9else"!cond """"""""""""9!s2m8o+&A"!chi+d-e2es"a-ftree#"'8+.e#"tr.e: """"""""""""9!8+.e-e2ed-ancestorA"!chi+d-father"a-ftree##"tr.e: """"""""""""9!8+.e-e2ed-ancestorA"!chi+d-mother"a-ftree##"tr.e: """"""""""""9else"fa+se:#:## 66"8+.e-e2ed-ancestorA":"ftn""-/""8oo+ean 66"to"determine"whether"a-ftree"contains"a"chi+d 66"str.ct.re"with"'8+.e"in"the"e2es"fie+d 66"0ersion"2:".sing"an"or-e*pression !define"!8+.e-e2ed-ancestorA"a-ftree# ""!cond """"9!empt2A"a-ftree#"fa+se: """"9else"!or"!s2m8o+&A"!chi+d-e2es"a-ftree#"'8+.e# """"""""""""""!or"!8+.e-e2ed-ancestorA"!chi+d-father"a-ftree##

/blue2e$ed2ancestorH /child2mother a2)tree0000W00 Figure !(' Two )unctions )or )inding a blue2e$ed ancestor The )unction 8+.e-e2ed-ancestorA is unusual in that it uses the recursions as conditions in a cond2e8pressions, To understand how this wor.s! let us e+aluate an application o) 8+.e-e2ed-ancestorA to 7ar+ b$ hand:
""!8+.e-e2ed-ancestorA"7ar+# &"!8+.e-e2ed-ancestorA"!ma-e-chi+d"empt2"empt2"'7ar+"1,2 "'green## &"!cond """"9!empt2A"!ma-e-chi+d"empt2"empt2"'7ar+"1,2 "'green##"fa+se: """"9else """"""!cond """"""""9!s2m8o+&A" """""""""""!chi+d-e2es"!ma-e-chi+d"empt2"empt2"'7ar+"1,2 "'green## """""""""""'8+.e# """""""""tr.e: """"""""9!8+.e-e2ed-ancestorA """""""""""!chi+d-father"!ma-e-chi+d"empt2"empt2"'7ar+"1,2 'green### """""""""tr.e: """"""""9!8+.e-e2ed-ancestorA """""""""""!chi+d-mother"!ma-e-chi+d"empt2"empt2"'7ar+"1,2 'green### """""""""tr.e: """"""""9else"fa+se:#:# &"!cond """"9!s2m8o+&A"'green"'8+.e#"tr.e: """"9!8+.e-e2ed-ancestorA"empt2#"tr.e: """"9!8+.e-e2ed-ancestorA"empt2#"tr.e: """"9else"fa+se:# &"!cond """"9fa+se"tr.e: """"9fa+se"tr.e: """"9fa+se"tr.e: """"9else"fa+se:# &"fa+se"

The e+aluation con)irms that 8+.e-e2ed-ancestorA wor.s properl$ )or 7ar+! and it also illustrates how the )unction wor.s, E ercise 1#<1<1< The second de)inition o) 8+.e-e2ed-ancestorA in )igure 5; uses an or2e8pression instead o) a nested conditional, Ase a hand2e+aluation to show that this de)inition produces the same output )or the inputs empt2 and 7ar+, Solution E ercise 1#<1<2< Con)irm that
!8+.e-e2ed-ancestorA"empt2#

e+aluates to fa+se with a hand2e+aluation, #+aluate !8+.e-e2ed-ancestorA"G.sta0# b$ hand and with DrScheme, For the hand2 e+aluation! s.ip those steps in the e+aluation that concern e8tractions! comparisons! and conditions in+ol+ing empt2A, Also reuse established e?uations where possible! especiall$ the one abo+e, Solution E ercise 1#<1<!< De+elop co.nt-persons, The )unction consumes a )amil$ tree node and produces the number o) people in the corresponding )amil$ tree, Solution E ercise 1#<1<#< De+elop the )unction a0erage-age, It consumes a )amil$ tree node and the current $ear, It produces the a+erage age o) all people in the )amil$ tree, Solution E ercise 1#<1<$< De+elop the )unction e2e-co+ors! which consumes a )amil$ tree node and produces a list o) all e$e colors in the tree, An e$e color ma$ occur more than once in the list, >int' Ase the Scheme operation append! which consumes two lists and produces the concatenation o) the two lists, For e8ample:
""!append"!+ist"'a"'8"'c#"!+ist"'d"'e##" &"!+ist"'a"'8"'c"'d"'e#

1e discuss the de+elopment o) )unctions li.e append in section (;,

Solution

E ercise 1#<1<&< Suppose we need the )unction proper-8+.e-e2ed-ancestorA, It is li.e 8+.e-e2ed-ancestorA but responds with tr.e onl$ when some proper ancestor! not the gi+en one! has blue e$es,

The contract )or this new )unction is the same as )or the old one:
66"proper-8+.e-e2ed-ancestorA":"ftn""-/""8oo+ean 66"to"determine"whether"a-ftree"has"a"8+.e-e2ed"ancestor !define"!proper-8+.e-e2ed-ancestorA"a-ftree#"...#

The results di))er slightl$, To appreciate the di))erence! we need to loo. at #+a! who is blue2e$ed! but does not ha+e a blue2e$ed ancestor, Hence
!8+.e-e2ed-ancestorA"50a#

is tr.e but
!proper-8+.e-e2ed-ancestorA"50a#

is fa+se, A)ter all 50a is not a proper ancestor o) hersel), Suppose a )riend sees the purpose statement and comes up with this solution:
!define"!proper-8+.e-e2ed-ancestorA"a-ftree# ""!cond """"9!empt2A"a-ftree#"fa+se: """"9else"!or"!proper-8+.e-e2ed-ancestorA"!chi+d-father"a-ftree## """"""""""""""!proper-8+.e-e2ed-ancestorA"!chi+d-mother"aftree###:##

1hat would be the result o) !proper-8+.e-e2ed-ancestorA"'# )or any ftn 'H Fi8 the )riendCs solution, Solution

$)#" E,tended E,ercise. Binary Search Trees


Programmers o)ten wor. with trees! though rarel$ with )amil$ trees, A particularl$ well2 .nown )orm o) tree is the binar$ search tree, Man$ applications emplo$ binar$ search trees to store and to retrie+e in)ormation, To be concrete! we discuss binar$ trees that manage in)ormation about people, In this conte8t! a binar$ tree is similar to a )amil$ tree but instead o) chi+d structures it contains nodes:
!define-struct"node"!ssn"name"+eft"right##

Here we ha+e decided to record the social securit$ number! the name! and two other trees, The latter are li.e the parent )ields o) )amil$ trees! though the relationship between a node and its +eft and right trees is not based on )amil$ relationships,

The corresponding data de)inition is Fust li.e the one )or )amil$ trees: A binary-tree /short: 1T0 is either (, fa+seE or &, !ma-e-node"soc"pn"+ft"rgt# where soc is a number! pn is a s$mbol! and +ft and rgt are (;s, The choice o) fa+se to indicate lac. o) in)ormation is arbitrar$, 1e could ha+e chosen empt2 again! but fa+se is an e?uall$ good and e?uall$ )re?uent choice that we should become )amiliar with, Here are two binar$ trees:
"""!ma-e-node """""15 """""'d" """""fa+se """""!ma-e-node"24"'i"fa+se"fa+se## !ma-e-node ""15 ""'d ""!ma-e-node"$7"'h"fa+se"fa+se# ""fa+se#

Figure 5< shows how we should thin. about such trees, The trees are drawn upside down! that is! with the root at the top and the crown o) the tree at the bottom, #ach circle corresponds to a node! labeled with the ssn )ield o) a corresponding node structure, The trees omit fa+se, E ercise 1#<2<1< Draw the two trees abo+e in the manner o) )igure 5<, Then de+elop contains-8t, The )unction consumes a number and a (; and determines whether the number occurs in the tree, Solution E ercise 1#<2<2< De+elop search-8t, The )unction consumes a number n and a (;, I) the tree contains a node structure whose soc )ield is n! the )unction produces the +alue o) the pn )ield in that node, @therwise! the )unction produces fa+se, >int' Ase contains-8t, @r! use 8oo+eanA to )ind out whether search-8t was success)ull$ used on a subtree, 1e will discuss this second techni?ue! called bac.trac.ing! in the interme**o at the end o) this part, Solution

Tree A:

Tree B:

Figure !)' A binar$ search tree and a binar$ tree Both trees in )igure 5< are binar$ trees but the$ di))er in a signi)icant wa$, I) we read the numbers in the two trees )rom le)t to right we obtain two se?uences:

The se?uence )or tree A is sorted in ascending order! the one )or B is not, A binar$ tree that has an ordered se?uence o) in)ormation is a BI-AR3 S#ARCH TR##, #+er$ binar$ search tree is a binar$ tree! but not e+er$ binar$ tree is a binar$ search tree, 1e sa$ that the class o) binar$ search trees is a PR@P#R SABC"ASS o) that o) binar$ trees! that is! a class that does not contain all binar$ trees, More concretel$! we )ormulate a condition 22 or data in+ariant 22 that distinguishes a binar$ search tree )rom a binar$ tree: The BST In+ariant A binary-search-tree /short: 16T0 is a (;: (, fa+se is alwa$s a (C;E &, !ma-e-node"soc"pn"+ft"rgt# is a (C; i) a, +ft and rgt are (C;s! b, all ssn numbers in +ft are smaller than soc! and c, all ssn numbers in rgt are larger than soc, The second and third conditions are di))erent )rom what we ha+e seen in pre+ious data de)initions, The$ place an additional and unusual burden on the construction (C;s, 1e must inspect all numbers in these trees and ensure that the$ are smaller /or larger0 than soc,

E ercise 1#<2<!< De+elop the )unction inorder, It consumes a binar$ tree and produces a list o) all the ssn numbers in the tree, The list contains the numbers in the le)t2to2right order we ha+e used abo+e, >int' Ase the Scheme operation append! which concatenates lists:
!append"!+ist"1"2"3#"!+ist"4#"!+ist"5" "7## e0a+.ates"to" !+ist"1"2"3"4"5" "7#

1hat does inorder produce )or a binar$ search treeH

Solution

"oo.ing )or a speci)ic node in a (C; ta.es )ewer steps than loo.ing )or the same node in a (;, To )ind out whether a (; contains a node with a speci)ic ssn )ield! a )unction ma$ ha+e to loo. at e+er$ node o) the tree, In contrast! to inspect a binar$ search tree re?uires )ar )ewer inspections than that, Suppose we are gi+en the (C;:
!ma-e-node" "'a"L"Q#

I) we are loo.ing )or ! we ha+e )ound it, -ow suppose we are loo.ing )or 3, =i+en the abo+e node! we can )ocus the search on L because a!! nodes with ssns smaller than are in L, Similarl$! i) we were to loo. )or ,,! we would ignore L and )ocus on Q because a!! nodes with ssns larger than are in Q, E ercise 1#<2<#< De+elop search-8st, The )unction consumes a number n and a (C;, I) the tree contains a node structure whose soc )ield is n! the )unction produces the +alue o) the pn )ield in that node, @therwise! the )unction produces fa+se, The )unction organi*ation must e8ploit the BST In+ariant so that the )unction per)orms as )ew comparisons as necessar$, Compare searching in binar$ search trees with searching in sorted lists /e8ercise (&,&,&0, Solution Building a binar$ tree is eas$E building a binar$ search tree is a complicated! error2prone a))air, To create a (; we combine two (;s! an ssn number and a name with ma-e-node, The result is! b$ de)inition! a (;, To create a (C;! this procedure )ails because the result would t$picall$ not be a (C;, For e8ample! i) one tree contains 3 and 5! and the other one contains 2 and ! there is no wa$ to Foin these two (C;s into a single binar$ search tree, 1e can o+ercome this problem in /at least0 two wa$s, First! gi+en a list o) numbers and s$mbols! we can determine b$ hand what the corresponding (C; should loo. li.e and then use ma-e-node to build it, Second! we can write a )unction that builds a (C; )rom the list! one node a)ter another,

E ercise 1#<2<$< De+elop the )unction create-8st, It consumes a (C; (! a number J! and a s$mbol C, It produces a (C; that is Fust li.e ( and that in place o) one fa+se subtree contains the node structure
!ma-e-node"J"C"fa+se"fa+se#

Test the )unction with !create-8st"fa+se" Then show that the )ollowing holds:

"'a#E

this should create a single node,

""!create-8st"!create-8st"fa+se" "'a#"53"'8# &"!ma-e-node" " """""""""""""'a """""""""""""!ma-e-node"53"'8"fa+se"fa+se# """""""""""""fa+se#

Finall$! create tree A )rom )igure 5< using create-8st,

Solution

E ercise 1#<2<&< De+elop the )unction create-8st-from-+ist, It consumes a list o) numbers and namesE it produces a (C; b$ repeatedl$ appl$ing create-8st, The data de)inition )or a list o) numbers and names is as )ollows: A !ist-of-n mber7name is either (, empt2 or &, !cons"!+ist"ssn"nom#"+onn# where ssn is a number! nom a s$mbol! and +onn is a +ist-of-n.m8er/name, Consider the )ollowing e8amples:

!define"samp+e ""K!!,,"o# """"!77"+# """"!24"i# """"!1%"h# """"!,5"g# """"!15"d# """"!$,"c# """"!2,"8# """"! 3"a###

!define"samp+e ""!+ist"!+ist",,"Ko# """"!+ist"77"K+# """"!+ist"24"Ki# """"!+ist"1%"Kh# """"!+ist",5"Kg# """"!+ist"15"Kd# """"!+ist"$,"Kc# """"!+ist"2,"K8# """"!+ist" 3"Ka###

The$ are e?ui+alent! although the le)t one is de)ined with the ?uote abbre+iation! the right one using +ist, The le)t tree in )igure 5< is the result o) using create-8st-from+ist on this list, Solution

$)#( Lists in Lists


The 1orld 1ide 1eb! or Fust DDthe 1eb!CC has become the most interesting part o) the Internet! a global networ. o) computers, Roughl$ spea.ing! the 1eb is a collection o) 1eb pages, #ach 1eb page is a se?uence o) words! pictures! mo+ies! audio messages! and man$ more things, Most important! 1eb pages also contain lin.s to other 1eb pages, A 1eb browser enables people to +iew 1eb pages, It presents a 1eb page as a se?uence o) words! images! and so on, Some o) the words on a page ma$ be underlined, Clic.ing on underlined words leads to a new 1eb page, Most modern browsers also pro+ide a 1eb page composer, These are tools that help people create collections o) 1eb pages, A composer can! among other things! search )or words or replace one word with another, In short! 1eb pages are things that we should be able to represent on computers! and there are man$ )unctions that process 1eb pages, To simpli)$ our problem! we consider onl$ 1eb pages o) words and nested 1eb pages, @ne wa$ o) understanding such a page is as a se?uence o) words and 1eb pages, This in)ormal description suggests a natural representation o) 1eb pages as lists o) s$mbols! which represent words! and 1eb pages! which represent nested 1eb pages, A)ter all! we ha+e emphasi*ed be)ore that a list ma$ contain di))erent .inds o) things, Still! when we spell out this idea as a data de)inition! we get something rather unusual: A #eb-page /short: #*0 is either

(, empt2E &, !cons"s"wp# where s is a s$mbol and wp is a 1eb pageE or 5, !cons"ewp"wp# where both ewp and wp are 1eb pages, This data de)inition di))ers )rom that o) a list o) s$mbols in that it has three clauses instead o) two and that it has three sel)2re)erences instead o) one, @) these sel)2 re)erences! the one at the beginning o) a constructed list is the most unusual, 1e re)er to such 1eb pages as immediate!y embedded 1eb pages, Because the data de)inition is unusual! we construct some e8amples o) 1eb pages be)ore we continue, Here is a plain page:
'!;he";eachCchemeD"3roSect"aims"to"impro0e"the" ""pro8+em-so+0ing"and"organi@ation"s-i++s"of"high" ""schoo+"st.dents."It"pro0ides"software"and"+ect.re" ""notes"as"we++"as"e*ercises"and"so+.tions"for"teachers.#

It contains nothing but words, Here is a comple8 page:


'!;he";eachCcheme"Oe8"3age ""=ere"2o."can"find:" ""!Lect.reJotes"for";eachers# ""!G.idance"for"!DrCcheme:"a"Ccheme"programming"en0ironment## ""!5*ercise"Cets# ""!Co+.tions"for"5*ercises# "">or"f.rther"information:"write"to"schemeYcs#

The immediatel$ embedded pages start with parentheses and the s$mbols 'Lect.reJotes! 'G.idance! '5*ercises! and 'Co+.tions, The second embedded 1eb page contains another embedded page! which starts with the word 'DrCcheme, 1e sa$ this page is embedded with respect to the entire page, "etCs de+elop the )unction si@e! which consumes a 1eb page and produces the number o) words that it and all o) its embedded pages contain:
66"si@e":"O3""-/""n.m8er 66"to"co.nt"the"n.m8er"of"s2m8o+s"that"occ.r"in"a-wp !define"!si@e"a-wp#"...#

The two 1eb pages abo+e suggest two good e8amples! but the$ are too comple8, Here are three e8amples! one per subclass o) data:
!&"!si@e"empt2# """%# !&"!si@e"!cons"'Nne"empt2##

"""1# !&"!si@e"!cons"!cons"'Nne"empt2#"empt2## """1#

The )irst two e8amples are ob+ious, The third one deser+es a short e8planation, It is a 1eb page that contains one immediatel$ embedded 1eb page! and nothing else, The embedded 1eb page is the one o) the second e8ample! and it contains the one and onl$ s$mbol o) the third e8ample, To de+elop the template )or si@e! letCs care)ull$ step through the design recipe, The shape o) the data de)inition suggests that we need three cond2clauses: one )or the empt2 page! one )or a page that starts with a s$mbol! and one )or a page that starts with an embedded 1eb page, 1hile the )irst condition is the )amiliar test )or empt2! the second and third need closer inspection because both clauses in the data de)inition use cons! and a simple consA wonCt distinguish between the two )orms o) data, I) the page is not empt2! it is certainl$ constructed! and the distinguishing )eature is the )irst item on the list, In other words! the second condition must use a predicate that tests the )irst item on a-wp:
66"si@e":"O3""-/""n.m8er 66"to"co.nt"the"n.m8er"of"s2m8o+s"that"occ.r"in"a-wp !define"!si@e"a-wp#" ""!cond """"9!empt2A"a-wp#"...: """"9!s2m8o+A"!first"a-wp##"..."!first"a-wp#"..."!si@e"!rest"awp##"...: """"9else"..."!si@e"!first"a-wp##"..."!si@e"!rest"a-wp##"...:##

The rest o) the template is as usual, The second and third cond clauses contain selector e8pressions )or the )irst item and the rest o) the list, Because !rest"a-wp# is alwa$s a 1eb page and because !first"a-wp# is one in the third case! we also add a recursi+e call to si*e )or these selector e8pressions, Asing the e8amples and the template! we are read$ to design si@e: see )igure 5>, The di))erences between the de)inition and the template are minimal! which shows again how much o) a )unction we can design b$ merel$ thin.ing s$stematicall$ about the data de)inition )or its inputs,
66"si@e":"O3""-/""n.m8er 66"to"co.nt"the"n.m8er"of"s2m8o+s"that"occ.r"in"a-wp !define"!si@e"a-wp#" ""!cond """"9!empt2A"a-wp#"%: """"9!s2m8o+A"!first"a-wp##"!+"1"!si@e"!rest"a-wp###:

Velse /I /si*e /)irst a2wp00 /si*e /rest a2wp000W00 Figure !-' The de)inition o) si'e )or 1eb pages E ercise 1#<!<1< Brie)l$ e8plain how to de)ine si@e using its template and the e8amples, Test si@e using the e8amples )rom abo+e,

E ercise 1#<!<2< De+elop the )unction occ.rs1, The )unction consumes a 1eb page and a s$mbol, It produces the number o) times the s$mbol occurs in the 1eb page! ignoring the nested 1eb pages, De+elop the )unction occ.rs2, It is li.e occ.rs1! but counts a!! occurrences o) the s$mbol! including in embedded 1eb pages, Solution E ercise 1#<!<!< De+elop the )unction rep+ace, The )unction consumes two s$mbols! new and o+d! and a 1eb page! a-wp, It produces a page that is structurall$ identical to a-wp but with all occurrences o) o+d replaced b$ new, Solution E ercise 1#<!<#< People do not li.e deep 1eb trees because the$ re?uire too man$ page switches to reach use)ul in)ormation, For that reason a 1eb page designer ma$ also want to measure the depth o) a page, A page containing onl$ s$mbols has depth %, A page with an immediatel$ embedded page has the depth o) the embedded page plus 1, I) a page has se+eral immediatel$ embedded 1eb pages! its depth is the ma8imum o) the depths o) embedded 1eb pages plus 1, De+elop depth! which consumes a 1eb page and computes its depth, Solution

$)#) E,tended E,ercise. Evaluating Scheme


DrScheme is itsel) a program that consists o) se+eral parts, @ne )unction chec.s whether the de)initions and e8pressions we wrote down are grammatical Scheme e8pressions, Another one e+aluates Scheme e8pressions, 1ith what we ha+e learned in this section! we can now de+elop simple +ersions o) these )unctions, @ur )irst tas. is to agree on a data representation )or Scheme programs, In other words! we must )igure out how to represent a Scheme e8pression as a piece o) Scheme data, This sounds unusual! but it is not di))icult, Suppose we Fust want to represent numbers! +ariables! additions! and multiplications )or a start, Clearl$! numbers can stand )or numbers and s$mbols )or +ariables, Additions and multiplications! howe+er! call )or a class o) compound data because the$ consist o) an operator and two sube8pressions, A straight)orward wa$ to represent additions and multiplications is to use two structures: one )or additions and another one )or multiplications, Here are the structure de)initions:
!define-struct"add"!+eft"right## !define-struct"m.+"!+eft"right##

#ach structure has two components, @ne represents the le)t e8pression and the other one the right e8pression o) the operation,

Scheme e pression
3 * !*"3"1%# 3 K*

representation of Scheme e pression

!ma-e-m.+"3"1%#

!+"!*"3"3#"!*"4"4## !ma-e-add"!ma-e-m.+"3"3#"!ma-e-m.+"4"4## !+"!*"*"*#"!*"2"2## !ma-e-add"!ma-e-m.+"K*"K*#"!ma-e-m.+"K2"K2## !*"1/2"!*"3"3## !ma-e-m.+"1/2"!ma-e-m.+"3"3##

"etCs loo. at some e8amples: These e8amples co+er all cases: numbers! +ariables! simple e8pressions! and nested e8pressions, E ercise 1#<#<1< Pro+ide a data de)inition )or the representation o) Scheme e8pressions, Then translate the )ollowing e8pressions into representations: (, !+"1%"-1%# &, !+"!*"2%"3#"33# 5, !*"3.14"!*"r"r## 6, !+"!*",/5"c#"32# 7, !+"!*"3.14"!*"o"o##"!*"3.14"!*"i"i### Solution

A Scheme e+aluator is a )unction that consumes a representation o) a Scheme e8pression and produces its +alue, For e8ample! the e8pression 3 has the +alue 3! !+"3 5# has the +alue $! !+"!*"3"3#"!*"4"4## has the +alue 25! etc, Since we are ignoring de)initions )or now! an e8pression that contains a +ariable! )or e8ample! !+"3"*#! does not ha+e a +alueE a)ter all! we do not .now what the +ariable stands )or, In other words! our Scheme e+aluator should be applied onl$ to representations o) e8pressions that do not contain +ariables, 1e sa$ such e8pressions are n meric, E ercise 1#<#<2< De+elop the )unction n.mericA! which consumes /the representation o)0 a Scheme e8pression and determines whether it is numeric, Solution

E ercise 1#<#<!< Pro+ide a data de)inition )or numeric e8pressions, De+elop the )unction e0a+.ate-e*pression, The )unction consumes /the representation o)0 a numeric Scheme e8pression and computes its +alue, 1hen the )unction is tested! modi)$ it so it consumes all .inds o) Scheme e8pressionsE the re+ised +ersion raises an error when it encounters a +ariable, Solution E ercise 1#<#<#< 1hen people e+aluate an application !f"a# the$ substitute a )or fCs parameter in fCs bod$, More generall$! when people e+aluate e8pressions with +ariables! the$ substitute the +ariables with +alues, De+elop the )unction s.8st, The )unction consumes /the representation o)0 a +ariable /W0! a number /J0! and /the representation o)0 a Scheme e8pression, It produces a structurall$ e?ui+alent e8pression in which all occurrences o) W are substituted b$ J, Solution

Section 1$ /utuall% 0eferential Data Definitions


In the preceding section! we de+eloped data representations o) )amil$ trees! 1eb pages! and Scheme e8pressions, De+eloping )unctions )or these data de)initions was based on one and the same design recipe, I) we wish to de+elop more realistic representations o) 1eb pages or Scheme e8pressions! or i) we wish to stud$ descendant )amil$ trees rather than ancestor trees! we must learn to describe classes o) data that are interrelated, That is! we must )ormulate se+eral data de)initions at once where the data de)initions not onl$ re)er to themsel+es! but also re)er to other data de)initions,

$*#$ Lists of Structures2 Lists in Structures


1hen we build a )amil$ tree retroacti+el$! we o)ten start )rom the childCs perspecti+e and proceed )rom there to parents! grandparents! etc, As we construct the tree! we write down who is whose child rather than who is whose parents, 1e build a descendant fami!y tree, Drawing a descendant tree proceeds Fust li.e drawing an ancestor tree! e8cept that all arrows are re+ersed, Figure 6' represents the same )amil$ as that o) )igure 57! but drawn )rom the descendant perspecti+e,

Figure #.' A descendant )amil$ tree

Representing these new .inds o) )amil$ trees and their nodes in a computer re?uires a di))erent class o) data than do the ancestor )amil$ trees, This time a node must include in)ormation about the children instead o) the two parents, Here is a structure de)inition:
!define-struct"parent"!chi+dren"name"date"e2es##

The last three )ields in a parent structure contain the same basic in)ormation as a corresponding child structure! but the contents o) the )irst one poses an interesting ?uestion, Since a parent ma$ ha+e an arbitrar$ number o) children! the chi+dren )ield must contain an undetermined number o) nodes! each o) which represents one child, The natural choice is to insist that the chi+dren )ield alwa$s stands )or a list o) parent structures, The list represents the childrenE i) a person doesnCt ha+e children! the list is empt2, This decision suggests the )ollowing data de)inition: A parent is a structure: where +oc is a list o) a number, An)ortunatel$! this data de)inition +iolates our criteria concerning de)initions, In particular! it mentions the name o) a collection that is not $et de)ined: list o) children, Since it is impossible to de)ine the class o) parents without .nowing what a list o) children is! letCs start )rom the latter: A !ist of chi!dren is either (, empt2 or &, !cons"p"+oc# where p is a parent and +oc is a list o) children, This second de)inition loo.s standard! but it su))ers )rom the same problem as the one )or parents, The un.nown class it re)ers to is that o) the class o) parents! which cannot be de)ined without a de)inition )or the list o) children! and so on, The conclusion is that the two data de)initions re)er to each other and are onl$ meaning)ul i) introduced together: A parent is a structure:
!ma-e-parent"+oc"n"d"e# !ma-e-parent"+oc"n"d"e# children! n and e are s$mbols! and d is

where +oc is a list o) children! n and e are s$mbols! and d is a number, A !ist-of-chi!dren is either (, empt2 or

&, !cons"p"+oc# where p is a parent and +oc is a list o) children, 1hen two /or more0 data de)initions re)er to each other! the$ are said to be MATAA""3 R#CARSI4# or MATAA""3 R#F#R#-TIA", -ow we can translate the )amil$ tree o) )igure 6' into our Scheme data language, Be)ore we can create a parent structure! o) course! we must )irst de)ine all o) the nodes that represent children, And! Fust as in section (6,(! the best wa$ to do this is to name a parent structure be)ore we reuse it in a list o) children, Here is an e8ample:
!define"G.sta0"!ma-e-parent"empt2"'G.sta0"1,$$"'8rown## !ma-e-parent"!+ist"G.sta0#"'>red"1,5%"'2e++ow#

To create a parent structure )or Fred! we )irst de)ine one )or =usta+ so that we can )orm !+ist"G.sta0#! the list o) children )or Fred, Figure 6( contains the complete Scheme representation )or our descendant tree, To a+oid repetitions! it also includes de)initions )or lists o) children, Compare the de)initions with )igure 59 /see page (>0! which represents the same )amil$ as an ancestor tree,
66"Io.ngest"Generation: !define"G.sta0"!ma-e-parent"empt2"'G.sta0"1,$$"'8rown## !define">redU50a"!+ist"G.sta0## 66"Hidd+e"Generation: !define"'dam"!ma-e-parent"empt2"''dam"1,5%"'2e++ow## !define"Da0e"!ma-e-parent"empt2"'Da0e"1,55"'8+ac-## !define"50a"!ma-e-parent">redU50a"'50a"1, 5"'8+.e## !define">red"!ma-e-parent">redU50a"'>red"1, "'pin-## !define"7ar+U(ettina"!+ist"'dam"Da0e"50a## 66"N+dest"Generation: !define"7ar+"!ma-e-parent"7ar+U(ettina"'7ar+"1,2 "'green##

/define Bettina /ma.e2parent CarlGBettina =Bettina (>&9 =green00 Figure #1' A Scheme representation o) the descendant )amil$ tree "et us now stud$ the de+elopment o) 8+.e-e2ed-descendantA! the natural companion o) 8+.e-e2ed-ancestorA, It consumes a parent structure and determines whether it or an$ o) its descendants has blue e$es:
66"8+.e-e2ed-descendantA":"parent""-/""8oo+ean 66"to"determine"whether"a-parent"or"an2"of"its"descendants !chi+dren<" 66"grandchi+dren<"and"so"on#"ha0e"'8+.e"in"the"e2es"fie+d !define"!8+.e-e2ed-descendantA"a-parent#"...#

Here are three simple e8amples! )ormulated as tests:

!8oo+ean&A"!8+.e-e2ed-descendantA"G.sta0#"fa+se# !8oo+ean&A"!8+.e-e2ed-descendantA"50a#"tr.e# !8oo+ean&A"!8+.e-e2ed-descendantA"(ettina#"tr.e#

A glance at )igure 6' e8plains the answers in each case, According to our rules! the template )or 8+.e-e2ed-descendantA is simple, Since its input is a plain class o) structures! the template contains nothing but selector e8pressions )or the )ields in the structure:
!define"!8+.e-e2ed-descendantA"a-parent# ""..."!parent-chi+dren"a-parent#"..." ""..."!parent-name"a-parent#"..." ""..."!parent-date"a-parent#"..." ""..."!parent-e2es"a-parent#"..."#

The structure de)inition )or parent speci)ies )our )ields so there are )our e8pressions, The e8pressions in the template remind us that the e$e color o) the parent is a+ailable and can be chec.ed, Hence we add a cond2e8pression that compares !parent-e2es"aparent# to '8+.e:
!define"!8+.e-e2ed-descendantA"a-parent# ""!cond """"9!s2m8o+&A"!parent-e2es"a-parent#"'8+.e#"tr.e: """"9else" """"""..."!parent-chi+dren"a-parent#"..." """"""..."!parent-name"a-parent#"..." """"""..."!parent-date"a-parent#"...:##

The answer is tr.e i) the condition holds, The else clause contains the remaining e8pressions, The name and date )ield ha+e nothing to do with the e$e color o) a person! so we can ignore them, This lea+es us with
!parent-chi+dren"a-parent#

an e8pression that e8tracts the list o) children )rom the parent structure, I) the e$e color o) some parent structure is not '8+.e! we must clearl$ search the list o) children )or a blue2e$ed descendant, Following our guidelines )or comple8 )unctions! we add the )unction to our wish list and continue )rom there, The )unction that we want to put on a wish list consumes a list o) children and chec.s whether an$ o) these or their grandchildren has blue e$es, Here are the contract! header! and purpose statement:
66"8+.e-e2ed-chi+drenA":"+ist-of-chi+dren""-/""8oo+ean 66"to"determine"whether"an2"of"the"str.ct.res"on"a+oc"is"8+.e-e2ed 66"or"has"an2"8+.e-e2ed"descendant !define"!8+.e-e2ed-chi+drenA"a+oc#"...#

Asing 8+.e-e2ed-chi+drenA we can complete the de)inition o) 8+.e-e2eddescendantA:

!define"!8+.e-e2ed-descendantA"a-parent# ""!cond """"9!s2m8o+&A"!parent-e2es"a-parent#"'8+.e#"tr.e: """"9else"!8+.e-e2ed-chi+drenA"!parent-chi+dren"a-parent##:##

That is! i) a-parent doesnCt ha+e blue e$es! we Fust loo. through the list o) its children, Be)ore we can test 8+.e-e2ed-descendantA! we must de)ine the )unction on our wish list, To ma.e up e8amples and tests )or 8+.e-e2ed-chi+drenA! we use the list2o)2 children de)initions in )igure 6(:
!not"!8+.e-e2ed-chi+drenA"!+ist"G.sta0### !8+.e-e2ed-chi+drenA"!+ist"'dam"Da0e"50a##

=usta+ doesnCt ha+e blue e$es and doesnCt ha+e an$ recorded descendants, Hence! 8+.ee2ed-chi+drenA produces fa+se )or !+ist"G.sta0#, In contrast! 50a has blue e$es! and there)ore 8+.e-e2ed-chi+drenA produces tr.e )or the second list o) children, Since the input )or 8+.e-e2ed-chi+drenA is a list! the template is the standard pattern:
!define"!8+.e-e2ed-chi+drenA"a+oc# ""!cond """"9!empt2A"a+oc#"...: """"9else """"""..."!first"a+oc#"... """"""..."!8+.e-e2ed-chi+drenA"!rest"a+oc##"...:##

-e8t we consider the two cases, I) 8+.e-e2ed-chi+drenACs input is empt2! the answer is fa+se, @therwise we ha+e two e8pressions: (, !first"a+oc#! which e8tracts the )irst item! a parent structure! )rom the listE and &, !8+.e-e2ed-chi+drenA"!rest"a+oc##! which determines whether an$ o) the structures on a+oc is blue2e$ed or has an$ blue2e$ed descendant, Fortunatel$ we alread$ ha+e a )unction that determines whether a parent structure or an$ o) its descendants has blue e$es: 8+.e-e2ed-descendantA, This suggests that we chec. whether
!8+.e-e2ed-descendantA"!first"a+oc##

holds and! i) so! 8+.e-e2ed-chi+drenA can produce tr.e, I) not! the second e8pression determines whether we ha+e more luc. with the rest o) the list, Figure 6& contains the complete de)initions )or both )unctions: 8+.e-e2eddescendantA and 8+.e-e2ed-chi+drenA, Anli.e an$ other group o) )unctions! these

two )unctions re)er to each other, The$ are MATAA""3 R#CARSI4#, -ot surprisingl$! the mutual re)erences in the de)initions match the mutual re)erences in data de)initions, The )igure also contains a pair o) alternati+e de)initions that use or instead o) nested cond2e8pressions,
66"8+.e-e2ed-descendantA":"parent""-/""8oo+ean 66"to"determine"whether"a-parent"an2"of"the"descendants"!chi+dren< 66"grandchi+dren<"and"so"on#"ha0e"'8+.e"in"the"e2es"fie+d !define"!8+.e-e2ed-descendantA"a-parent# ""!cond """"9!s2m8o+&A"!parent-e2es"a-parent#"'8+.e#"tr.e: """"9else"!8+.e-e2ed-chi+drenA"!parent-chi+dren"a-parent##:## 66"8+.e-e2ed-chi+drenA":"+ist-of-chi+dren""-/""8oo+ean 66"to"determine"whether"an2"of"the"str.ct.res"in"a+oc"is"8+.e-e2ed 66"or"has"an2"8+.e-e2ed"descendant !define"!8+.e-e2ed-chi+drenA"a+oc# ""!cond """"9!empt2A"a+oc#"fa+se: """"9else """"""!cond """"""""9!8+.e-e2ed-descendantA"!first"a+oc##"tr.e: """"""""9else"!8+.e-e2ed-chi+drenA"!rest"a+oc##:#:## 66"8+.e-e2ed-descendantA":"parent""-/""8oo+ean 66"to"determine"whether"a-parent"an2"of"the"descendants"!chi+dren< 66"grandchi+dren<"and"so"on#"ha0e"'8+.e"in"the"e2es"fie+d !define"!8+.e-e2ed-descendantA"a-parent# ""!or"!s2m8o+&A"!parent-e2es"a-parent#"'8+.e# """"""!8+.e-e2ed-chi+drenA"!parent-chi+dren"a-parent#### 66"8+.e-e2ed-chi+drenA":"+ist-of-chi+dren""-/""8oo+ean 66"to"determine"whether"an2"of"the"str.ct.res"in"a+oc"is"8+.e-e2ed 66"or"has"an2"8+.e-e2ed"descendant !define"!8+.e-e2ed-chi+drenA"a+oc# ""!cond """"9!empt2A"a+oc#"fa+se: """"9else"!or"!8+.e-e2ed-descendantA"!first"a+oc##

/blue2e$ed2childrenH /rest aloc000W00 Figure #2' Two programs )or )inding a blue2e$ed descendant E ercise 1$<1<1< #+aluate !8+.e-e2ed-descendantA"50a# b$ hand, Then e+aluate !8+.e-e2ed-descendantA"(ettina#, Solution E ercise 1$<1<2< De+elop the )unction how-far-remo0ed, It determines how )ar a blue2e$ed descendant! i) one e8ists! is remo+ed )rom the gi+en parent, I) the gi+en parent has blue e$es! the distance is %E i) e2es is not blue but at least one its childrenCs e$es are! the distance is 1E and so on, I) no descendant o) the gi+en parent has blue e$es! the )unction returns fa+se when it is applied to the corresponding )amil$ tree, Solution E ercise 1$<1<!< De+elop the )unction co.nt-descendants! which consumes a parent and produces the number o) descendants! including the parent,

De+elop the )unction co.nt-proper-descendants! which consumes a parent and produces the number o) proper descendants! that is! all nodes in the )amil$ tree! not counting the parent, Solution E ercise 1$<1<#< De+elop the )unction e2e-co+ors! which consumes a parent and produces a list o) all e$e colors in the tree, An e$e color ma$ occur more than once in the list, >int' Ase the Scheme operation append! which consumes two lists and produces the concatenation o) the two lists, Solution

$*#" Designing +unctions for /utually Referential Definitions


The recipe )or designing )unctions on mutuall$ re)erential data de)initions generali*es that )or sel)2re)erential data, Indeed! it o))ers onl$ two pieces o) additional ad+ice, First! we must create severa! templates simultaneousl$! one )or each data de)inition, Second! we must annotate templates with sel)2re)erences and CR@SS2R#F#R#-C#S! that is! re)erences among di))erent templates, Here is a more detailed e8planation o) the di))erences: The data anal%sis and design' I) a problem mentions a number o) di))erent classes o) in)ormation /o) arbitrar$ si*e0! we need a group o) data de)initions that are sel)2re)erential and that re)er to each other, In these groups! we identi)$ the sel)2re)erences and the cross2 re)erences between two data de)initions, In the abo+e e8ample! we needed two interrelated de)initions:

The )irst one concerns parents and another one )or list o) children, The )irst /unconditionall$0 de)ines a parent in terms o) s$mbols! numbers! and a list o) children! that is! it contains a cross2re)erence to the second de)inition, This second de)inition is a conditional de)inition, Its )irst clause is simpleE its second clause re)erences both the de)inition )or parents and +ist-of-chi+dren, Contract, Purpose, >eader'

To process interrelated classes o) data! we t$picall$ need as man$ )unctions as there are class de)initions, Hence! we must )ormulate as man$ contracts! purpose statements! and headers in parallel as there are data de)initions, Templates' The templates are created in parallel! )ollowing the ad+ice concerning compound data! mi8ed data! and sel)2re)erential data, Finall$! we must determine )or each selector e8pression in each template whether it corresponds to a cross2re)erence to some de)inition, I) so! we annotate it in the same wa$ we annotate cross2 re)erences, Here are the templates )or our running e8ample:

The f.n-parent template is unconditional because the data de)inition )or parents does not contain an$ clauses, It contains a cross2re)erence to the second template: to process the chi+dren )ield o) a parent structure, B$ the same rules! f.n-chi+dren is conditional, The second cond2clause contains one sel)2 re)erence! )or the rest o) the list! and one cross2re)erence )or the first item o) the list! which is a parent structure, A comparison o) the data de)initions and the templates shows how analogous the two are, To emphasi*e the similarit$ in sel)2re)erences and cross2re)erences! the data de)initions and templates ha+e been annotated with arrows, It is eas$ to see how corresponding arrows ha+e the same origin and destination in the two pictures, The bod%' As we proceed to create the )inal de)initions! we start with a template or a cond2 clause that does not contain sel)2re)erences to the template and cross2re)erences to other templates, The results are t$picall$ eas$ to )ormulate )or such templates or cond2clauses, The rest o) this step proceeds as be)ore, 1hen we deal with other clauses or )unctions! we remind oursel+es what each e8pression in the template computes! assuming that a!! )unctions alread$ wor. as speci)ied in the contracts, Then we decide how to combine these pieces o) data into a )inal answer, As we do that! we must not )orget the guidelines concerning the composition o) comple8 )unctions /sections ;,5 and (&0,

Figure 65 summari*es the e8tended design recipe, Phase Data Anal$sis and Design Template =oal to )ormulate a group o) related data de)initions to )ormulate a group o) )unction outlines Acti+it$ de+elop a group o) mutuall$ recursi+e data de)initions at least one de)inition or one alternati+e in a de)inition must re)er to basic data e+p!icit!y identify a!! references among the data definitions de+elop as many temp!ates as there are data definitions sim !taneo s!y de+elop each templates according to the rules )or compound andKor mi8ed data de)initions as appropriate annotate the templates with recursions and cross2applications to match the /cross20re)erences in the data de)initions )ormulate a Scheme e8pression )or each template! and )or each cond2clause in a template e8plain what each e8pression in each template computes use additional au8iliar$ )unctions where necessar$

Bod$

to de)ine a group o) )unctions

Figure #!' Designing groups o) )unctions )or groups o) data de)initions the essential stepsE )or others see )igures 6 /pg, 70! (& /pg, >0! and (< /pg, ('0

$*#( E,tended E,ercise. /ore on We& Pages


1ith mutuall$ re)erential data de)initions we can represent 1eb pages in a more accurate manner than in section (6,5, Here is the basic structure de)inition:
!define-struct"wp"!header"8od2##

The two )ields contain the two essential pieces o) data in a 1eb page: a header and a 8od2, The data de)inition speci)ies that a bod$ is a list o) words and 1eb pages: A #eb-page /short: #*0 is a structure:
!ma-e-wp"h"p#

where h is a s$mbol and p is a /1eb0 document, A /#eb0 doc ment is either (, empt2! &, !cons"s"p# where s is a s$mbol and p is a document! or

5, !cons"w"p# where w is a 1eb page and p is a document, E ercise 1$<!<1< De+elop the )unction si@e! which consumes a 1eb page and produces the number o) s$mbols /words0 it contains, Solution E ercise 1$<!<2< De+elop the )unction wp-to-fi+e, The )unction consumes a 1eb page and produces a list o) s$mbols, The list contains all the words in a bod$ and all the headers o) embedded 1eb pages, The bodies o) immediatel$ embedded 1eb pages are ignored, Solution E ercise 1$<!<!< De+elop the )unction occ.rs, It consumes a s$mbol and a 1eb page and determines whether the )ormer occurs an$where in the latter! including the embedded 1eb pages, Solution E ercise 1$<!<#< De+elop the program find, The )unction consumes a 1eb page and a s$mbol, It produces fa+se! i) the s$mbol does not occur in the bod$ o) the page or its embedded 1eb pages, I) the s$mbol occurs at least once! it produces a list o) the headers that are encountered on the wa$ to the s$mbol, >int' De)ine an au8iliar$ li.e find that produces onl$ tr.e when a 1eb page contains the desired word, Ase it to de)ine find, Alternati+el$! use 8oo+eanA to determine whether a natural recursion o) find produced a list or a boolean, Then compute the result again, 1e will discuss this second techni?ue! called bac.trac.ing! in the interme**o at the end o) this part, Solution

Section 1& De1elopment through Iterati1e 0efinement


1hen we de+elop real )unctions! we are o)ten con)ronted with the tas. o) designing a data representation )or complicated )orms o) in)ormation, The best strateg$ to approach this tas. is appl$ a well2.nown scienti)ic techni?ue: IT#RATI4# R#FI-#M#-T, A scientistCs problem is to represent a part o) the real world using mathematics, The result o) the e))ort is called a M@D#", The scientist then tests the model in man$ wa$s! in particular b$ predicting certain properties o) e+ents, I) the model trul$ captured the essential elements o) the real world! the prediction will be accurateE otherwise! there will be discrepancies between the predictions and the actual outcomes, For e8ample! a ph$sicist ma$ start b$ representing a Fet plane as a point and b$ predicting its mo+ement in a straight line using -ewtonCs e?uations, "ater! i) there is a need to understand the planeCs )riction! the ph$sicist ma$ add certain aspects o) the Fet planeCs contour to the model, In general! a scientist re)ines a model and retests its use)ulness until it is su))icientl$ accurate, A programmer or a computing scientist should proceed li.e a scientist, Since the representation o) data pla$s a central role in the wor. o) a programmer! the .e$ is to )ind an accurate data representation o) the real2world in)ormation, The best wa$ to get there in complicated situations is to de+elop the representation in an iterati+e manner! starting with the essential elements and adding more attributes when the current model is )ull$ understood, In this boo.! we ha+e encountered iterati+e re)inement in man$ o) our e8tended e8ercises, For e8ample! the e8ercise on mo+ing pictures started with simple circles and rectanglesE later on we de+eloped programs )or mo+ing entire lists o) shapes, Similarl$! we )irst introduced 1eb pages as a list o) words and embedded 1eb pagesE in section (7,5 we re)ined the representation o) embedded 1eb pages, For all o) these e8ercises! howe+er! the re)inement was built into the presentation, This section illustrates iterati+e re)inement as a principle o) program de+elopment, The goal is to model a )ile s$stem, A )ile s$stem is that part o) the computer that remembers programs and data when the computer is turned o)), 1e )irst discuss )iles in more detail and then iterati+el$ de+elop three data representations, The last part o) the section suggests some programming e8ercises )or the )inal model, 1e will use iterati+e re)inement again in later sections,

$-#$ Data

nalysis

1hen we turn a computer o))! it should remember the )unctions and the data we wor.ed on, @therwise we ha+e to reenter e+er$thing when we turn it on again, Things that a computer is to remember )or a long time are put into fi!es, A )ile is a se?uence o) small pieces o) data, For our purposes! a )ile resembles a listE we ignore wh$ and how a computer stores a )ile in a permanent manner,

Figure ##' A sample director$ tree It is more important to us that! on most computer s$stems! the collection o) )iles is organi*ed in directories,6' Roughl$ spea.ing! a director$ contains some )iles and some more directories, The latter are called subdirectories and ma$ contain $et more subdirectories and )iles! and so on, The entire collection is collecti+el$ called a fi!e system or a directory tree, Figure 66 contains a graphical s.etch o) a small director$ tree,6( The treeCs root directory is ;C, It contains one )ile! called readD! and two subdirectories! called ;e*t and Li8s, The )irst subdirector$! ;e*t! contains onl$ three )ilesE the latter! Li8s! contains onl$ two subdirectories! each o) which contains at least one )ile, #ach bo8 has one o) two annotations, A director$ is annotated with DIR! and a )ile is annotated with a number! which signi)ies the )ileCs si*e, Altogether ;C contains se+en )iles and consists o) )i+e /sub0directories, E ercise 1&<1<1< How man$ times does a )ile name readD occur in the director$ tree ;C H 1hat is the total si*e o) all the )iles in the treeH How deep is the tree /how man$ le+els does it contain0H Solution

$-#" Defining Data Classes and Refining Them


"etCs de+elop a data representation )or )ile s$stems using the method o) iterati+e re)inement, The )irst decision we need to ma.e is what to )ocus on and what to ignore,

Consider the director$ tree in )igure 66 and letCs imagine how it is created, 1hen a user )irst creates a director$! it is empt$, As time goes b$! the user adds )iles and directories, In general! a user re)ers to )iles b$ names but thin.s o) directories as containers o) other things, /odel 1: @ur thought e8periment suggests that our )irst and most primiti+e model should )ocus on )iles as atomic entities! sa$! a s$mbol that represents a )ileCs name! and on the directoriesC nature as containers, More concretel$! we should thin. o) a director$ as Fust a list that contains )iles and directories, All o) this suggests the )ollowing two data de)initions: A fi!e is a s$mbol, A directory /short: dir0 is either (, empt2E &, !cons"f"d# where f is a fi+e and d is a dirE or 5, !cons"d1"d2# where d1 and d2 are dirs, The )irst data de)inition sa$s that )iles are represented b$ their names, The second one captures how a director$ is graduall$ constructed b$ adding )iles and directories, A closer loo. at the second data de)inition shows that the class o) directories is the class o) 1eb pages o) section (6,5, Hence we can reuse the template )or 1eb2page processing )unctions to process director$ trees, I) we were to write a )unction that consumes a director$ /tree0 and counts how man$ )iles are contained! it would be identical to a )unction that counts the number o) words in a 1eb tree, E ercise 1&<2<1< Translate the )ile s$stem in )igure 66 into a Scheme representation according to model (, Solution E ercise 1&<2<2< De+elop the )unction how-man2! which consumes a dir and produces the number o) )iles in the dir tree, Solution

/odel 2: 1hile the )irst data de)inition is )amiliar to us and eas$ to use! it obscures the nature o) directories, In particular! it hides the )act that a director$ is not Fust a collection o) )iles and directories but has se+eral interesting attributes, To model directories in a more )aith)ul manner! we must introduce a structure that collects all rele+ant properties o) a director$, Here is a minimal structure de)inition:
!define-struct"dir"!name"content##

It suggests that a director$ has a name and a contentE other attributes can now be added as needed, The intention o) the new de)inition is that a director$ has two attributes: a name! which is a s$mbol! and a content! which is a list o) )iles and directories, This! in turn! suggests the )ollowing data de)initions: A directory /short: dir0 is a structure:
!ma-e-dir"n"c#

where n is a s$mbol and c is a list o) )iles and directories, A !ist-of-fi!es-and-directories /short: L8900 is either (, empt2E &, !cons"f"d# where f is a )ile and d is a LN>DE or 5, !cons"d1"d2# where d1 is a dir and d2 is a LN>D, Since the data de)inition )or dir re)ers to the de)inition )or LN>Ds! and the de)inition )or LN>Ds re)ers bac. to that o) dirs! the two are mutuall$ recursi+e de)initions and must be introduced together, Roughl$ spea.ing! the two de)initions are related li.e those o) parent and +ist-ofchi+dren in section (7,(, This! in turn! means that the design recipe )or programming )rom section (7,& directl$ applies to dirs and LN>Ds, More concretel$! to design a )unction that processes dirs! we must de+elop templates )or dir2processing )unctions and LN>D2processing )unctions in parallel, E ercise 1&<2<!< Show how to model a director$ with two more attributes: a si*e and a s$stems attribute, The )ormer measures how much space the director$ itsel) /as opposed to its )iles and subdirectories0 consumesE the latter speci)ies whether the director$ is recogni*ed b$ the operating s$stem, Solution

E ercise 1&<2<#< Translate the )ile s$stem in )igure 66 into a Scheme representation according to model &, Solution E ercise 1&<2<$< De+elop the )unction how-man2! which consumes a dir according to model & and produces the number o) )iles in the dir tree, Solution /odel !: The second data de)inition re)ined the )irst one with the introduction o) attributes )or directories, Files also ha+e attributes, To model those! we proceed Fust as abo+e, First! we de)ine a structure )or )iles:
!define-struct"fi+e"!name"si@e"content##

Second! we pro+ide a data de)inition: A fi!e is a structure: where n is a s$mbol! s is


!ma-e-fi+e"n"s"*# a number! and * is some Scheme

+alue,

For now! we thin. o) the content )ield o) a )ile as set to empt2, "ater! we will discuss how to get access to the data in a )ile, Finall$! letCs split the content )ield o) dirs into two pieces: one )or a list o) )iles and one )or a list o) subdirectories, The data de)inition )or a list o) )iles is straight)orward and relies on nothing but the de)inition )or fi+es: A !ist-of-fi!es is either (, empt2! or &, !cons"s"+of# where s is a fi+e and +of is a list o) )iles, In contrast! the data de)initions )or dirs and its list o) subdirectories still re)er to each other and must there)ore be introduced together, @) course! we )irst need a structure de)inition )or dirs that has a )ield )or )iles and another one )or subdirectories:
!define-struct"dir"!name"dirs"fi+es##

Here are the data de)initions: A dir is a structure:


!ma-e-dir"n"ds"fs#

where n is a s$mbol! ds is a list o) directories! and fs is a list o) )iles,

A !ist-of-directories is either (, empt2 or &, !cons"s"+od# where s is a dir and +od is a list o) directories, This third model /or data representation0 o) a director$ hierarch$ captures the nature o) a )ile s$stem as a user t$picall$ percei+es it, 1ith two structure de)initions and )our data de)initions! it is! howe+er! )ar more complicated than the )irst model, But! b$ starting with a the simple representation o) the )irst model and re)ining it step b$ step! we ha+e gained a good understanding o) how to wor. with this comple8 web o) classes, It is now our Fob to use the design recipe )rom section (7,& )or de+eloping )unctions on this set o) data de)initions, @therwise! we cannot hope to understand our )unctions at all,

$-#( Refining +unctions and Programs


The goal o) the )ollowing se?uence o) e8ercises is to de+elop se+eral common utilit$ )unctions )or director$ and )ile s$stems! using our third and most re)ined model, #+en though these )unctions process Scheme2based representations o) )iles and directories! the$ gi+e us a good idea how such real2world programs wor., E ercise 1&<!<1< Translate the )ile s$stem in )igure 66 into a Scheme representation, Remember to use empt2 )or the content o) the )iles, Solution To ma.e the e8ercise more realistic! DrScheme supports the teachpac. dir.ss, It introduces the two necessar$ structure de)initions and a )unction to create representations o) directories according to our third model:
66"create-dir":"string""-/""dir 66"to"create"a"representation"of"the"director2"that"a-path specifies: 66"1."Oindows:"!create-dir"1c:ZZwindows1#" 66"2."Hac:"!create-dir"1H2"Dis-:1#" 66"3."Pni*:"!create-dir"1/home/scheme/1# !define"!create-dir"a-path#"...#

Ase the )unction to create some small and large e8amples based on the directories in a real computer, @arning: For large director$ trees! DrScheme ma$ need a lot o) time to build a representation, Ase create-dir on small director$ trees )irst, Do not de)ine $our own dir structures, E ercise 1&<!<2< De+elop the )unction how-man2! which consumes a dir /according to model 50 and produces the number o) )iles in the dir tree, Test the )unction on the

directories created in e8ercise (9,5,(, 1h$ are we con)ident that the )unction produces correct resultsH Solution E ercise 1&<!<!< De+elop the )unction d.-dir, The )unction consumes a director$ and computes the total si*e o) all the )iles in the entire director$ tree, This )unction appro8imates a true dis.2usage meter in that it assumes that directories donCt re?uire storage, Re)ine the )unction to compute appro8imate si*es )or subdirectories, "etCs assume that storing a )ile and a director$ in a dir structure costs 1 storage unit, Solution E ercise 1&<!<#< De+elop the )unction findA! which consumes a dir and a )ile name and determines whether or not a )ile with this name occurs in the director$ tree, Challenge: De+elop the )unction find, It consumes a director$ d and a )ile name f, I) !findA"d"f# is true! it produces a path to the )ileE otherwise it produces fa+se, A path is a list o) director$ names, The )irst one is that o) the gi+en director$E the last one is that o) the subdirector$ whose fi+es list contains f, For e8ample:
!find";C"'part3# 66"e*pected"0a+.e:" !+ist"';C"';e*t# !find";C"'readD# 66"e*pected"0a+.e:" !+ist"';C#

assuming ;C is defined to be the director$ in )igure 66, 1hich readD )ile in )igure 66 should find disco+erH =enerali*e the )unction to return a list o) paths i) the )ile name occurs more than once, #ach path should lead to a di))erent occurrence! and there should be a path )or each occurrence, Solution @n some computers! a director$ is called a fo!der, The picture e8plains wh$ computer scientists call such directories trees,

6'

6(

Section 1( Processing T3o Comple Pieces of Data


@n occasion! a )unction consumes two arguments that belong to classes with non2tri+ial data de)initions, In some cases! one o) the arguments should be treated as i) it were atomicE a precisel$ )ormulated purpose statement t$picall$ clari)ies this, In other cases! the two arguments must be processed in loc.step, Finall$! in a )ew rare cases! the )unction must ta.e into account all possible cases and process the arguments accordingl$, This section illustrates the three cases with e8amples and pro+ides an augmented design recipe )or the last one, The last section discusses the e?ualit$ o) compound data and its relationship to testingE it is essential )or automating test suites )or )unctions,

$0#$ Processing T!o Lists Simultaneously. Case $


Consider the )ollowing contract! purpose statement! and header:
66"rep+ace-eo+-with":"+ist-of-n.m8ers"+ist-of-n.m8ers""-/""+istof-n.m8ers 66"to"constr.ct"a"new"+ist"82"rep+acing"empt2"in"a+on1"with"a+on2 !define"!rep+ace-eo+-with"a+on1"a+on2#"...#

The contract sa$s that the )unction consumes two lists! which we ha+enCt seen in the past, "etCs see how the design recipe wor.s in this case, First! we ma.e up e8amples, Suppose the )irst input is empt2, Then rep+ace-eo+-with should produce the second argument! no matter what it is:
""!rep+ace-eo+-with"empt2"L#" &"L

In this e?uation! L stands )or an arbitrar$ list o) numbers, -ow suppose the )irst argument is not empt2, Then the purpose statement re?uires that we replace empt2 at the end o) a+on1 with a+on2:
!rep+ace-eo+-with"!cons"1"empt2#"L#" 66"e*pected"0a+.e: !cons"1"L# !rep+ace-eo+-with"!cons"2"!cons"1"empt2##"L#" 66"e*pected"0a+.e: !cons"2"!cons"1"L## !rep+ace-eo+-with"!cons"2"!cons"11"!cons"1"empt2###"L#" 66"e*pected"0a+.e:" !cons"2"!cons"11"!cons"1"L###

Again! L stands )or an$ list o) numbers in these e8amples,


66"rep+ace-eo+-with":"+ist-of-n.m8ers"+ist-of-n.m8ers""-/""+istof-n.m8ers 66"to"constr.ct"a"new"+ist"82"rep+acing"empt2"in"a+on1"with"a+on2 !define"!rep+ace-eo+-with"a+on1"a+on2# ""!cond """"!!empt2A"a+on1#"a+on2#

/else /cons /)irst alon(0 /replace2eol2with /rest alon(0 alon&00000 Figure #$' The complete de)inition o) rep!ace-eo!--ith The e8amples suggest that it doesnCt matter what the second argument is 22 as long as it is a listE otherwise! it doesnCt e+en ma.e sense to replace empt2 with the second argument, This implies that the template should be that o) a list2processing )unction with respect to the )irst argument:
!define"!rep+ace-eo+-with"a+on1"a+on2# ""!cond """"!!empt2A"a+on1#"...# """"!else"..."!first"a+on1#"..."!rep+ace-eo+-with"!rest"a+on1# a+on2#"..."###

The second argument is treated as it were an atomic piece o) data, "etCs )ill the gaps in the template! )ollowing the design recipe and using our e8amples, I) a+on1 is empt2! rep+ace-eo+-with produces a+on2 according to our e8amples, For the second cond2clause! when a+on1 is not empt2! we must proceed b$ inspecting the a+ailable e8pressions: (, !first"a+on1# e+aluates to the )irst item on the list! and &, !rep+ace-eo+-with"!rest"a+on1#"a+on2# replaces empt2 in !rest"a+on1# with a+on2, To gain a better understanding o) what this means! consider one o) the e8amples:
!rep+ace-eo+-with"!cons"2"!cons"11"!cons"1"empt2###"L#" 66"e*pected"0a+.e:" !cons"2"!cons"11"!cons"1"L###

Here !first"a+on1# is 2! !rest"a+on1# is !cons"11"!cons"1"empt2##! and !rep+ace-eo+-with"!rest"a+on1#"a+on2# is !cons"11"!cons"1"a+on2##, 1e can combine 2 and the latter with cons and can thus obtain the desired result, More generall$!
!cons"!first"a+on1#"!rep+ace-eo+-with"!rest"a+on1#"a+on2##

is the answer in the second cond2clause, Figure 67 contains the complete de)inition,

E ercise 1(<1<1< In se+eral e8ercises! we ha+e used the Scheme operation append! which consumes three lists and Fu8taposes their items:
!append"!+ist"'a#"!+ist"'8"'c#"!+ist"'d"'e"'f## 66"e*pected"0a+.e:" !+ist"'a"'8"'c"'d"'e"'f#

Ase rep+ace-eo+-with to de)ine o.r-append! which acts Fust li.e SchemeCs append, Solution E ercise 1(<1<2< De+elop cross, The )unction consumes a list o) s$mbols and a list o) numbers and produces all possible pairs o) s$mbols and numbers, #8ample:
!cross"'!a"8"c#"'!1"2## 66"e*pected"0a+.e:" !+ist"!+ist"'a"1#"!+ist"'a"2#"!+ist"'8"1#"!+ist"'8"2#"!+ist"'c"1# !+ist"'c"2##

Solution

$0#" Processing T!o Lists Simultaneously. Case "


In section (',(! we de+eloped the )unction hours-/wages )or the computation o) wee.l$ wages, It consumed a list o) numbers 22 hours wor.ed per wee. 22 and produced a list o) wee.l$ wages, 1e had based the )unction on the simpli)$ing assumption that all emplo$ees recei+ed the same pa$ rate, #+en a small compan$! howe+er! emplo$s people at di))erent rate le+els, T$picall$! the compan$Cs accountant also maintains two collections o) in)ormation: a permanent one that! among other things! includes an emplo$eeCs personal pa$2rate! and a temporar$ one that records how much time an emplo$ee has wor.ed during the past wee., The re+ised problem statement means that the )unction should consume t-o lists, To simpli)$ the problem! let us assume that the lists are Fust lists o) numbers! pa$ rates and wee.l$ hours, Then here is the problem statement:
66"hours-/wages":"+ist-of-n.m8ers"+ist-of-n.m8ers""-/""+ist-ofn.m8ers 66"to"constr.ct"a"new"+ist"82"m.+tip+2ing"the"corresponding"items on 66"a+on1"and"a+on2 66"'CCPH3;INJ:"the"two"+ists"are"of"e).a+"+ength" !define"!hours-/wages"a+on1"a+on2#"...#

1e can thin. o) a+on1 as the list o) pa$2rates and o) a+on2 as the list o) hours wor.ed per wee., To get the list o) wee.l$ wages! we must multipl$ the corresponding numbers in the two input lists,

"etCs loo. at some e8amples:


!hours-/wages"empt2"empt2# 66"e*pected"0a+.e: empt2 !hours-/wages"!cons"5. 5"empt2#"!cons"4%"empt2## 66"e*pected"0a+.e:" !cons"22 .%"empt2# !hours-/wages"!cons"5. 5"!cons"$.75"empt2##" """"""""""""""!cons"4%.%"!cons"3%.%"empt2### 66"e*pected"0a+.e:" !cons"22 .%"!cons"2 2.5"empt2##

For all three e8amples the )unction is applied to two lists o) e?ual length, As stated in the addendum to the purpose statement! the )unction assumes this and! indeed! using the )unction ma.es no sense i) the condition is +iolated, The condition on the inputs can also be e8ploited )or the de+elopment o) the template, Put more concretel$! the condition sa$s that !empt2A"a+on1# is true i)! and onl$ i)! !empt2A"a+on2# is trueE and )urthermore! !consA"a+on1# is true i)! and onl$ i)! !consA"a+on2# is true, In other words! the condition simpli)ies the design o) the templateCs cond2structure! because it sa$s the template is similar to that o) a plain list2 processing )unction:
!define"!hours-/wages"a+on1"a+on2# ""!cond """"!!empt2A"a+on1#"...# """"!else"..."###

In the )irst cond2clause! both a+on1 and a+on2 are empt2, Hence no selector e8pressions are needed, In the second clause! both a+on1 and a+on2 are constructed lists! which means we need )our selector e8pressions:
!define"!hours-/wages"a+on1"a+on2# ""!cond """"!!empt2A"a+on1#"...# """"!else """"""..."!first"a+on1#"..."!first"a+on2#"... """"""..."!rest"a+on1#"..."!rest"a+on2#"..."###

Finall$! because the last two are lists o) e?ual length! the$ ma.e up a natural candidate )or the natural recursion o) hours-/wages:
!define"!hours-/wages"a+on1"a+on2# ""!cond """"!!empt2A"a+on1#"...# """"!else """"""..."!first"a+on1#"..."!first"a+on2#"... """"""..."!hours-/wages"!rest"a+on1#"!rest"a+on2##"..."###

The onl$ unusual aspect o) this template is that the recursi+e application consists o) two e8pressions! both selector e8pressions )or the two arguments, But! as we ha+e seen! the idea is easil$ e8plicable owing to the assumption that a+on1 and a+on2 are o) e?ual length,

66"hours-/wages":"+ist-of-n.m8ers"+ist-of-n.m8ers""-/""+ist-ofn.m8ers 66"to"constr.ct"a"new"+ist"82"m.+tip+2ing"the"corresponding"items on 66"'CCPH3;INJ:"the"two"+ists"are"of"e).a+"+ength" 66"a+on1"and"a+on2 !define"!hours-/wages"a+on1"a+on2# ""!cond """"!!empt2A"a+on1#"empt2# """"!else"!cons"!wee-+2-wage"!first"a+on1#"!first"a+on2## """"""""""""""""!hours-/wages"!rest"a+on1#"!rest"a+on2###### 66"wee-+2-wage":"n.m8er"n.m8er""-/""n.m8er 66"to"comp.te"the"wee-+2"wage"from"pa2-rate"and"ho.rs-wor-ed !define"!wee-+2-wage"pa2-rate"ho.rs-wor-ed#

/T pa$2rate hours2wor.ed00 Figure #&' The complete de)inition o) ho rs22S-age To de)ine the )unction )rom here! we )ollow the design recipe, The )irst e8ample implies that the answer )or the )irst cond2clause is empt2, In the second one! we ha+e three +alues a+ailable: (, !first"a+on1# e+aluates to the )irst item on the list o) pa$2ratesE &, !first"a+on2# e+aluates to the )irst item on the list o) hours wor.edE and 5, !hours-/wages"!rest"a+on1#"!rest"a+on2## computes the list o) wee.l$ wages )or the remainders o) a+on1 and a+on2, 1e merel$ need to combine these +alues to get the )inal answer, More speci)icall$! gi+en the purpose statement! we must compute the wee.l$ wage )or the )irst emplo$ee and construct a list )rom that wage and the rest o) the wages, This suggests the )ollowing answer )or the second cond2clause:
!cons"!wee-+2-wage"!first"a+on1#"!first"a+on2## """"""!hours-/wages"!rest"a+on1#"!rest"a+on2###

The au8iliar$ )unction wee-+2-wage consumes the two )irst items and computes the wee.l$ wage, Figure 69 contains the complete de)initions, E ercise 1(<2<1< In the real world! hours-/wages consumes lists o) emplo$ee structures and lists o) wor. structures, An emplo$ee structure contains an emplo$eeCs name! social securit$ number! and pa$ rate, A wor. structure contains an emplo$eeCs name and the number o) hours wor.ed in a wee., The result is a list o) structures that contain the name o) the emplo$ee and the wee.l$ wage,

Modi)$ the )unction in )igure 69 so that it wor.s on these classes o) data, Pro+ide the necessar$ structure de)initions and data de)initions, Ase the design recipe to guide the modi)ication process, Solution E ercise 1(<2<2< De+elop the )unction @ip! which combines a list o) names and a list phone numbers into a list o) phone records, Assuming the )ollowing structure de)inition:
!define-struct"phone-record"!name"n.m8er##",

a phone record is constructed with !ma-e-phone-record"s"n# where s is a s$mbol and n is a number, Assume the lists are o) e?ual length, Simpli)$ the de)inition! i) possible, Solution

$0#( Processing T!o Lists Simultaneously. Case (


Here is a third problem statement! gi+en as in the )orm o) a )unction contract! purpose statement! and header:
66"+ist-pic-":"+ist-of-s2m8o+s"N9/&"1:""-/""s2m8o+ 66"to"determine"the"nth"s2m8o+"from"a+os<"co.nting"from"16 66"signa+s"an"error"if"there"is"no"nth"item !define"!+ist-pic-"a+os"n#"...#

That is! the problem is to de+elop a )unction that consumes a natural number and a list o) s$mbols, Both belong to classes with comple8 data de)initions! though! unli.e )or the pre+ious two problems! the classes are distinct, Figure 6; recalls the two de)initions, The data definitions' A nat ra! n mber [>=
] /N9/&"1:0 is

either

(, 1 or &, !add1"n# i) n is a N9/&"1:, A !ist-of-symbo!s is either (, the empt$ list! empt2! or &, !cons"s"+of# where s is a s$mbol and +of is a list o) s$mbols, Figure #(' Data de)initions )or !ist-pic$

Because the problem is non2standard! we should ensure that our e8amples co+er all important cases, 1e usuall$ accomplish this goal b$ pic.ing one item per clause in the de)inition and choosing elements )rom basic )orms o) data on a random basis, In this e8ample! this procedure implies that we pic. at least two elements )rom +ist-ofs2m8o+s and two )rom N9/&"1:, "etCs choose empt2 and !cons"'a"empt2# )or the )ormer! and 1 and 3 )or the latter, But two choices per argument means )our e8amples totalE a)ter all! there is no immediatel$ ob+ious connection between the two arguments and no restriction in the contract:
!+ist-pic-"empt2"1#" 66"e*pected"8eha0ior:" !error"'+ist-pic-"1...1# !+ist-pic-"!cons"'a"empt2#"1# 66"e*pected"0a+.e:" 'a !+ist-pic-"empt2"3#" 66"e*pected"8eha0ior:" !error"'+ist-pic-"1...1# !+ist-pic-"!cons"'a"empt2#"3# 66"e*pected"8eha0ior:" !error"'+ist-pic-"1...1#

@nl$ one o) the )our results is a s$mbolE in the other cases! we see an error! indicating that the list doesnCt contain enough items, The discussion on e8amples indicates that there are indeed )our possible! independent cases that we must consider )or the design o) the )unction, 1e can disco+er the )our cases b$ arranging the necessar$ conditions in a table )ormat:
!empt2A"a+os# !consA"a+os# !&"n"1# !/"n"1#

The hori*ontal dimension o) the table lists those ?uestions that +ist-pic- must as. about the list argumentE the +ertical dimension lists the ?uestions about the natural number, Furthermore! the partitioning o) the table $ields )our s?uares, #ach s?uare represents the case when both the condition on the hori*ontal and the one on the +ertical are true, 1e can e8press this )act with and2e8pressions in the s?uares:
!empt2A"a+os# !consA"a+os#

!&"n"1#

!and"!&"n"1# """""!empt2A"a+os##

!and"!&"n"1# """""!consA"a+os##

!/"n"1#

!and"!/"n"1# """""!empt2A"a+os##

!and"!/"n"1# """""!consA"a+os##

It is straight)orward to chec. that )or an$ gi+en pair o) arguments e8actl$ one o) the )our composite claims must e+aluate to tr.e, Asing our cases anal$sis! we can now design the )irst part o) the template! the conditional e8pression:
!define"!+ist-pic-"a+os"n# ""!cond """"9!and"!&"n"1#"!empt2A"a+os##"...: """"9!and"!/"n"1#"!empt2A"a+os##"...: """"9!and"!&"n"1#"!consA"a+os##"...: """"9!and"!/"n"1#"!consA"a+os##"...:##

The cond2e8pression as.s all )our ?uestions! thus distinguishing all possibilities, -e8t we must add selector e8pressions to each cond2clause i) possible:
!define"!+ist-pic-"a+os"n# ""!cond """"9!and"!&"n"1#"!empt2A"a+os## """""...: """"9!and"!/"n"1#"!empt2A"a+os## """""..."!s.81"n#"...: """"9!and"!&"n"1#"!consA"a+os## """""..."!first"a+os#"..."!rest"a+os#...: """"9!and"!/"n"1#"!consA"a+os##" """""..."!s.81"n#"..."!first"a+os#"..."!rest"a+os#"...:##

For n! a natural number! the template contains at most one selector e8pression! which determines the predecessor o) n, For a+os! it might contain two, In those cases where either !&"n"1# or !empt2A"a+os# holds! one o) the two arguments is atomic and there is no need )or a corresponding selector e8pression, The )inal step o) the template construction demands that we annotate the template with recursions where the results o) selector e8pressions belong to the same class as the inputs, In the template )or +ist-pic-! this ma.es sense onl$ in the last cond2clause! which contains both a selector e8pression )or N9/&"1: and one )or +ist-of-s2m8o+s, All other clauses contain at most one rele+ant selector e8pression, It is! howe+er! unclear how to )orm the natural recursions, I) we disregard the purpose o) the )unction! and the template construction step as.s us to do Fust that! there are three possible recursions: (, !+ist-pic-"!rest"a+os#"!s.81"n## &, !+ist-pic-"a+os"!s.81"n## 5, !+ist-pic-"!rest"a+os#"n#

Since we cannot .now which one matters or whether all three matter! we mo+e on to the ne8t de+elopment stage,
66"+ist-pic-":"+ist-of-s2m8o+s"N9/&"1:""-/""s2m8o+ 66"to"determine"the"nth"s2m8o+"from"a+os<"co.nting"from"16 66"signa+s"an"error"if"there"is"no"nth"item !define"!+ist-pic-"a+os"n# ""!cond """"9!and"!&"n"1#"!empt2A"a+os##"!error"'+ist-pic-"1+ist"too short1#: """"9!and"!/"n"1#"!empt2A"a+os##"!error"'+ist-pic-"1+ist"too short1#: """"9!and"!&"n"1#"!consA"a+os##"!first"a+os#:

V/and /S n (0 /consH alos00 /list2pic. /rest alos0 /sub( n00W00 Figure #)' The complete de)inition o) !ist-pic$ Following the design recipe! let us anal$*e each cond2clause in the template and decide what a proper answer is: (, I) !and"!&"n"1#"!empt2A"a+os## holds! +ist-pic- was as.ed to pic. the )irst item )rom an empt$ list! which is impossible, The answer must be an application o) error, &, I) !and"!/"n"1#"!empt2A"a+os## holds! +ist-pic- was again as.ed to pic. an item )rom an empt$ list, The answer is also an error, 5, I) !and"!&"n"1#"!consA"a+os## holds! +ist-pic- is supposed to produce the )irst item )rom some list, The selector e8pression !first"a+os# reminds us how to get this item, It is the answer, 6, For the )inal clause! i) !and"!/"n"1#"!consA"a+os## holds! we must anal$*e what the selector e8pressions compute: a, !first"a+os# selects the )irst item )rom the list o) s$mbolsE b, !rest"a+os# is the rest o) the listE and c, !s.81"n# is one less that the original gi+en list inde8, "et us consider an e8ample to illustrate the meaning o) these e8pressions, Suppose +ist-pic- is applied to !cons"'a"!cons"'8"empt2## and 2:
"""!+ist-pic-"!cons"'a"!cons"'8"empt2##"2#

The answer must be '8! !first"a+os# is 'a! and !s.81"n# is 1, Here is what the three natural recursions would compute with these +alues: d, !+ist-pic-"!cons"'8"empt2#"1# produces '8! the desired answerE e, !+ist-pic-"!cons"'a"!cons"'8"empt2##"1# e+aluates to 'a! which is a s$mbol! but the the wrong answer )or the original problemE and ), !+ist-pic-"!cons"'8"empt2#"2# signals an error because the inde8 is larger than the length o) the list, This suggests that we use !+ist-pic-"!rest"a+os#"!s.81"n## as the answer in the last cond2clause, But! e8ample2based reasoning is o)ten treacherous! so we should tr$ to understand wh$ the e8pression wor.s in general, Recall that! according to the purpose statement!
!+ist-pic-"!rest"a+os#"!s.81"n##

pic.s the /n - (0st item )rom !rest"a+os#, In other words! )or the second application! we ha+e decreased the inde8 b$ 1! shortened the list b$ one item! and now loo. )or an item, Clearl$! the second application alwa$s produces the same answer as the )irst one! assuming a+os and n are DDcompoundCC +alues, Hence our choice )or the last clause is trul$ Fusti)ied, E ercise 1(<!<1< De+elop +ist-pic-%! which pic.s items )rom a list li.e +ist-picbut starts counting at %, #8amples:
!s2m8o+&A"!+ist-pic-%"!+ist"'a"'8"'c"'d#"3# """""""""'d# !+ist-pic-%"!+ist"'a"'8"'c"'d#"4# 66"e*pected"8eha0ior: !error"'+ist-pic-%"1the"+ist"is"too"short1#

Solution

$0#) +unction Simplification


The +ist-pic- )unction in )igure 6< is more complicated than necessar$, Both the )irst and the second cond2clause produce the same answer: an error, In other words! i) either

!and"!&"n"1#"!empt2A"a+os##

or
!and"!/"n"1#"!empt2A"a+os##

e+aluates to tr.e! the answer is an error, 1e can translate this obser+ation into a simpler cond2e8pression:
!define"!+ist-pic-"a+os"n# ""!cond """"9!or"!and"!&"n"1#"!empt2A"a+os##" """""""""!and"!/"n"1#"!empt2A"a+os###"!error"'+ist-pic-"1+ist"too short1#: """"9!and"!&"n"1#"!consA"a+os##"!first"a+os#: """"9!and"!/"n"1#"!consA"a+os##"!+ist-pic-"!rest"a+os#"!s.81 n##:##

The new e8pression is a direct transliteration o) our #nglish obser+ation, To simpli)$ this )unction e+en more! we need to get ac?uainted with an algebraic law concerning booleans:
""!or"!and"condition1"a-condition#" """"""!and"condition2"a-condition## &"!and"!or"condition1"condition2# """""""a-condition#

The law is called de MorganCs law o) distributi+it$, Appl$ing it to our )unction $ields the )ollowing:
!define"!+ist-pic-"n"a+os# ""!cond """"9!and"!or"!&"n"1#"!/"n"1## """"""""""!empt2A"a+os##"!error"'+ist-pic-"1+ist"too"short1#: """"9!and"!&"n"1#"!consA"a+os##"!first"a+os#: """"9!and"!/"n"1#"!consA"a+os##"!+ist-pic-"!rest"a+os#"!s.81 n##:##

-ow consider the )irst part o) the condition: !or"!&"n"1#"!/"n"1##, Because n belongs to N9/&"1:! the condition is alwa$s true, But! i) we replace it with tr.e we get
!and"tr.e """""!empt2A"a+os##"""""

which is clearl$ e?ui+alent to !empt2A"a+os#, In other words! the )unction can be written as
!define"!+ist-pic-"a+os"n# ""!cond """"9!empt2A"a+os#"!error"'+ist-pic-"1+ist"too"short1#: """"9!and"!&"n"1#"!consA"a+os##"!first"a+os#: """"9!and"!/"n"1#"!consA"a+os##"!+ist-pic-"!rest"a+os#"!s.81 n##:##

which is alread$ signi)icantl$ simpler than that in )igure 6<, Still! we can do e+en better than that, The )irst condition in the latest +ersion o) +istpic- )ilters out all those cases when a+os is empt$, Hence !consA"a+os# in the ne8t two clauses is alwa$s going to e+aluate to tr.e, I) we replace the condition with tr.e and simpli)$ the and2e8pressions! we get the simplest possible +ersion o) +ist-pic-! which is displa$ed in )igure 6>, 1hile this last )unction is simpler than the original! it is important to understand that we designed both the original and the simpli)ied +ersion in a s$stematic manner and that we can there)ore trust both, I) we tr$ to )ind the simple +ersions directl$! we sooner or later )ail to consider a case and produce )lawed )unctions,
66"+ist-pic-":"+ist-of-s2m8o+s"N9/&"1:""-/""s2m8o+ 66"to"determine"the"nth"s2m8o+"from"a+os<"co.nting"from"16 66"signa+s"an"error"if"there"is"no"nth"item !define"!+ist-pic-"a+os"n# ""!cond """"9!empt2A"a+os#"!error"'+ist-pic-"1+ist"too"short1#: """"9!&"n"1#"!first"a+os#:

V/S n (0 /list2pic. /rest alos0 /sub( n00W00 Figure #-' The simpli)ied de)inition o) !ist-pic$

E ercise 1(<#<1< De+elop the )unction rep+ace-eo+-with )ollowing the strateg$ o) section (;,&, Then simpli)$ it s$stematicall$, Solution E ercise 1(<#<2< Simpli)$ the )unction +ist-pic-% )rom e8ercise (;,5,( or e8plain wh$ it canCt be simpli)ied, Solution

$0#* Designing +unctions that Consume T!o Comple, 3nputs


@n occasion! we will encounter problems that re?uire )unctions on two comple8 classes o) inputs, The most interesting situation occurs when both inputs are o) un.nown si*e, As we ha+e seen in the )irst three subsections! we ma$ ha+e to deal with such )unctions in three di))erent wa$s, The proper approach to this problem is to )ollow the general design recipe, In particular! we must conduct a data anal$sis and we must de)ine the rele+ant classes o) data, Then we can state the contract and the purpose o) the )unction! which! in turn! puts us in a position where we can thin. ahead, Be)ore we continue )rom this point! we should decide which one o) the )ollowing three situations we are )acing: (, In some cases! one o) the parameters pla$s a dominant role, Con+ersel$! we can thin. o) one o) the parameters as an atomic piece o) data as )ar as the )unction is concerned,

&, In some other cases! the two parameters are s$nchroni*ed, The$ must range o+er the same class o) +alues! and the$ must ha+e the same structure, For e8ample! i) we are gi+en two lists! the$ must ha+e the same length, I) we are gi+en two 1eb pages! the$ must ha+e the same length! and where one o) them contains an embedded page! the other one does! too, I) we decide that the two parameters ha+e this e?ual status and must be processed in a s$nchroni*ed manner! then we can pic. one o) them and organi*e the )unction around it, 5, Finall$! in some rare cases! there ma$ not be an$ ob+ious connection between the two parameters, In this case! we must anal$*e all possible cases be)ore we pic. e8amples and design the template, For the )irst two cases! we use an e8isting design recipe, The last case deser+es some special consideration, A)ter we ha+e decided that a )unction )alls into the third categor$ but be)ore we de+elop e8amples and the )unction template! we de+elop a two2dimensional table, Here is the table )or +ist-pic- again:
a+os !empt2A"a+os# !consA"a+os#

n !&"n"1#
!/"n"1#

Along the hori*ontal direction we enumerate the conditions that recogni*e the subclasses )or the )irst parameter! and along the +ertical direction we enumerate the conditions )or the second parameter, The table guides the de+elopment o) both the set o) )unction e8amples and the )unction template, As )ar as the e8amples are concerned! the$ must co+er all possible cases, That is! there must be at least one e8ample )or each cell in the table, As )ar as the template is concerned! it must ha+e one cond2clause per cell, #ach cond2 clause! in turn! must contain all )easible selector e8pressions )or both parameters, I) one o) the parameters is atomic! there is no need )or a selector e8pression, Finall$! instead o) a single natural recursion! we might ha+e se+eral, For +ist-pic-! we disco+ered three cases, In general! all possible combinations o) selector e8pressions are candidates )or a natural recursion, Because we canCt .now which ones are necessar$ and which ones arenCt! we write them all down and pic. the proper ones )or the actual )unction de)inition,

In summar$! the design o) multi2parameter )unctions is Fust a +ariation on the old design2recipe theme, The .e$ idea is to translate the data de)initions into a table that shows all )easible and interesting combinations, The de+elopment o) )unction e8amples and the template e8ploit the table as much as possible, Filling in the gaps in the template ta.es practice! Fust li.e an$thing else,

$0#- E,ercises on Processing T!o Comple, 3nputs


E ercise 1(<&<1< De+elop the )unction merge, It consumes two lists o) numbers! sorted in ascending order, It produces a single sorted list o) numbers that contains all the numbers on both inputs lists /and nothing else0, A number occurs in the output as man$ times as it occurs on the two input lists together, #8amples:
!merge"!+ist"1"3"5"7",#"!+ist"%"2"4" "$## 66"e*pected"0a+.e:" !+ist"%"1"2"3"4"5" "7"$",# !merge"!+ist"1"$"$"11"12#"!+ist"2"3"4"$"13"14## 66"e*pected"0a+.e:"

/list ( & 5 6 < < < (( (& (5 (60 E


"Co+.tion

E ercise 1(<&<2< The goal o) this e8ercise is to de+elop a +ersion o) the Hangman game o) section 9,; )or words o) arbitrar$ length, Pro+ide a data de)inition )or representing words o) arbitrar$ length with lists, A !etter is represented with the s$mbols 'a through '@ plus 'V, De+elop the )unction re0ea+-+ist, It consumes three arguments: (, the chosen word! which is the word that we ha+e to guessE &, the stat s word! which states how much o) the word we ha+e guessed so )arE and 5, a letter! which is our current g ess, It produces a new status word! that is! a word that contains ordinar$ letters and 'V, The )ields in the new status word are determined b$ comparing the guess with each pair o) letters )rom the status word and the chosen word:

(, I) the guess is e?ual to the letter in the chosen word! the guess is the corresponding letter in the new status word, &, @therwise! the new letter is the corresponding letter )rom the status word, Test the )unction with the )ollowing e8amples: (, !re0ea+-+ist"!+ist"'t"'e"'a#"!+ist"'V"'e"'V#"'.# &, !re0ea+-+ist"!+ist"'a"'+"'e#"!+ist"'a"'V"'V#"'e# 5, !re0ea+-+ist"!+ist"'a"'+"'+#"!+ist"'V"'V"'V#"'+# First determine what the result should be, Ase the teachpac. hangman.ss and the )unctions draw-ne*t-part /)rom e8ercise 9,;,(0 and re0ea+-+ist to pla$ the Hangman game, #+aluate the )ollowing e8pression:
!hangman-+ist"re0ea+-+ist"draw-ne*t-part#

The )unction hangman-+ist chooses a word randoml$ and pops up a window with a choice menu )or letters, Choose letters and! when read$! clic. on the Chec. button to see whether $our guess is correct, #nFo$L Solution E ercise 1(<&<!< In a )actor$! emplo$ees punch time cards as the$ arri+e in the morning and lea+e in the e+ening, In the modern age o) electronic punch cards! a punch card contains an emplo$ee number and the number o) hours wor.ed, Also! emplo$ee records alwa$s contain the name o) the emplo$ee! an emplo$ee number! and a pa$ rate, De+elop the )unction hours-/wages2, The )unction consumes a list o) emplo$ee records and a list o) /electronic0 punch cards, It computes the wee.l$ wage )or each emplo$ee b$ matching the emplo$ee record with a punch card based on emplo$ee numbers, I) a pair is missing or i) a pairCs emplo$ee numbers are mismatched! the )unction stops with an appropriate error message, Assume that there is at most one card per emplo$ee and emplo$ee number,

>int' An accountant would sort the two lists b$ emplo$ee number )irst,

Solution

E ercise 1(<&<#< A !inear combination is the sum o) man$ linear terms! that is! products o) +ariables and numbers, The latter are called coe))icients in this conte8t, Here are some e8amples:

In all three e8amples! the coe))icient o) + is 7! that o) y is (;! and the one )or ' is 5, I) we are gi+en +alues )or +ariables! we can determine the +alue o) a pol$nomial, For e8ample! i) + O ('! the +alue o) 7 P + is 7'E i) + O (' and y O (! the +alue o) 7 P + I (; P y is 9;E and i) + O ('! y O (! and ' O &! the +alue o) 7 P + I (; P y I 5 P ' is ;5, In the past! we would ha+e de+eloped )unctions to compute the +alues o) linear combinations )or speci)ic +alues, An alternati+e representation is a list o) its coe))icients, The abo+e combinations would be represented as:
!+ist"5# !+ist"5"17# !+ist"5"17"3#

This representation assumes that we alwa$s agree on using +ariables in a )i8ed order, De+elop the )unction 0a+.e, It consumes the representation o) a linear combination and a list o) numbers, The lists are o) e?ual length, It produces the +alue o) the combination )or these +alues, Solution E ercise 1(<&<$< "ouise! Jane! "aura! Dana! and Mar$ are sisters who would li.e to sa+e mone$ and wor. spent on Christmas gi)ts, So the$ decide to hold a lotter$ that assigns to each one o) them a single gi)t recipient, Since Jane is a computer programmer! the$ as. her to write a program that per)orms the lotter$ in an impartial manner, @) course! the program must not assign an$ o) the sisters to hersel), Here is the de)inition o) gift-pic-, It consumes a list o) distinct names /s$mbols0 and randoml$ pic.s one o) those arrangements o) the list that do not agree with the original list at an$ position:
66"gift-pic-:"+ist-of-names""-/""+ist-of-names 66"to"pic-"a"[[randomKK"non-identit2"arrangement"of"names !define"!gift-pic-"names# ""!random-pic""""!non-same"names"!arrangements"names####

Recall that arrangements /see e8ercise (&,6,&0 consumes a list o) s$mbols and produces the list o) all rearrangements o) the items in the list,

De+elop the au8iliar$ )unctions (, random-pic-":"+ist-of-+ist-of-names""-/""+ist-of-names! which consumes a list o) items and randoml$ pic.s one o) them as the resultE &, non-same":"+ist-of-names"+ist-of-+ist-of-names""-/""+ist-of+ist-of-names! which consumes a list o) names L and a list o) arrangements and produces the list o) those that do not agree with L at an$ position, Two permutations agree at some position i) we can e8tract the same name )rom both lists b$ appl$ing first and the same number o) rest operations to both, For e8ample! !+ist"'a"'8"'c# and !+ist"'c"'a"'8# do not agree! but !+ist 'a"'8"'c# and !+ist"'c"'8"'a# agree at the second position, 1e can pro+e that b$ appl$ing rest )ollowed b$ first to both lists, Follow the appropriate recipe in each case care)ull$, >int' Recall that !random"n# pic.s a random number between % and n-1 /compare with e8ercise ((,5,(0, Solution E ercise 1(<&<&< De+elop the )unction DJ'prefi*, The )unction ta.es two arguments! both lists o) s$mbols /onl$ 'a! 'c! 'g! and 't occur in D-A! but we can sa)el$ ignore this issue here0, The )irst list is called a pattern! the second one a search-string, The )unction returns tr.e i) the pattern is a pre)i8 o) the search2string, In all other cases! the )unction returns fa+se, #8amples:
!DJ'prefi*"!+ist"'a"'t#"!+ist"'a"'t"'c##" !not"!DJ'prefi*"!+ist"'a"'t#"!+ist"'a### !DJ'prefi*"!+ist"'a"'t#"!+ist"'a"'t##" !not"!DJ'prefi*"!+ist"'a"'c"'g"'t#"!+ist"'a"'g### !not"!DJ'prefi*"!+ist"'a"'a"'c"'c#"!+ist"'a"'c###

Simpli)$ DJ'prefi*! i) possible, Modi)$ DJ'prefi* so that it returns the )irst item be$ond the pattern in the search2string i) the pattern is a proper pre)i8 o) the search2string, I) the lists do not match or i) the pattern is no shorter than the search2string! the modi)ied )unction should still return fa+se, Similarl$! i) the lists are e?uall$ long and match! the result is still tr.e, #8amples:

!s2m8o+&A"!DJ'prefi*"!+ist"'a"'t#"!+ist"'a"'t"'c##" """"""""""'c# !not"!DJ'prefi*"!+ist"'a"'t#"!+ist"'a### !DJ'prefi*"!+ist"'a"'t#"!+ist"'a"'t##"

Can this +ariant o) DJ'prefi* be simpli)iedH I) so! do it, I) not! e8plain,

Solution

$0#0 E,tended E,ercise. Evaluating Scheme2 Part "


The goal o) this section is to e8tend the e+aluator o) section (6,6 so that it can cope with )unction applications and )unction de)initions, In other words! the new e+aluator simulates what happens in DrScheme when we enter an e8pression in the Interactions window a)ter clic.ing 5*ec.te, To ma.e things simple! we assume that all )unctions in the Definitions window consume one argument, E ercise 1(<(<1< #8tend the data de)inition o) e8ercise (6,6,( so that we can represent the application o) a user2de)ined )unction to an e8pression such as !f"!+"1"1## or !* 3"!g"2##, The application should be represented as a structure with two )ields, The )irst )ield contains the name o) the )unction! the second one the representation o) the argument e8pression, Solution A )ull2)ledged e+aluator can also deal with )unction de)initions, E ercise 1(<(<2< Pro+ide a structure de)inition and a data de)inition )or de)initions, Recall that a )unction de)inition has three essential attributes: (, the )unctionCs name! &, the parameter name! and 5, the )unctionCs bod$, This suggests the introduction o) a structure with three )ields, The )irst two contain s$mbols! the last one a representation o) the )unctionCs bod$! which is an e8pression, Translate the )ollowing de)initions into Scheme +alues: (, !define"!f"*#"!+"3"*##

&, !define"!g"*#"!*"3"*## 5, !define"!h".#"!f"!*"2".### 6, !define"!i"0#"!+"!*"0"0#"!*"0"0### 7, !define"!-"w#"!*"!h"w#"!i"w###

Ma.e up more e8amples and translate them! too,

Solution

E ercise 1(<(<!< De+elop e0a+.ate-with-one-def, The )unction consumes /the representation o)0 a Scheme e8pression and /the representation o)0 a single )unction de)inition! 3, The remaining e8pressions )rom e8ercise (6,6,( are e+aluated as be)ore, For /the representation o)0 a +ariable! the )unction signals an error, For an application o) the )unction 3! e0a+.ate-with-one-def (, e+aluates the argumentE &, substitutes the +alue o) the argument )or the )unction parameter in the )unctionCs bod$E and 5, e+aluates the new e8pression +ia recursion, Here is a s.etch:6&
4. !e0a+.ate-with-one-def"!s.8st"..."..."...#" 5. """""""a-f.n-def#

For all other )unction applications! e0a+.ate-with-one-def signals an error, Solution E ercise 1(<(<#< De+elop the )unction e0a+.ate-with-defs, The )unction consumes /the representation o)0 a Scheme e8pression and a list o) /representations o)0 )unction de)initions! defs, The )unction produces the number that DrScheme would produce i) we were to e+aluate the actual Scheme e8pression in the Interactions window and i) the Definitions window contained the actual de)initions, The remaining e8pressions )rom e8ercise (6,6,( are e+aluated as be)ore, For an application o) the )unction 3! e0a+.ate-with-defs

(, e+aluates the argumentE &, loo.s up the de)inition o) 3 in defsE 5, substitutes the +alue o) the argument )or the )unction parameter in the )unctionCs bod$E and 6, e+aluates the new e8pression +ia recursion, "i.e DrScheme! e0a+.ate-with-defs signals an error )or a )unction application whose )unction name is not on the list and )or /the representation o)0 a +ariable, Solution

$0#4 E:uality and Testing


Man$ o) the )unctions we designed produce lists, 1hen we test these )unctions! we must compare their results with the predicted +alue! both o) which are lists, Comparing lists b$ hand is tedious and error2prone, "etCs de+elop a )unction that consumes two lists o) numbers and determines whether the$ are e?ual:
66"+ist&A":"+ist-of-n.m8ers"+ist-of-n.m8ers""-/""8oo+ean 66"to"determine"whether"a-+ist"and"another-+ist" 66"contain"the"same"n.m8ers"in"the"same"order !define"!+ist&A"a-+ist"another-+ist#"...#

The purpose statement re)ines our general claim and reminds us that! )or e8ample! shoppers ma$ consider two lists e?ual i) the$ contain the same items! regardless o) the order! but programmers are more speci)ic and include the order in the comparison, The contract and the purpose statement also show that +ist&A is a )unction that processes two comple8 +alues! and indeed! it is an interesting case stud$, Comparing two lists means loo.ing at each item in both lists, This rules out designing +ist&A along the lines o) rep+ace-eo+-with in section (;,(, At )irst glance! there is also no connection between the two lists! which suggests that we should use the modi)ied design recipe, "etCs start with the table:
!empt2A"a-+ist# !consA"a-+ist# !empt2A"another-+ist# !consA"another-+ist#

It has )our cells! which implies that we need /at least0 )our tests and )our cond2clauses in the template, Here are )i+e tests:
!+ist&A"empt2"empt2#" !not" ""!+ist&A"empt2"!cons"1"empt2### !not" ""!+ist&A"!cons"1"empt2#"empt2## !+ist&A"!cons"1"!cons"2"!cons"3"empt2###" """"""""!cons"1"!cons"2"!cons"3"empt2#### !not" ""!+ist&A"!cons"1"!cons"2"!cons"3"empt2###" """"""""""!cons"1"!cons"3"empt2####

The second and third show that +ist&A must deal with its arguments in a s$mmetric )ashion, The last two show how +ist&A can produce tr.e and fa+se, Three o) the templateCs )our cond2clauses contain selector e8pressions and one contains natural recursions:
!define"!+ist&A"a-+ist"another-+ist# ""!cond """"9!and"!empt2A"a-+ist#"!empt2A"another-+ist##"...: """"9!and"!consA"a-+ist#"!empt2A"another-+ist## """""..."!first"a-+ist#"..."!rest"a-+ist#"...: """"9!and"!empt2A"a-+ist#"!consA"another-+ist##" """"..."!first"another-+ist#"..."!rest"another-+ist#"...: """"9!and"!consA"a-+ist#"!consA"another-+ist## """""..."!first"a-+ist#"..."!first"another-+ist#"... """""..."!+ist&A"!rest"a-+ist#"!rest"another-+ist##"... """""..."!+ist&A"a-+ist"!rest"another-+ist##"... """""..."!+ist&A"!rest"a-+ist#"another-+ist#"...:##

There are three natural recursions in the )ourth clause because we can pair the two selector e8pressions and we can pair each parameter with one selector e8pression, From the template to the complete de)inition is onl$ a small step, Two lists can contain the same items onl$ i) the$ are both empt$ or constructed, This immediatel$ implies tr.e as the answer )or the )irst c+a.se and fa+se )or the ne8t two, In the last clause! we ha+e two numbers! the )irst o) both lists! and three natural recursions, 1e must compare the two numbers, Furthermore! !+ist&A"!rest"a-+ist#"!rest"another+ist## computes whether the rest o) the two lists are e?ual, The two lists are e?ual i)! and onl$ i)! both conditions hold! which means we must combine them with an and:
!define"!+ist&A"a-+ist"another-+ist# ""!cond """"9!and"!empt2A"a-+ist#"!empt2A"another-+ist##"tr.e: """"9!and"!consA"a-+ist#"!empt2A"another-+ist##"fa+se: """"9!and"!empt2A"a-+ist#"!consA"another-+ist##"fa+se: """"9!and"!consA"a-+ist#"!consA"another-+ist## """""!and"!&"!first"a-+ist#"!first"another-+ist## """"""""""!+ist&A"!rest"a-+ist#"!rest"another-+ist###:##

The other two natural recursions pla$ no role, "et us now ta.e a second loo. at the connection between the two parameters, The )irst de+elopment suggests that the second parameter must ha+e the same shape as the )irst one! i) the two lists are to be e?ual, Put di))erentl$! we could de+elop the )unction based on the structure o) the )irst parameter and chec. structure o) the other one as needed, The )irst parameter is a list o) numbers! so we can reuse the template )or list2processing )unctions:
!define"!+ist&A"a-+ist"another-+ist# ""!cond """"9!empt2A"a-+ist#"...: """"9!consA"a-+ist#" """""..."!first"a-+ist#"..."!first"another-+ist#"... """""..."!+ist&A"!rest"a-+ist#"!rest"another-+ist##"...:##

The onl$ di))erence is that the second clause processes the second parameter in the same wa$ as the )irst one, This mimics the de+elopment o) hours-/wages in section (;,&, Filling the gaps in this template is more di))icult than )or the )irst de+elopment o) +ist&A, I) a-+ist is empt2! the answer depends on another-+ist, As the e8amples show! the answer is tr.e i)! and onl$ i)! another-+ist is also empt2, Translated into Scheme this means that the answer in the )irst cond2clause is !empt2A"another-+ist#, I) a-+ist is not empt$! the template suggests that we compute the answer )rom (, !first"a-+ist#! the )irst number o) a-+istE &, !first"another-+ist#! the )irst number on another-+istE and 5, !+ist&A"!rest"a-+ist#"!rest"another-+ist##! which determines whether the rest o) the two lists are e?ual, =i+en the purpose o) the )unction and the e8amples! we now simpl$ compare !first a-+ist# and !first"another-+ist# and combine the result with the natural recursion in an and2e8pression:
!and"!&"!first"a-+ist#"!first"another-+ist## """""!+ist&A"!rest"a-+ist#"!rest"another-+ist###

1hile this step appears to be simple and straight)orward! the result is an improper de)inition, The purpose o) spelling out the conditions in a cond2e8pression is to ensure

that all selector e8pressions are appropriate, -othing in the speci)ication o) +ist&A! howe+er! suggests that another-+ist is constructed i) a-+ist is constructed, 1e can o+ercome this problem with an additional condition:
!define"!+ist&A"a-+ist"another-+ist# ""!cond """"9!empt2A"a-+ist#"!empt2A"another-+ist#: """"9!consA"a-+ist#" """""!and"!consA"another-+ist# """"""""""!and"!&"!first"a-+ist#"!first"another-+ist## """""""""""""""!+ist&A"!rest"a-+ist#"!rest"another-+ist####:##

The additional condition is !consA"another-+ist#! which means that +ist&A produces fa+se i) !consA"a-+ist# is true and !consA"another-+ist# is empt$, As the e8amples show! this is the desired outcome, In summar$! +ist&A shows that! on occasion! we can use more than one design recipe to de+elop a )unction, The outcomes are di))erent! though closel$ relatedE indeed! we could pro+e that the two alwa$s produce the same results )or the same inputs, Also! the second de+elopment bene)ited )rom the )irst one,

E ercise 1(<)<1< Test both +ersions o) +ist&A,

Solution

E ercise 1(<)<2< Simpli)$ the )irst +ersion o) +ist&A, That is! merge neighboring cond2clauses with the same result b$ combining their conditions in an or2e8pressionE switch cond2clauses as neededE and use else in the last clause o) the )inal +ersion, Solution E ercise 1(<)<!< De+elop s2m-+ist&A, The )unction determines whether two lists o) s$mbols are e?ual, Solution E ercise 1(<)<#< De+elop contains-same-n.m8ers, The )unction determines whether two lists o) numbers contain the same numbers! regardless o) the ordering, Thus! )or e8ample!
!contains-same-n.m8ers"!+ist"1"2"3#"!+ist"3"2"1##

e+aluates to tr.e,

Solution

E ercise 1(<)<$< The class o) numbers! s$mbols! and booleans are sometimes called atoms:65

An atom is either (, a number &, a boolean 5, a s$mbol De+elop the )unction +ist-e).a+A! which consumes two lists o) atoms and determines whether the$ are e?ual, Solution A comparison between the two +ersions o) +ist&A suggests that the second one is easier to understand than the )irst, It sa$s that two compound +alues are e?ual i) the second is made )rom the same constructor and the components are e?ual, In general! this idea is a good guide )or the de+elopment o) other e?ualit$ )unctions, "etCs loo. at an e?ualit$ )unction )or simple 1eb pages to con)irm this conFecture:
66"we8&A":"we8-page"we8-page""-/""8oo+ean 66"to"determine"whether"a-wp"and"another-wp"ha0e"the"same"tree shape 66"and"contain"the"same"s2m8o+s"in"the"same"order !define"!we8&A"a-wp"another-wp#"...#

Recall the data de)inition )or simple 1eb pages: A #eb-page /short: #*0 is either (, empt2E &, !cons"s"wp# where s is a s$mbol and wp is a 1eb pageE or 5, !cons"ewp"wp# where both ewp and wp are 1eb pages, The data de)inition has three clauses! which means that i) we were to de+elop we8&A with the modi)ied design recipe! we would need to stud$ nine cases, B$ using the insight gained )rom the de+elopment o) +ist&A instead! we can start )rom the plain template )or 1eb sites:

!define"!we8&A"a-wp"another-wp# ""!cond """"9!empt2A"a-wp#"...: """"9!s2m8o+A"!first"a-wp## """""..."!first"a-wp#"..."!first"another-wp#"... """""..."!we8&A"!rest"a-wp#"!rest"another-wp##"...: """"9else" """""..."!we8&A"!first"a-wp#"!first"another-wp##"... """""..."!we8&A"!rest"a-wp#"!rest"another-wp##"...:##

In the second cond2clause! we )ollow the e8ample o) hours-/wages and +ist&A again, That is! we sa$ that another-wp must ha+e the same shape as a-wp i) it is to be e?ual and process the two pages in an analogous manner, The reasoning )or the third clause is similar, As we re)ine this template into a )ull de)inition now! we must again add conditions on another-wp to ensure that the selector e8pressions are Fusti)ied:
!define"!we8&A"a-wp"another-wp# ""!cond """"9!empt2A"a-wp#"!empt2A"another-wp#: """"9!s2m8o+A"!first"a-wp## """""!and"!and"!consA"another-wp#"!s2m8o+A"!first"another-wp### """"""""""!and"!s2m8o+&A"!first"a-wp#"!first"another-wp## """""""""""""""!we8&A"!rest"a-wp#"!rest"another-wp####: """"9else" """""!and"!and"!consA"another-wp#"!+istA"!first"another-wp### """"""""""!and"!we8&A"!first"a-wp#"!first"another-wp## """""""""""""""!we8&A"!rest"a-wp#"!rest"another-wp####:##

In particular! we must ensure in the second and third clause that another-wp is a constructed list and that the )irst item is a s$mbol or a list! respecti+el$, @therwise the )unction is analogous to +ist&A and wor.s in the same wa$, E ercise 1(<)<&< Draw the table based on the data de)inition )or simple 1eb pages, De+elop /at least0 one e8ample )or each o) the nine cases, Test we8&A with these e8amples, Solution E ercise 1(<)<(< De+elop the )unction posn&A! which consumes two binar$ posn structures and determines whether the$ are e?ual, Solution E ercise 1(<)<)< De+elop the )unction tree&A! which consumes two binar$ trees and determines whether the$ are e?ual, Solution E ercise 1(<)<-< Consider the )ollowing two! mutuall$ recursi+e data de)initions: A 6!ist is either

(, empt2 &, !cons"s"s+# where s is a Ce*pr and s+ is a C+ist, A 6e+pr is either (, a number &, a boolean 5, a s$mbol 6, a C+ist De+elop the )unction C+ist&A! which consumes two C+ists and determines whether the$ are e?ual, "i.e lists o) numbers! two C+ists are e?ual i) the$ contain the same item at analogous positions, Solution -ow that we ha+e e8plored the idea o) e?ualit$ o) +alues! we can return to the original moti+ation o) the section: testing )unctions, Suppose we wish to test hours-/wages )rom section (;,&:
""!hours-/wages"!cons"5. 5"!cons"$.75"empt2##" """"""""""""""""!cons"4%"!cons"3%"empt2### &"!cons"22 .%"!cons"2 2.5"empt2##

I) we Fust t$pe in the application into Interactions window or add it to the bottom o) the Definitions window! we must compare the result and the predicted +alue b$ inspection, For short lists! li.e the ones abo+e! this is )easibleE )or long lists! deep 1eb pages! or other large compound data! manual inspection is error2prone, Asing e?ualit$ )unctions li.e +ist&A! we can greatl$ reduce the need )or manual inspection o) test results, In our running e8ample! we can add the e8pression
!+ist&A" ""!hours-/wages"!cons"5. 5"!cons"$.75"empt2##" """"""""""""""""!cons"4%"!cons"3%"empt2### ""!cons"22 .%"!cons"2 2.5"empt2###

to the bottom o) the Definitions window, 1hen we clic. the 5*ec.te button now! we Fust need to ma.e sure that all test cases produce tr.e as their results are displa$ed in the Interactions window,

66"test!hours-/wages":"+ist-of-n.m8ers"+ist-of-n.m8ers"+ist-ofn.m8ers""-/""test-res.+t 66"to"test"hours-/wages !define"!test!hours-/wages"a-+ist"another-+ist"e*pected-res.+t# ""!cond """"9!+ist&A"!hours-/wages"a-+ist"another-+ist#"e*pected-res.+t# """""tr.e: """"9else

/list Zbad test result:Z a2list another2list e8pected2result0W00 Figure $.' A test )unction Indeed! we can go e+en )urther, 1e can write a test )unction li.e the one in )igure 7', The class o) test-res.+ts consists o) the +alue tr.e and lists o) )our items: the string 18ad"test"res.+t:1 )ollowed b$ three lists, Asing this new au8iliar$ )unction! we can test hours-/wages as )ollows:
!test!hours-/wages" ""!cons"5. 5"!cons"$.75"empt2##" ""!cons"4%"!cons"3%"empt2## ""!cons"22 .%"!cons"2 2.5"empt2###

I) something goes wrong with the test! the )our2item list will stand out and speci)$ precisel$ which test case )ailed, Testing 3ith e9ualB: The designers o) Scheme anticipated the need o) a general e?ualit$ procedure and pro+ide:
66"e).a+A":"an2-0a+.e"an2-0a+.e""-/""8oo+ean 66"to"determine"whether"two"0a+.es"are"str.ct.ra++2"e).i0a+ent" 66"and"contain"the"same"atomic"0a+.es"in"ana+ogo.s"positions"

1hen e).a+A is applied to two lists! it compares them in the same manner as +ist&AE when it encounters a pair o) structures! it compares their corresponding )ields! i) the$ are the same .ind o) structuresE and when it consumes a pair o) atomic +alues! it compares them with &! s2m8o+&A! or 8oo+ean&A! whate+er is appropriate,

=uideline on Testing
Ase e).a+A )or testing /when comparisons o) +alues are necessar$0, 8nordered ,ists: @n some occasions! we use lists e+en though the ordering o) the items doesnCt pla$ a role, For those cases! it is important to ha+e )unctions such as contains-same-n.m8ers /see e8ercise (;,<,60 i) we wish to determine whether the result o) some )unction application contains the proper items, E ercise 1(<)<1.< De)ine a test )unction )or rep+ace-eo+-with )rom section (;,( using e).a+A and )ormulate the e8amples as test cases using this )unction, Solution

E ercise 1(<)<11< De)ine the )unction test-+ist-pic-! which manages test cases )or the +ist-pic- )unction )rom section (;,5, Formulate the e8amples )rom the section as test cases using test-+ist-pic-, Solution E ercise 1(<)<12< De)ine test-interpret! which tests interpret-with-defs )rom e8ercise (;,;,6! using e).a+A, Re)ormulate the test cases using this )unction, Solution

6&

1e discuss this )orm o) recursion in detail in part 4, Some people also include empt2 and .e$board characters /chars0,

65

Section 1) Interme**o !' ,ocal Definitions and ,e ical Scope


Intermediate Student Programs do not Fust consist o) single de)initions, In man$ cases! a program re?uires the de)inition o) au8iliar$ )unctions or o) )unctions with mutual re)erences, Indeed! as we become more e8perienced! we write programs that consist o) numerous au8iliar$ )unctions, I) we are not care)ul! these large collections o) )unctions o+erwhelm us, As the si*e o) our )unctions grows! we need to organi*e them so that we /and other readers0 can ?uic.l$ identi)$ the relationships between parts, This section introduces local! a simple construct )or organi*ing collections o) )unctions, 1ith local! a programmer can group )unction de)initions that belong together so that readers immediatel$ recogni*e the connection between the )unctions, Finall$! the introduction o) local also )orces us to discuss the concept o) +ariable binding, 1hile the +ariable and )unction de)initions o) (eginning"Ct.dent Scheme alread$ introduce bindings into a program! a good understanding o) local de)initions is possible onl$ with a thorough )amiliarit$ o) this concept,

$4#$ ;rgani9ing Programs !ith local


A local2e8pression groups together an arbitraril$ long se?uence o) de)initions similar to those )ound in the Definitions window, Following our established rules! we )irst introduce the s$nta8 and then the semantics and pragmatics o) local2e8pressions,

S%nta of local
A local2e8pression is Fust another .ind o) e8pression: O /local /?def-1/ ...?def-n/0 ?e*p/0 As usual! ?def-1/ ... ?def-n/ is an arbitraril$ long se?uence o) de)initions /see )igure 7(0 and ?e*p/ is an arbitrar$ e8pression, In other words! a local2e8pression consists o) the .e$word local! )ollowed b$ a se?uence o) de)initions grouped with ! and #! )ollowed b$ an e8pression,
?e*p/

?def/

O /define /?0ar/ ?0ar/ ...?0ar/0 ?e*p/0 X /define ?0ar/ ?e*p/0 X /define2struct ?0ar/ /?0ar/ ...?0ar/00 Figure $1' Scheme de)initions

The .e$word local distinguishes this new class o) e8pressions )rom other e8pressions! Fust as cond distinguishes conditional e8pressions )rom applications, The parenthesi*ed se?uence that )ollows local is re)erred to as the "@CA" D#FI-ITI@- ,The de)initions are called the "@CA""3 D#FI-#D +ariables! )unctions! or structures, All those in the Definitions window are called T@P2"#4#" D#FI-ITI@-S, #ach name ma$ occur at most once on the le)t2hand side! be it in a +ariable de)inition or a )unction de)inition, The e8pression in each de)inition is called the RI=HT2HA-D SID# e8pression, The e8pression that )ollows the de)initions is the B@D3, "et us ta.e a loo. at an e8ample:
!local"!!define"!f"*#"!+"*"5## !define"!g"a+on# ""!cond """"9!empt2A"a+on#"empt2: """"9else"!cons"!f"!first"a+on##"!g"!rest"a+on###:### ""!g"!+ist"1"2"3###

The locall$ de)ined )unctions are f and g, The right2hand side o) the )irst )unction de)inition is !+"*"5#E the second one is
!cond ""9!empt2A"a+on#"empt2: ""9else"!cons"!f"!first"a+on##"!g"!rest"a+on###:#

Finall$! the bod$ o) the local2e8pression is !g"!+ist"1"2"3##, E ercise 1)<1<1< Circle the locall$ de)ined +ariables and )unctions in red! the right2 hand sides in green! and the bod$ o) the )ollowing local2e8pression in blue:
1."!local"!!define"*"!*"2"3### """""""!*"*"*## 2."!local"!!define"!odd"an# """""""!cond "9!@eroA"an#"fa+se: "9else"!e0en"!s.81"an##:## """""!define"!e0en"an# """""""!cond "9!@eroA"an#"tr.e: "9else"!odd"!s.81"an##:### """""""!e0en"a-nat-n.m## 3."!local"!!define"!f"*#"!g"*"!+"*"1### """""!define"!g"*"2#"!f"!+"*"2#### """""""!+"!f"1%#"!g"1%"2%###

Solution

E ercise 1)<1<2< The )ollowing phrases are not s$ntacticall$ legal:


1."!local"!!define"*"1%# """""!2"!+"*"*### """""""2# 2."!local"!!define"!f"*#"!+"!*"*"*#"!*"3"*#"15## """""!define"*"1%%# """""!define"fY1%%"!f"*### """""""fY1%%"*# 3."!local"!!define"!f"*#"!+"!*"*"*#"!*"3"*#"14## """""!define"*"1%%# """""!define"f"!f"*### """""""f#

#8plain wh$L

Solution

E ercise 1)<1<!< Determine which o) the )ollowing de)initions or e8pressions are legal and which ones are not:
1."!define"'-7NJC;'J; """""""!not" "!local"!!define"!odd"an# """!cond """""9!&"an"%#"fa+se: """""9else"!e0en"!-"an"1##:## "!define"!e0en"an# """!cond """""9!&"an"%#"tr.e: """""9else"!odd"!-"an"1##:### """!e0en"a-nat-n.m#### 2."!+"!local"!!define"!f"*#"!+"!*"*"*#"!*"3"*#"15## !define"*"1%%# !define"fY1%%"!f"*### ""fY1%%# 1%%%# 3."!local"!!define"7NJC;"1%%# """""!define"f"*"!+"*"7NJC;### """""""!define"!g"*"2"@#"!f"!+"*"!*"2"@#####

#8plain wh$ each e8pression is legal or illegal,

Solution

Semantics of local
The purpose o) a local2e8pression is to de)ine a +ariable! a )unction! or a structure )or the e+aluation o) the bod$ e8pression, @utside o) the local2e8pression the de)initions ha+e no e))ect, Consider the )ollowing e8pression:
!local"!!define"!f"*#"e*p-1##"e*p#

It de)ines the )unction f during the e+aluation o) e*p, The result o) e*p is the result o) the entire local2e8pression, Similarl$!
!local"!!define"3I"3##"e*p#

temporaril$ lets the +ariable 3I stand )or 3 during the e+aluation o) e*p, 1e can describe the e+aluation o) local2e8pressions with a single rule! but the rule is e8tremel$ comple8, More speci)icall$! the rule re?uires two steps in a hand2e+aluation, First! we must s$stematicall$ replace all locall$ de)ined +ariables! )unctions! and structures so that the names do not o+erlap with those used in the Definitions window, Second! we mo+e the entire se?uence o) de)initions to the top le+el and proceed as i) we had Fust created a new )unction, Here is the e+aluation rule! stated s$mbolicall$:
"""def-1"..."def-n" """59!local"!!define"!f-1"*#"e*p-1#"..."!define"!f-n"*#"e*p-n## e*p#:" &" """def-1"..."def-n"!define"!f-1K"*#"e*p-1K#"..."!define"!f-nK"*# e*p-nK#" """59e*pK:

For simplicit$! the local2e8pression in this rule de)ines onl$ one2argument )unctions! but it is straight)orward to generali*e )rom here, As usual! the se?uence def-1"..."def-n represents top2le+el de)initions, The unusual part o) the rule is the notation 59e*p:, It represents an e8pression e*p and its conte8t 5, More speci)icall$! e*p is the ne8t e8pression that must be e+aluatedE 5 is called its #4A"AATI@- C@-T#NT, For e8ample! the e8pression
"""!+"!local"!!define"!f"*#"1%##"!f"13##"5#

is an addition, Be)ore we can compute its result! we must e+aluate the two sube8pressions to numbers, Since the )irst sube8pression is not a number! we )ocus on it:
"""!local"!!define"!f"*#"1%##"!f"13##

This local2e8pression must and can be e+aluated! so


"""e*p"&"!local"!!define"!f"*#"1%##"!f"13## """5"&"!+"..."5#

@n the right2hand side o) the rule )or local! we can see se+eral primed names and e8pressions, The primed names f-1K! ...! f-nK are new )unction names! distinct )rom all other names in top2le+el de)initionsE the primes on the e8pressions e*p-1K! ...! e*p-nK indicate that these e8pressions are structurall$ identical to e*p-1! ...! e*p-n but contain f-1K instead o) f-1! etc,

The e+aluation rule )or local2e8pressions is the most comple8 rule that we ha+e encountered so )ar! and indeed! it is the most comple8 rule that we will e+er encounter, #ach o) the two steps is important and ser+es a distinct purpose, Their purpose is best illustrated b$ a series o) simple e8amples, The )irst part o) the rule eliminates name clashes between names that are alread$ de)ined in the top2le+el en+ironment and those that will be inserted there, Consider the )ollowing e8ample:
!define"2"1%# !+"2" """!local"!!define"2"1%# """!define"@"!+"2"2### """""@##

The e8pression introduces a local de)inition )or 2! adds 2 to itsel) to get @! and returns the +alue o) @, The in)ormal description o) local sa$s that the result should be 3%, "etCs +eri)$ this with our rule, I) we simpl$ added the de)initions in local to the top le+el! the two de)initions )or 2 would clash, The renaming step pre+ents this clash and clari)ies which o) the 2Cs belong together:
&"!define"2"1%# ""!+"2"!local"!!define"21"1%#"!define"@1"!+"21"21###"@1## &"!define"2"1%# ""!define"21"1%# ""!define"@1"!+"21"21## ""!+"2"@1# &"!define"2"1%# ""!define"21"1%# ""!define"@1"2%# ""!+"1%"@1# &"!define"2"1%# ""!define"21"1%# ""!define"@1"2%# ""!+"1%"2%#

As e8pected! the result is 3%, Since local2e8pressions ma$ occur inside o) )unction bodies! renaming is important i) such )unctions are applied more than once, The )ollowing second e8ample illustrates this point:
""!define"!D"*"2# """"!local"!!define"*2"!*"*"*## """"!define"22"!*"2"2### """"""!s)rt"!+"*2"22#### ""!+"!D"%"1#"!D"3"4##

The )unction D computes the s?uare root o) the sum o) the s?uares o) its arguments, Hence the result o) !+"!D"%"1#"!D"3"4## should be , As D computes its answer! it introduces two local +ariables: *2 and 22, Since D is applied twice! a modi)ied +ersion o) its bod$ is e+aluated twice and there)ore its local de)initions must be added to the top2le+el twice, The renaming step ensures that no matter how o)ten we li)t such de)initions! the$ ne+er inter)ere with each other, Here is how this wor.s:
&"!define"!D"*"2# """"!local"!!define"*2"!*"*"*## """"!define"22"!*"2"2### """"""!s)rt"!+"*2"22#### ""!+"!local"!!define"*2"!*"%"%## """""!define"22"!*"1"1### """""""!s)rt"!+"*2"22### """""!D"3"4##

The e8pression !D"%"1# is e+aluated according to the regular rules, -ow we rename and li)t the local de)initions:
&"!define"!D"*"2# """"!local"!!define"*2"!*"*"*## """"!define"22"!*"2"2### """"""!s)rt"!+"*2"22#### ""!define"*21"!*"%"%## ""!define"221"!*"1"1## ""!+"!s)rt"!+"*21"221## """""!D"3"4##

From here! the e+aluation proceeds according to the standard rules until we encounter a second nested local2e8pression in the e8pression that we are e+aluating:
&"!define"!D"*"2# """"!local"!!define"*2"!*"*"*## """"!define"22"!*"2"2### """"""!s)rt"!+"*2"22#### ""!define"*21"%# ""!define"221"1# ""!+"1"!local"!!define"*2"!*"3"3## """""""!define"22"!*"4"4### "!s)rt"!+"*2"22#### &"!define"!D"*"2# """"!local"!!define"*2"!*"*"*## """"!define"22"!*"2"2### """"""!s)rt"!+"*2"22#### ""!define"*21"%# ""!define"221"1# ""!define"*22",# ""!define"222"1 # ""!+"1"!s)rt"!+"*22"222###

B$ renaming *2 and 22 again! we a+oided clashes, From here! the e+aluation o) the e8pression is straight)orward:
""!+"1"!s)rt"!+"*22"222### &"!+"1"!s)rt"!+","222###

&"!+"1"!s)rt"!+","1 ### &"!+"1"!s)rt"25## &"!+"1"5# &"

The result is 9! as e8pected,66 E ercise 1)<1<#< Since local de)initions are added to the Definitions window during an e+aluation! we might wish to tr$ to see their +alues b$ Fust t$ping in the +ariables into the Interactions window, Is this possibleH 1h$ or wh$ notH Solution E ercise 1)<1<$< #+aluate the )ollowing e8pressions b$ hand:
1."!local"!!define"!*"2#"!*"3"2### """""""!*"!*"2#"5## 2."!local"!!define"!f"c#"!+"!*",/5"c#"32### """""""!-"!f"%#"!f"1%### 3."!local"!!define"!oddA"n# """""""!cond "9!@eroA"n#"fa+se: "9else"!e0enA"!s.81"n##:## """""!define"!e0enA"n# """""""!cond "9!@eroA"n#"tr.e: "9else"!oddA"!s.81"n##:### """""""!e0enA"1## 4."!+"!local"!!define"!f"*#"!g"!+"*"1#"22## !define"!g"*"2#"!+"*"2### ""!f"1%## 555# 5."!define"!h"n#" """""""!cond "9!&"n"%#"empt2: "9else"!local"!!define"r"!*"n"n### "!cons"r"!h"!-"n"1####:## """""!h"2#

The e+aluations should show all local2reductions,

Solution

Pragmatics of local, Part 1


The most important use o) local2e8pressions is to #-CAPSA"AT# a collection o) )unctions that ser+e one purpose, Consider )or an e8ample the de)initions )or our sort )unction )rom section (&,&:
66"sort":"+ist-of-n.m8ers""-/""+ist-of-n.m8ers !define"!sort"a+on# ""!cond """"9!empt2A"a+on#"empt2: """"9!consA"a+on#"!insert"!first"a+on#"!sort"!rest"a+on###:## 66"insert":"n.m8er"+ist-of-n.m8ers"!sorted#""-/""+ist-of-n.m8ers !define"!insert"an"a+on#

""!cond """"9!empt2A"a+on#"!+ist"an#: """"9else"!cond """"9!/"an"!first"a+on##"!cons"an"a+on#: """"9else"!cons"!first"a+on#"!insert"an"!rest"a+on###:#:##

The )irst de)inition de)ines sort per se! and the second one de)ines an au8iliar$ )unction that inserts a number into a sorted list o) numbers, The )irst one uses the second one to construct the result )rom a natural recursion! a sorted +ersion o) the rest o) the list! and the )irst item, The two )unctions together )orm the program that sorts a list o) numbers, To indicate this intimate relationship between the )unctions! we can! and should! use a local2 e8pression, Speci)icall$! we de)ine a program sort that immediatel$ introduces the two )unctions as au8iliar$ de)initions:
66"sort":"+ist-of-n.m8ers""-/""+ist-of-n.m8ers !define"!sort"a+on# ""!local"!!define"!sort"a+on# """"!cond """"""9!empt2A"a+on#"empt2: """"""9!consA"a+on#"!insert"!first"a+on# """"""""""""""""""""""""""""""""""""!sort"!rest"a+on###:## ""!define"!insert"an"a+on# """"!cond """"""9!empt2A"a+on#"!+ist"an#: """"""9else"!cond """"""9!/"an"!first"a+on##"!cons"an"a+on#: """"""9else"!cons"!first"a+on#" """"""""""""""""""""""""""""""""""!insert"an"!rest"a+on###:#:### """"!sort"a+on###

Here the bod$ o) local2e8pressions simpl$ passes on the argument to the locall$ de)ined )unction sort,

=uideline on the Ase o) local


De+elop a )unction )ollowing the design recipes, I) the )unction re?uires the use o) au8iliar$ de)initions! group them in a local2e8pression and put the local2e8pression into a new )unction de)inition, The bod$ o) the local should appl$ the main )unction to the arguments o) the newl$ de)ined )unction, E ercise 1)<1<&< #+aluate !sort"!+ist"2"1"3## b$ hand until the locall$ de)ined sort )unction is used, Do the same )or !e).a+A"!sort"!+ist"1##"!sort"!+ist 2###, Solution E ercise 1)<1<(< Ase a local e8pression to organi*e the )unctions )or mo+ing pictures )rom section (',5, Solution

E ercise 1)<1<)< Ase a local e8pression to organi*e the )unctions )or drawing a pol$gon in )igure 56, Solution E ercise 1)<1<-< Ase a local e8pression to organi*e the )unctions )or rearranging words )rom section (&,6, Solution E ercise 1)<1<1.< Ase a local e8pression to organi*e the )unctions )or )inding blue2 e$ed descendants )rom section (7,(, Solution

Pragmatics of local, Part 2


Suppose we need a )unction that produces the last occurrence o) some item in a list, To be precise! assume we ha+e lists o) records o) roc. stars, For simplicit$! each star is represented as a pair o) +alues:
!define-struct"star"!name"instr.ment##

A star /record0 is a structure:


!ma-e-star"s"t#

where s and t are s$mbols, Here is an e8ample:


!define"a+os" ""!+ist"!ma-e-star"'7hris"'sa*ophone# """"""""!ma-e-star"'Qo882"'tr.mpet# """"""""!ma-e-star"'Hatt"'0io+in# """"""""!ma-e-star"'Oen"'g.itar# """"""""!ma-e-star"'Hatt"'radio###

This list contains two occurrences o) 'Hatt, So! i) we wanted to determine the instrument that goes with the last occurrence o) 'Hatt! we would want 'radio, For 'Oen! on the other hand! our )unction would produce 'g.itar, @) course! loo.ing )or the instrument o) '\ate should $ield fa+se to indicate that there is no record )or '\ate, "etCs write down a contract! a purpose statement! and a header:
66"+ast-occ.rrence":"s2m8o+"+ist-of-star""-/""star"or"fa+se 66"to"find"the"+ast"star"record"in"a+ostars"that"contains"s"in name"fie+d !define"!+ast-occ.rrence"s"a+ostars#"...#

The contract is unusual because it mentions two classes o) data to the right o) the arrow: star and fa+se, Although we ha+enCt seen this .ind o) contract be)ore! its meaning is ob+ious, The )unction ma$ produce a star or fa+se,

1e ha+e alread$ de+eloped some e8amples! so we can mo+e directl$ to the template stage o) our design recipe:
!define"!+ast-occ.rrence"s"a+ostars# ""!cond """"9!empt2A"a+ostars#"...: """"9else"..."!first"a+ostars#"..."!+ast-occ.rrence"s"!rest a+ostars##"...:##

The real problem with this )unction! o) course! shows up onl$ when we want to )ill in the gaps in this template, The answer in the )irst case is fa+se! per speci)ication, How to )orm the answer in the second case is )ar )rom clear, Here is what we ha+e: (, !first"a+ostars# is the )irst star record on the gi+en list, I) its name )ield is e?ual to s! it ma$ or ma$ not be the )inal result, It all depends on the records in the rest o) the list, &, !+ast-occ.rrence"s"!rest"a+ostars## e+aluates to one o) two things: a star record with s as the name )ield or fa+se, In the )irst case! the star record is the resultE in the second case! the result is either fa+se or the )irst record, The second point implies that we need to use the result o) the natural recursion twice! )irst to chec. whether it is a star or a 8oo+ean! and second! to use it as the answer i) it is a star, The dual2use o) the natural recursion is best e8pressed with a local2e8pression:
!define"!+ast-occ.rrence"s"a+ostars# ""!cond """"9!empt2A"a+ostars#"fa+se: """"9else"!local"!!define"r"!+ast-occ.rrence"s"!rest"a+ostars#### """"""""""""!cond """"""""""""""9!starA"r#"r: """"""...##:##

The nested local2e8pression gi+es a name to the result o) the natural recursion, The cond2e8pression uses it twice, 1e could eliminate the local2e8pression b$ replacing r with the right2hand side:
!define"!+ast-occ.rrence"s"a+ostars# ""!cond """"9!empt2A"a+ostars#"fa+se: """"9else"!cond """"""""""""9!starA"!+ast-occ.rrence"s"!rest"a+ostars###" """""!+ast-occ.rrence"s"!rest"a+ostars##: """"...#:##

But e+en a super)icial glance shows that reading a natural recursion twice is di))icult, The +ersion with local is superior,

From the partiall$ re)ined template it is onl$ a short step to the )ull de)inition:
66"+ast-occ.rrence":"s2m8o+"+ist-of-star""-/""star"or"fa+se 66"to"find"the"+ast"star"record"in"a+ostars"that"contains"s"in name"fie+d !define"!+ast-occ.rrence"s"a+ostars# ""!cond """"9!empt2A"a+ostars#"fa+se: """"9else"!local"!!define"r"!+ast-occ.rrence"s"!rest"a+ostars#### """"""""""""!cond """"""""""""""9!starA"r#"r: """"""""""""""9!s2m8o+&A"!star-name"!first"a+ostars##"s#"!first a+ostars#: """"""""""""""9else"fa+se:##:##

The second clause in the nested cond2e8pression compares the )irst recordCs name )ield with s i) r is not a star record, In that case! there is no record with the matching name in the rest o) the list! and! i) the )irst record is the appropriate one! it is the result, @therwise! the entire list does not contain the name weCre loo.ing )or and the result is fa+se, E ercise 1)<1<11< #+aluate the )ollowing test b$ hand:
!+ast-occ.rrence"'Hatt ""!+ist"!ma-e-star"'Hatt"'0io+in# """"""""!ma-e-star"'Hatt"'radio###

How man$ local2e8pressions are li)tedH

Solution

E ercise 1)<1<12< Consider the )ollowing )unction de)inition:


66"ma*i":"non-empt2-+on""-/""n.m8er 66"to"determine"the"+argest"n.m8er"on"a+on !define"!ma*i"a+on# ""!cond """"9!empt2A"!rest"a+on##"!first"a+on#: """"9else"!cond """"9!/"!first"a+on#"!ma*i"!rest"a+on###"!first"a+on#: """"9else"!ma*i"!rest"a+on##:#:##

Both clauses in the nested cond2e8pression compute !ma*i"!rest"an-in0##! which is there)ore a natural candidate )or a local2e8pression, Test both +ersions o) ma*i with
!+ist"1"2"3"4"5" "7"$","1%"11"12"13"14"15"1 "17"1$"1,"2%#

#8plain the e))ect,

Solution

E ercise 1)<1<1!< De+elop the )unction to-8+.e-e2ed-ancestor, The )unction consumes a )amil$ tree /ftn0 /see section (6,(0 and produces a list that e8plains how to get to a blue2e$ed ancestor, I) there is no blue2e$ed ancestor! the )unction produces fa+se,

The )unctionCs contract! purpose statement! and header are as )ollows:


66"to-8+.e-e2ed-ancestor":"ftn""-/""path"or"fa+se" 66"to"comp.te"the"path"from"a-ftn"tree"to"a"8+.e-e2ed"ancestor !define"!to-8+.e-e2ed-ancestor"a-ftn#"...#

A path is a list o) 'father and 'mother! which we call a direction, Here are the two data de)initions: A direction is either (, the s$mbol 'father or &, the s$mbol 'mother , A path is either (, empt2 or &, !cons"s"+os# where s is a direction and +os is a path, The empt$ path indicates that a-ftn has '8+.e in the e2es )ield, I) the )irst item is 'mother! we ma$ search in the motherCs )amil$ tree )or a blue2e$ed ancestor using the rest o) the path, Similarl$! we search in the )atherCs )amil$ tree i) the )irst item is 'father and use the rest o) the path )or )urther directions, #8amples: (, !to-8+.e-e2ed-ancestor"G.sta0# produces !+ist"'mother# )or the )amil$ tree in )igure 57E &, !to-8+.e-e2ed-ancestor"'dam# produces fa+se in the same settingE and 5, i) we added !define"=a+"!ma-e-chi+d"G.sta0"50a"'G.sta0"1,$$ 'ha@e+## then !to-8+.e-e2ed-ancestor"=a+# would $ield !+ist"'father 'mother#,

Build test cases )rom these e8amples, Formulate them as boolean e8pressions! using the strateg$ o) section (;,<, Solution 5ac6trac6ing: The )unctions +ast-occ.rrence and to-8+.e-e2ed-ancestor produce two .inds o) results: one to indicate a success)ul search and another one to indicate a )ailure, Both are recursi+e, I) a natural recursion )ails to )ind the desired result! each tries to compute a result in a di))erent manner, Indeed! to-8+.e-e2edancestor ma$ use another natural recursion, This strateg$ o) computing an answer is a simple )orm o) BAC TRAC I-=, In the world o) data that we ha+e dealt with so )ar! bac.trac.ing is simple and Fust a de+ice to sa+e computing steps, It is alwa$s possible to write two separate recursi+e )unctions that accomplish the same purpose as one o) the bac.trac.ing )unctions here, 1e will ta.e an e+en closer loo. at bac.trac.ing in section &<, Also! we will discuss counting computing steps in interme**o 7, E ercise 1)<1<1#< Discuss the )unction find )rom e8ercise (7,5,6 in terms o) bac.trac.ing, Solution

Pragmatics of local, Part !


Consider the )ollowing )unction de)inition:
66"m.+t1%":"+ist-of-digits""-/""+ist-of-n.m8ers 66"to"create"a"+ist"of"n.m8ers"82"m.+tip+2ing"each"digit"on"a+od" 66"82"!e*pt"1%"p#"where"p"is"the"n.m8er"of"digits"that"fo++ow !define"!m.+t1%"a+od# ""!cond """"9!empt2A"a+od#"%: """"9else"!cons"!*"!e*pt"1%"!+ength"!rest"a+od###"!first"a+od## """"""" """"""""!m.+t1%"!rest"a+od###:##

Here is a test:
!e).a+A"!m.+t1%"!+ist"1"2"3##"!+ist"1%%"2%"3##

Clearl$! the )unction could be used to con+ert a list o) digits into a number, A small problem with the de)inition o) m.+t1% is the computation o) the )irst item o) the result in the second clause, It is a large e8pression and doesnCt ?uite correspond to the purpose statement, B$ using a local2e8pression in the second clause! we can introduce names )or some intermediate +alues in the computation o) the answer:
66"m.+t1%":"+ist-of-digits""-/""+ist-of-n.m8ers 66"to"create"a"+ist"of"n.m8ers"82"m.+tip+2ing"each"digit"on"a+od"

66"82"!e*pt"1%"p#"where"p"is"the"n.m8er"of"digits"that"fo++ow !define"!m.+t1%"a+on# ""!cond """"9!empt2A"a+on#"empt2: """"9else"!local"!!define"a-digit"!first"a+on## """"""""""""""""""!define"p"!+ength"!rest"a+on#### """"66"-----------------------------------------------------""""""""""""!cons"!*"!e*pt"1%"p#"a-digit#"!m.+t1%"!rest a+on####:##

The use o) names helps us understand the e8pression when we read the de)inition again because we can stud$ one local2de)inition at a time, The use o) local )or such cases is most appropriate when a +alue is computed twice as! )or e8ample! the e8pression !rest"a+on# in m.+t1%, B$ introducing names )or repeated e8pressions! we might also a+oid some /small0 e))ort on DrSchemeCs side:
!define"!m.+t1%"a+on# ""!cond """"9!empt2A"a+on#"empt2: """"9else"!local"!!define"a-digit"!first"a+on## """"""""""""""""""!define"the-rest"!rest"a+on## ""!define"p"!+ength"the-rest### """"66"-----------------------------------------------------""""""""""""!cons"!*"!e*pt"1%"p#"a-digit#"!m.+t1%"the-rest###:##

For the programs that we ha+e de+eloped! this third usage o) local is hardl$ e+er use)ul, An au8iliar$ )unction is almost alwa$s better, 1e will! howe+er! encounter man$ di))erent st$les o) )unctions in the remaining parts o) the boo. and with them the opportunit$! and sometimes the necessit$! to use local2e8pressions li.e the one )or m.+t1%, E ercise 1)<1<1$< Consider the )ollowing )unction de)inition:
66"e*tract1":"in0entor2""-/""in0entor2 66"to"create"an"in0entor2"from"an-in0"for"a++ 66"those"items"that"cost"+ess"than"X1 !define"!e*tract1"an-in0# ""!cond """"9!empt2A"an-in0#"empt2: """"9else"!cond """"9!?&"!ir-price"!first"an-in0##"1.%%# """""!cons"!first"an-in0#"!e*tract1"!rest"an-in0###: """"9else"!e*tract1"!rest"an-in0##:#:##

Both clauses in the nested cond2e8pression e8tract the )irst item )rom an-in0 and both compute !e*tract1"!rest"an-in0##, Introduce a local2e8pression )or these e8pressions, Solution

$4#" Le,ical Scope and Block Structure


Chec. S$nta8 The introduction o) local re?uires some additional terminolog$ concerning the s$nta8 o) Scheme and the structure o) )unctions, Speci)icall$! we need words to discuss the usage o) names )or +ariables! )unctions! and structures, For a simple e8ample! consider the )ollowing two de)initions:
!define"!f"*#"!+"!*"*"*#"25## !define"!g"*#"!*"12"!e*pt"*"5###

Clearl$! the underlined occurrences o) * in f are completel$ unrelated to the occurrences o) * in g, As mentioned be)ore! i) we s$stematicall$ replaced the underlined occurrences with 2! the )unction would still compute the e8act same numbers, In short! the underlined occurrences o) * mean something onl$ in the de)inition o) f and nowhere else, At the same time! the )irst occurrence o) * is di))erent )rom the others, 1hen we appl$ f to a number n! this occurrence completel$ disappearsE in contrast! the others are replaced with n, To distinguish these two )orms o) +ariable occurrences! we call the one to the right o) the )unction name BI-DI-= occurrence o) * and those in the bod$ the B@A-D occurrences o) *, 1e also sa$ that the binding occurrence o) * binds all occurrences o) * in the bod$ o) f! and )rom the discussion abo+e! the bod$ o) f is clearl$ the onl$ te8tual region o) the )unction where the underlined binding occurrence o) * can bind other occurrences, The name o) this region is *Cs "#NICA" SC@P#, 1e also sa$ that the de)initions o) f and g /or other de)initions in the Definitions window0 ha+e ="@BA" SC@P#, @n occasion! people also use the word FR## @CCARR#-C#, The description o) an application o) f to a number n suggests the )ollowing pictorial representation o) the de)inition:

The bullet o+er the )irst occurrence indicates that it is a binding occurrence, The arrow that originates )rom the bullet suggests the )low o) +alues, That is! when the +alue o) a binding occurrence becomes .nown! the bound occurrences recei+e their +alues )rom there, Put di))erentl$! when we .now which is the binding occurrence o) a +ariable! we .now where the +alue will come )rom during an e+aluation, Along similar lines! the scope o) a +ariable also dictates where we can rename it, I) we wish to rename a parameter! sa$! )rom * to 2! we search )or all bound occurrences in the

scope o) the parameter and replace them with 2, For e8ample! i) the )unction de)inition is the one )rom abo+e:
!define"!f"*#"!+"!*"*"*#"25##

renaming * to 2 a))ects two bound occurrences:


!define"!f"2#"!+"!*"2"2#"25##

-o other occurrences o) * outside o) the de)initions need to be changed, @b+iousl$ )unction de)initions also introduce a binding occurrence )or the )unction name, I) a de)inition introduces a )unction named f! the scope o) f is the entire se?uence o) de)initions:

That is! the scope o) f includes all de)initions abo+e and below the de)inition o) f, E ercise 1)<2<1< Here is a simple Scheme program:
!define"!p1"*"2#" ""!+"!*"*"2# """""!+"!*"2"*# !+"!*"2"2#"22#### !define"!p2"*# ""!+"!*"55"*#"!+"*"11### !define"!p3"*# ""!+"!p1"*"%# """""!+"!p1"*"1#"!p2"*####

Draw arrows )rom p1Cs * parameter to all its bound occurrences, Draw arrows )rom p1 to all bound occurrences o) p1, Cop$ the )unction and rename the parameter * o) p1 to a and the parameter * o) p3 to 8, Chec. the results with DrSchemeCs 7hec-"C2nta* button, Solution

In contrast to top2le+el )unction de)initions! the scope o) the de)initions in a local are limited, Speci)icall$! the scope o) local de)initions is the local2e8pression, Consider the

de)inition o) an au8iliar$ )unction f in a local2e8pression, It binds all occurrences within the local2e8pression but none that occur outside:

The two occurrences outside o) local are not bound b$ the local de)inition o) f, As alwa$s! the parameters o) a )unction de)inition! local or not! is onl$ bound in the )unctionCs bod$ and nowhere else:

Since the scope o) a )unction name or a )unction parameter is a te8tual region! people o)ten draw a bo8 to indicate some scope, More precisel$! )or parameters a bo8 is drawn around the bod$ o) a )unction:

In the case o) a local de)inition! the bo8 is drawn aorund the entire local2e8pression:

In this e8ample! the bo8 describes the scope o) the de)initions o) f and g, Asing a bo8 )or a scope! we can also easil$ understand what it means to reuse the name o) )unction inside a local2e8pression:

The inner bo8 describes the scope o) the inner de)inition o) fE the outer bo8 is the scope o) the outer de)inition o) f, Accordingl$! all occurrences o) f in the inner bo8 re)er to the inner localE all those in the outer bo8 re)er to the de)inition in the outer local, In other words! the scope o) the outer de)inition o) f has a hole: the inner bo8! which is the scope o) the inner de)inition o) f, Holes can also occur in the scope o) a parameter de)inition, Here is an e8ample:

In this )unction! the parameter * is used twice: )or the )unction f and )or g, The scope o) the latter is nested in the scope o) the )ormer and is thus a hole )or the scope o) the outer use o) *, In general! i) the same name occurs more than once in a )unction! the bo8es that describe the corresponding scopes ne+er o+erlap, In some cases the bo8es are nested within each other! which gi+es rise to holes, Still! the picture is alwa$s that o) a hierarch$ o) smaller and smaller nested bo8es, E ercise 1)<2<2< Here is a simple Scheme )unction:
66"sort":"+ist-of-n.m8ers""-/""+ist-of-n.m8ers !define"!sort"a+on# ""!local"!!define"!sort"a+on# """"!cond """"""9!empt2A"a+on#"empt2: """"""9!consA"a+on#"!insert"!first"a+on#"!sort"!rest"a+on###:## ""!define"!insert"an"a+on# """"!cond """"""9!empt2A"a+on#"!+ist"an#: """"""9else"!cond """"""9!/"an"!first"a+on##"!cons"an"a+on#: """"""9else"!cons"!first"a+on#"!insert"an"!rest a+on###:#:### """"!sort"a+on###

Draw a bo8 around the scope o) each binding occurrence o) sort and a+on, Then draw arrows )rom each occurrence o) sort to the matching binding occurrence, Solution

E ercise 1)<2<!< Recall that each occurrence o) a +ariable recei+es its +alue )rom the corresponding binding occurrence, Consider the )ollowing de)inition:
!define"*"!cons"1"*##

1here is the underlined occurrence o) * boundH Since the de)inition is a +ariable de)inition and not a )unction de)inition! we need to e+aluate the right2hand side i) we wish to wor. with this )unction, 1hat is the +alue o) the right2hand side according to our rulesH Solution

As we e+aluate e8pressions in this manner! our list o) de)initions grows longer and longer, Fortunatel$! DrScheme .nows how to manage such growing lists, Indeed! it occasionall$ throws out de)initions that will ne+er be used again,
66

Part I" +bstracting Designs Section 1Similarities in Definitions


Man$ o) our data de)initions and )unction de)initions loo. ali.e, For e8ample! the de)inition )or a list o) s$mbols di))ers )rom that o) a list o) numbers in onl$ two regards: the name o) the class o) data and the words DDs$mbolCC and DDnumber,CC Similarl$! a )unction that loo.s )or a speci)ic s$mbol in a list o) s$mbols is nearl$ indistinguishable )rom one that loo.s )or a speci)ic number in a list o) numbers, Repetitions are the source o) man$ programming mista.es, There)ore good programmers tr$ to a+oid repetitions as much as possible, As we de+elop a set o) )unctions! especiall$ )unctions deri+ed )rom the same template! we soon learn to spot similarities, It is then time to re+ise the )unctions so as to eliminate the repetitions as much as possible, Put di))erentl$! a set o) )unctions is Fust li.e an essa$ or a memo or a no+el or some other piece o) writing: the )irst dra)t is Fust a dra)t, Anless we edit the essa$ se+eral times! it does not e8press our ideas clearl$ and concisel$, It is a pain )or others to read it, Because )unctions are read b$ man$ other people and because real )unctions are modi)ied a)ter reading! we must learn to DDeditCC )unctions, The elimination o) repetitions is the most important step in the /program0 editing process, In this section! we discuss similarities in )unction de)initions and in data de)initions and how to a+oid them, @ur means o) a+oiding similarities are speci)ic to Scheme and )unctional programming languagesE still! other languages! in particular obFect2oriented ones! support similar mechanisms )or )actoring out similarities 22 or /code0 patterns as the$ are somtimes called,

$6#$ Similarities in +unctions


The use o) our design recipes entirel$ determines a )unctionCs template 22 or basic organi*ation 22 )rom the data de)inition )or the input, Indeed! the template is an

alternati+e method o) e8pressing what we .now about the input data, -ot surprisingl$! )unctions that consume the same .ind o) data loo. ali.e,
66"contains-do++A":"+os""-/" 8oo+ean 66"to"determine"whether"a+os contains" 66"the"s2m8o+"'do++ !define"!contains-do++A"a+os# ""!cond """"9!empt2A"a+os#"fa+se: """"9else """"""!cond 9!s2m8o+&A"!first"a+os# Kdo++# "tr.e: 9else" "!contains-do++A"!rest a+os##:#:## 66"contains-carA":"+os""-/" 8oo+ean 66"to"determine"whether"a+os contains" 66"the"s2m8o+"'car !define"!contains-carA"a+os# ""!cond """"9!empt2A"a+os#"fa+se: """"9else """"""!cond 9!s2m8o+&A"!first"a+os# Kcar# "tr.e: 9else" "!contains-carA"!rest a+os##:#:##

Figure $2' Two similar )unctions Ta.e a loo. at the two )unctions in )igure 7&! which consume lists o) s$mbols /names o) to$s0 and loo. )or speci)ic to$s, The )unction on the le)t loo.s )or 'do++! the one on the right )or 'car in a list o) s$mbols /los0, The two )unctions are nearl$ indistinguishable, #ach consumes lists o) s$mbolsE each )unction bod$ consists o) a cond2e8pressions with two clauses, #ach produces fa+se i) the input is empt2E each uses a second! nested cond2e8pression to determine whether the )irst item is the desired item, The onl$ di))erence is the s$mbol that is used in the comparison o) the nested cond2e8pression: contains-do++A uses 'do++ and contains-carA uses 'car! o) course, To highlight the di))erences! the two s$mbols are bo8ed, =ood programmers are too la*$ to de)ine se+eral closel$ related )unctions, Instead the$ de)ine a single )unction that can loo. )or both a 'do++ and a 'car in a list o) to$s, This more general )unction consumes an additional piece o) data! the s$mbol that we are loo.ing )or! but is otherwise li.e the two original )unctions:
66"containsA":"s2m8o+"+os""-/""8oo+ean 66"to"determine"whether"a+os"contains"the"s2m8o+"s !define"!containsA"s"a+os# ""!cond """"9!empt2A"a+os#"fa+se: """"9else"!cond """"9!s2m8o+&A"!first"a+os#"s# """""""""""""tr.e: """"9else" """""!containsA"s"!rest"a+os##:#:##

1e can now loo. )or 'do++ b$ appl$ing containsA to 'do++ and a list o) s$mbols, But containsA wor.s )or an$ other s$mbol! too, De)ining the single +ersion has sol+ed man$ related problems at once, The process o) combining two related )unctions into a single de)inition is called FA-CTI@-A" ABSTRACTI@-, De)ining abstract +ersions o) )unctions is highl$

bene)icial, The )irst bene)it is that a single )unction can per)orm man$ di))erent tas.s, In our )irst e8ample! containsA can search )or man$ di))erent s$mbols instead o) Fust one concrete s$mbol,67
66"8e+ow":"+on"n.m8er""-/" +on 66"to"constr.ct"a"+ist"of those"n.m8ers" 66"on"a+on"that"are"8e+ow"t !define"!8e+ow"a+on"t# ""!cond """"9!empt2A"a+on#"empt2: """"9else """"""!cond 9!?"!first"a+on#"t# "!cons"!first"a+on# """!8e+ow"!rest"a+on# t##: 9else "!8e+ow"!rest"a+on# t#:#:## 66"a8o0e":"+on"n.m8er""-/" +on 66"to"constr.ct"a"+ist"of those"n.m8ers" 66"on"a+on"that"are"a8o0e"t !define"!a8o0e"a+on"t# ""!cond """"9!empt2A"a+on#"empt2: """"9else """"""!cond 9!/"!first"a+on#"t#" "!cons"!first"a+on# """!a8o0e"!rest"a+on# t##: 9else "!a8o0e"!rest"a+on# t#:#:##

Figure $!' Two more similar )unctions In the case o) contains-do++A and contains-carA! abstraction is uninteresting, There are! howe+er! more interesting cases: see )igure 75, The )unction on the le)t consumes a list o) numbers and a threshold and produces a list o) all those numbers that are below the thresholdE the one on the right produces all those that are abo+e a threshold, The di))erence between the two )unctions is the comparison operator, The le)t uses U! the right one S, Following the )irst e8ample! we abstract o+er the two )unctions with an additional parameter that stands )or the concrete relational operator in 8e+ow and a8o0e:
!define"!fi+ter1"re+-op"a+on"t# ""!cond """"9!empt2A"a+on#"empt2: """"9else"!cond """"9!re+-op"!first"a+on#"t#" """""!cons"!first"a+on# """""""""""!fi+ter1"re+-op"!rest"a+on#"t##: """"9else """""!fi+ter1"re+-op"!rest"a+on#"t#:#:##

To appl$ this new )unction! we must suppl$ three arguments: a relational operator Q that compares two numbers! a list L o) numbers! and a number J, The )unction then e8tracts all those items i in L )or which !Q"i"J# e+aluates to true, Since we do not .now how to write down contracts )or )unctions li.e fi+ter1! we omit the contract )or now, 1e will discuss the problem o) contracts in section &',& below, "et us see how fi+ter1 wor.s with an e8ample, Clearl$! as long as the input list is empt2! the result is empt2! too! no matter what the other arguments are:
""!fi+ter1"?"empt2"5# &"empt2

So ne8t we loo. at a slightl$ more complicated case:


""!fi+ter1"?"!cons"4"empt2#"5#

The result should be !cons"4"empt2# because the onl$ item o) this list is 4 and !?"4 5# is true, The )irst step o) the e+aluation is based on the rule o) application:
""!fi+ter1"?"!cons"4"empt2#"5# &"!cond """"9!empt2A"!cons"4"empt2##"empt2: """"9else"!cond """"9!?"!first"!cons"4"empt2##"5#" """""!cons"!first"!cons"4"empt2## """""""""""!fi+ter1"?"!rest"!cons"4"empt2##"5##: """"9else"!fi+ter1"?"!rest"!cons"4"empt2##"5#:#:#

That is! it is the bod$ o) fi+ter1 with all occurrences o) re+-op replaced b$ ?! t replaced b$ 5! and a+on replaced b$ !cons"4"empt2#, The rest o) the e+aluation is straight)orward:
""!cond """"9!empt2A"!cons"4"empt2##"empt2: """"9else"!cond """"9!?"!first"!cons"4"empt2##"5#" """""!cons"!first"!cons"4"empt2## """""""""""!fi+ter1"?"!rest"!cons"4"empt2##"5##: """"9else"!fi+ter1"?"!rest"!cons"4"empt2##"5#:#:# &"!cond """"9!?"!first"!cons"4"empt2##"5# """""!cons"!first"!cons"4"empt2## """""""""""!fi+ter1"?"!rest"!cons"4"empt2##"5##: """"9else"!fi+ter1"?"!rest"!cons"4"empt2##"5#:# &"!cond """"9!?"4"5#"!cons"!first"!cons"4"empt2## """""""""""""""""""!fi+ter1"?"!rest"!cons"4"empt2##"5##: """"9else"!fi+ter1"?"!rest"!cons"4"empt2##"5#:# &"!cond """"9tr.e"!cons"!first"!cons"4"empt2## """"""""""""""!fi+ter1"?"!rest"!cons"4"empt2##"5##: """"9else"!fi+ter1"?"!rest"!cons"4"empt2##"5#:# &"!cons"4"!fi+ter1"?"!rest"!cons"4"empt2##"5## &"!cons"4"!fi+ter1"?"empt2"5## &"!cons"4"empt2#

The last step is the e?uation we discussed as our )irst case, @ur )inal e8ample is an application o) fi+ter1 to a list o) two items:

""!fi+ter1"?"!cons" "!cons"4"empt2##"5# &"!fi+ter1"?"!cons"4"empt2#"5# &"!cons"4"!fi+ter1"?"empt2"5## &"!cons"4"empt2#

The onl$ new step is the )irst one, It sa$s that fi+ter1 determines that the )irst item on the list is not less than the threshold! and that it there)ore is not added to the result o) the natural recursion, E ercise 1-<1<1< 4eri)$ the e?uation
""!fi+ter1"?"!cons" "!cons"4"empt2##"5# &"!fi+ter1"?"!cons"4"empt2#"5#

with a hand2e+aluation that shows e+er$ step, E ercise 1-<1<2< #+aluate the e8pression

Solution

""!fi+ter1"/"!cons"$"!cons" "!cons"4"empt2###"5#

b$ hand, Show onl$ the essential steps,

Solution

The calculations show that !fi+ter1"?"a+on"t# computes the same result as !8e+ow a+on"t#! which is what we e8pected, Similar reasoning shows that !fi+ter1"/"a+on t# produces the same output as !a8o0e"a+on"t#, So suppose we de)ine the )ollowing:
66"8e+ow1":"+on"n.m8er""-/" 66"a8o0e1":"+on"n.m8er""-/" +on +on !define"!8e+ow1"a+on"t# !define"!a8o0e1"a+on"t#" ""!fi+ter1"?"a+on"t## ""!fi+ter1"/"a+on"t## Clearl$! 8e+ow1 produces the same results as 8e+ow when gi+en the same inputs! and a8o0e1 is related to a8o0e in the same manner, In short! we ha+e de)ined 8e+ow and a8o0e as one2liners using fi+ter1,

Better $et: once we ha+e an abstract )unction li.e fi+ter1! we can put it to other uses! too, Here are three o) them: (, !fi+ter1"&"a+on"t#: This e8pression e8tracts all those numbers in a+on that are e?ual to t, &, !fi+ter1"?&"a+on"t#: This one produces the list o) numbers in a+on that are less than or e?ual to t, 5, !fi+ter1"/&"a+on"t#: This last e8pression computes the list o) numbers that are greater than or e?ual to the threshold,

In general! fi+ter1Cs )irst argument need not e+en be one o) SchemeCs prede)ined operationsE it can be an$ )unction that consumes two numbers and produces a boolean +alue, Consider the )ollowing e8ample:
66"s).ared/A":"n.m8er"n.m8er""-/""8oo+ean !define"!s).ared/A"*"c# ""!/"!*"*"*#"c##

The )unction produces tr.e whene+er the area o) a s?uare with side * is larger than some threshold c! that is! the )unction tests whether the claim +& S c holds, 1e now appl$ fi+ter1 to this )unction and a list o) numbers:
!fi+ter1"s).ared/A"!+ist"1"2"3"4"5#"1%#

This particular application e8tracts those numbers in !+ist"1"2"3"4"5# whose s?uare is larger than 1%, Here is the beginning o) a simple hand2e+aluation:
""!fi+ter1"s).ared/A"!+ist"1"2"3"4"5#"1%# &"!cond """"9!empt2A"!+ist"1"2"3"4"5##"empt2: """"9else"!cond """"9!s).ared/A"!first"!+ist"1"2"3"4"5##"1%#" """""!cons"!first"!+ist"1"2"3"4"5## """""""!fi+ter1"s).ared/A"!rest"!+ist"1"2"3"4"5##"1%##: """"9else """"""!fi+ter1"s).ared/A"!rest"!+ist"1"2"3"4"5##"1%#:#:#

That is! we appl$ our standard law o) application and calculate otherwise as usual:
&"!cond """"9!s).ared/A"1"1%#" """""!cons"!first"!+ist"1"2"3"4"5## """""""!fi+ter1"s).ared/A"!rest"!+ist"1"2"3"4"5##"1%##: """"9else """""!fi+ter1"s).ared/A"!rest"!+ist"1"2"3"4"5##"1%#:# &"!cond """"9fa+se" """""!cons"!first"!+ist"1"2"3"4"5## """""""!fi+ter1"s).ared/A"!rest"!+ist"1"2"3"4"5##"1%##: """"9else """""!fi+ter1"s).ared/A"!rest"!+ist"1"2"3"4"5##"1%#:#

The last step consists o) se+eral steps concerning s).ared/A! which we can s.ip at this point:
&"!fi+ter1"s).ared/A"!+ist"2"3"4"5#"1%# &"!fi+ter1"s).ared/A"!+ist"3"4"5#"1%# &"!fi+ter1"s).ared/A"!+ist"4"5#"1%#

1e lea+e the remainder o) the e+aluation to the e8ercises, E ercise 1-<1<!< Show that

""!fi+ter1"s).ared/A"!+ist"4"5#"1%# &"!cons"4"!fi+ter1"s).ared/A"!+ist"5#"1%##

with a hand2e+aluation, Act as i) s).ared/A were primiti+e,

Solution

E ercise 1-<1<#< The use o) s).ared/A also suggests that the )ollowing )unction will wor.! too:
66"s).ared1%A":"n.m8er"n.m8er""-/""8oo+ean !define"!s).ared1%A"*"c# ""!/"!s)r"*#"1%##

In other words! the relational )unction that fi+ter1 uses ma$ ignore its second argument, A)ter all! we alread$ .now it and it sta$s the same throughout the e+aluation o) !fi+ter1"s).ared/A"a+on"t#, This! in turn! implies another simpli)ication o) the )unction:
!define"!fi+ter"predicate"a+on# ""!cond """"9!empt2A"a+on#"empt2: """"9else"!cond """"9!predicate"!first"a+on##" """""!cons"!first"a+on# """""""!fi+ter"predicate"!rest"a+on###: """"9else """""!fi+ter"predicate"!rest"a+on##:#:##

The )unction fi+ter consumes onl$ a relational )unction! called predicate! and a list o) numbers, #+er$ item i on the list is chec.ed with predicate, I) !predicate"i# holds! i is included in the outputE i) not! i does not appear in the result, Show how to use fi+ter to de)ine )unctions that are e?ui+alent to 8e+ow and a8o0e, Test the de)initions, Solution So )ar we ha+e seen that abstracted )unction de)initions are more )le8ible and more widel$ usable than speciali*ed de)initions, A second! and in practice e?uall$ important! ad+antage o) abstracted de)initions is that we can change a single de)inition to )i8 and impro+e man$ di))erent uses, Consider the two +ariants o) fi+ter1 in )igure 76, The )irst +ariant )lattens the nested cond2e8pression! something that an e8perienced programmer ma$ wish to do, The second +ariant uses a local2e8pression that ma.es the nested cond2e8pression more readable,

!define"!fi+ter1"re+-op a+on"t# ""!cond """"9!empt2A"a+on#"empt2: """"9!re+-op"!first"a+on# t#" """""!cons"!first"a+on# """""""!fi+ter1"re+-op !rest"a+on#"t##: """"9else """"""!fi+ter1"re+-op !rest"a+on#"t#:##

!define"!fi+ter1"re+-op"a+on"t# ""!cond """"9!empt2A"a+on#"empt2: """"9else """"""!local"!!define"firstitem"!first"a+on## """"""!define"rest-fi+tered !fi+ter1"re+-op !rest"a+on#"t### !cond ""9!re+-op"first-item"t#" """!cons"first-item"restfi+tered#: ""9else """rest-fi+tered:##:##

Figure $#' Two modi)ications o) fi!ter1 Although both o) these changes are tri+ial! the .e$ is that all uses o) fi+ter1! including those to de)ine the )unctions 8e+ow1 and a8o0e1! bene)it )rom this change, Similarl$! i) the modi)ication had )i8ed a logical mista.e! all uses o) the )unction would be impro+ed, Finall$! it is e+en possible to add new tas.s to abstracted )unctions! )or e8ample! a mechanism )or counting how man$ elements are )iltered, In that case all uses o) the )unction would bene)it )rom the new )unctionalit$, 1e will encounter this )orm o) impro+ement later, E ercise 1-<1<$< Abstract the )ollowing two )unctions into a single )unction:
66"mini":"ne+on""-/""n.m8er 66"to"determine"the"sma++est n.m8er 66"on"a+on !define"!mini"a+on# ""!cond """"9!empt2A"!rest"a+on## !first"a+on#: """"9else"!cond """"9!?"!first"a+on#" !mini"!rest a+on### """""!first"a+on#: """"9else """""!mini"!rest a+on##:#:## 66"ma*i":"ne+on""-/""n.m8er 66"to"determine"the"+argest n.m8er 66"on"a+on !define"!ma*i"a+on# ""!cond """"9!empt2A"!rest"a+on## !first"a+on#: """"9else"!cond """"9!/"!first"a+on# !ma*i"!rest a+on### """""!first"a+on#: """"9else """""!ma*i"!rest a+on##:#:##

Both consume non2empt$ lists o) numbers and produce a single number, The le)t one produces the smallest number in the list! the right one the largest, De)ine mini1 and ma*i1 in terms o) the abstracted )unction, Test each o) them with the )ollowing three lists: (, !+ist"3"7" "2","$#

&, !+ist"2%"1,"1$"17"1 "15"14"13"12"11"1%","$"7" "5"4"3"2"1# 5, !+ist"1"2"3"4"5" "7"$","1%"11"12"13"14"15"1 "17"1$"1,"2%# 1h$ are the$ slow on the long listsH Impro+e the abstracted )unction, First! introduce a local name )or the result o) the natural recursion, Then introduce a local! au8iliar$ )unction that pic.s the DDinterestingCC one o) two numbers, Test mini1 and ma*i1 with the same inputs again, Solution E ercise 1-<1<&< Recall the de)inition o) sort! which consumes a list o) numbers and produces a sorted +ersion:
66"sort":"+ist-of-n.m8ers""-/""+ist-of-n.m8ers 66"to"constr.ct"a"+ist"with"a++"items"from"a+on"in"descending order !define"!sort"a+on# ""!local"!!define"!sort"a+on# """"!cond """"""9!empt2A"a+on#"empt2: """"""9else"!insert"!first"a+on#"!sort"!rest"a+on###:## ""!define"!insert"an"a+on# """"!cond """"""9!empt2A"a+on#"!+ist"an#: """"""9else"!cond """"""9!/"an"!first"a+on##"!cons"an"a+on#: """"""9else"!cons"!first"a+on#"!insert"an"!rest a+on###:#:### """"!sort"a+on###

De)ine an abstract +ersion o) sort that consumes the comparison operation in addition to the list o) numbers, Ase the abstract +ersion to sort !+ist"2"3"1"5"4# in ascending and descending order, Solution

$6#" Similarities in Data Definitions


Inspect the )ollowing two data de)initions:

A !ist-of-n mbers is either

A !ist-of-I:s is either

empt$ /cons n l0 where n is a number and n is a list2o)2numbers,

empt$ /cons n l0 where n is an IR and n is a list2o)2IRs,

Both de)ine a class o) lists, The one on the le)t is the data de)inition )or lists o) numbersE the one on the right describes lists o) in+entor$ records! which we represent with structures, The necessar$ structure and data de)initions )ollow:
!define-struct"ir"!name"price##

An I: is a structure:
!ma-e-ir"n"p#

where n is a s$mbol and p is a number, =i+en the similarit$ between the data de)initions! )unctions that consume elements o) these classes are similar! too, Ta.e a loo. at the illustrati+e e8ample in )igure 77, The )unction on the le)t is the )unction 8e+ow! which )ilters numbers )rom a list o) numbers, The one on the right is 8e+ow-ir! which e8tracts those in+entor$ records )rom a list whose prices are below a certain threshold, #8cept )or the name o) the )unction! which is arbitrar$! the two de)initions di))er in onl$ one point: the relational operator,
66"8e+ow":"n.m8er"+on""-/" +on 66"to"constr.ct"a"+ist"of those"n.m8ers 66"on"a+on"that"are"8e+ow"t !define"!8e+ow"a+on"t# ""!cond """"9!empt2A"a+on#"empt2: """"9else"!cond """"9!?"!first"a+on#"t# """""!cons"!first"a+on# """""""!8e+ow"!rest a+on#"t##: """"9else """"""!8e+ow"!rest"a+on# t#:#:## 66"8e+ow-ir":"n.m8er"+oIQ "-/""+oIQ 66"to"constr.ct"a"+ist"of those"records" 66"on"a+oir"that"contain"a price"8e+ow"t !define"!8e+ow"a+oir"t# ""!cond """"9!empt2A"a+oir#"empt2: """"9else"!cond """"9!?ir"!first"a+oir#"t# """""!cons"!first"a+oir# """"""!8e+ow-ir"!rest a+oir#"t##: """"9else """"""!8e+ow-ir"!rest a+oir#"t#:#:## 66"?ir":"IQ"n.m8er""-/" 8oo+ean !define"!?ir"ir"p# """"!?"!ir-price"ir#"p##

Figure $$' Mar.ing the di))erences in similar )unctions I) we abstract the two )unctions! we ob+iousl$ obtain fi+ter1, Con+ersel$! we can de)ine 8e+ow-ir in terms o) fi+ter1:

!define"!8e+ow-ir1"a+oir"t# ""!fi+ter1"?ir"a+oir"t##

It should not surprise us to disco+er $et another use )or fi+ter1 22 a)ter all! we alread$ argued that abstraction promotes the reuse o) )unctions )or di))erent purposes, Here we see that fi+ter1 not onl$ )ilters lists o) numbers but lists o) arbitrar$ things 22 as long as we can de)ine a )unction that compares these arbitrar$ things with numbers, Indeed! all we need is a )unction that compares items on the list with the items we pass to fi+ter1 as the second argument, Here is a )unction that e8tracts all items with the same label )rom a list o) in+entor$ records:
66"find":"+oIQ"s2m8o+""-/""8oo+ean 66"to"determine"whether"a+oir"contains"a"record"for"t !define"!find"a+oir"t# ""!consA"!fi+ter1"e)-irA"a+oir"t### 66"e)-irA":"IQ"s2m8o+""-/""8oo+ean 66"to"compare"irKs"name"and"p !define"!e)-irA"ir"p# ""!s2m8o+&A"!ir-name"ir#"p##

This new relational operator compares the name in an in+entor$ record with some other s$mbol, E ercise 1-<2<1< Determine the +alues o) (, !8e+ow-ir1"1%"!+ist"!ma-e-ir"'do++"$#"!ma-e-ir"'ro8ot"12### &, !find"'do++"!+ist"!ma-e-ir"'do++"$#"!ma-e-ir"'ro8ot"12#"!ma-e-ir
'do++"13###

b$ hand and with DrScheme, Show onl$ those lines that introduce new applications o) fi+ter1 to +alues, Solution In short! fi+ter1 uni)orml$ wor.s on man$ shapes o) input data, The word DDuni)orml$CC means that i) fi+ter1 is applied to a list o) R! its result is also a list o) R 22 no matter what .ind o) Scheme data R is, Such )unctions are called P@"3M@RPHIC69 or =#-#RIC )unctions, @) course! fi+ter1 is not the onl$ )unction that can process arbitrar$ lists, There are man$ other )unctions that process lists independentl$ o) what the$ contain, Here are two )unctions that determine the length o) lists o) numbers and IQs:

66"+ength-+on":"+on""-/" n.m8er !define"!+ength-+on"a+on# ""!cond """"9!empt2A"a+on#"empt2: """"9else" """"""!+"!+ength-+on"!rest a+on##"1#:##

66"+ength-ir":"+oIQ""-/" n.m8er !define"!+ength-ir"a+on# ""!cond """"9!empt2A"a+on#"empt2: """"9else """"""!+"!+ength-ir"!rest a+on##"1#:##

The two )unctions di))er onl$ in their names, I) we had chosen the same name! sa$! +ength! the two de)initions would be identical, To write precise contracts )or )unctions such as +ength! we need data de)initions with parameters, 1e call these PARAM#TRIC DATA D#FI-ITI@-S and agree that the$ do not speci)$ e+er$thing about a class o) data, Instead the$ use +ariables to sa$ that an$ )orm o) Scheme data can be used in a certain place, Roughl$ spea.ing! a parametric data de)inition abstracts )rom a re)erence to a particular collection o) data in the same manner as a )unction abstracts )rom a particular +alue, Here is a parametric de)inition o) lists o) I;5Hs: A !ist of IT)M is either (, empt2 or &, !cons"s"+# where a, s is an IT#M and b, + is a list o) IT#M, The to.en I;5H is a T3P# 4ARIAB"# that stands )or an$ arbitrar$ collection o) Scheme data: s$mbols! numbers! booleans! IQs! etc, B$ replacing I;5H with one o) these names! we get a concrete instance o) this abstract data de)inition )or lists o) s$mbols! numbers! booleans! IQs! etc, To ma.e the language o) contracts more concise! we introduce an additional abbre+iation:
!listof"I;5H#

1e use !listof"I;5H# as the name o) abstract data de)initions such as the abo+e, Then we can use !listof"s2m8o+# )or the class o) all lists o) s$mbols! !listof"n.m8er# )or the class o) all lists o) numbers! !listof"!listof"n.m8er## )or the class o) all lists o) lists o) numbers! etc, In contracts we use !listof"R# to sa$ that a )unction wor.s on all lists:

66"+ength":"!listof"R#""-/""n.m8er 66"to"comp.te"the"+ength"of"a"+ist" !define"!+ength"a+on# ""!cond """"9!empt2A"a+on#"empt2: """"9else"!+"!+ength"!rest"a+on##"1#:##

The R is Fust a +ariable! a name that stands )or some class o) data, I) we now appl$ +ength to an element o)! sa$! !listof"s2m8o+# or !listof"IQ#! we get a number, The )unction +ength is an e8ample o) simple pol$morphism, It wor.s on all classes o) lists, 1hile there are other use)ul e8amples o) simple pol$morphic )unctions! the more common cases re?uire that we de)ine )unctions li.e fi+ter1! which consume a parametric )orm o) data and )unctions that wor. on this data, This combination is e8tremel$ power)ul and greatl$ )acilitates the construction and maintenance o) so)tware s$stems, To understand it better! we will ne8t discuss a re+ision o) SchemeCs grammar and new wa$s to write contracts, E ercise 1-<2<2< Show how to use the abstracted +ersion o) sort )rom e8ercise (>,(,9 to sort a list o) IQs in ascending and descending order, Solution E ercise 1-<2<!< Here is a structure de)inition )or pairs
!define-struct"pair"!+eft"right##

and its parametric data de)inition: A ;pair " #< is a structure:


!ma-e-pair"+"r#

where + is an R and r is a I, Asing this abstract data de)inition! we can describe man$ di))erent )orms o) pairs: (, !pair"n.m8er"n.m8er#! which is the class o) pairs that combine two numbersE &, !pair"s2m8o+"n.m8er#! which is the class o) pairs that combine a number with a s$mbolE and 5, !pair"s2m8o+"s2m8o+#! which is the class o) pairs that combine two s$mbols, Still! in all o) these e8amples! each pair contains two +alues that are accessible +ia pair-+eft and pair-right,

B$ combining the abstract data de)inition )or lists and pairs we can describe lists o) parametric pairs with a single line:
!listof"!pair"R"I##

Some concrete e8amples o) this abstract class o) data are: (, !listof"!pair"n.m8er"n.m8er##! the list o) pairs o) numbersE &, !listof"!pair"s2m8o+"n.m8er##! the list o) pairs o) s$mbols and numbersE 5, !listof"!pair"s2m8o+"s2m8o+##! the list o) pairs o) s$mbols, Ma.e an e8ample )or each o) these classes, De+elop the )unction +efts! which consumes a list o) !pair"R"I# and produces a corresponding list o) RCsE that is! it e8tracts the +eft part o) each item in its input, Solution E ercise 1-<2<#< Here is a parametric data de)inition o) non2empt$ lists: A $non!empty!listof %&'() is either (, !cons"s"empt2#! or &, !cons"s"+# where + is a !non-empt2-+istof"I;5H# and s is alwa$s an I;5H, De+elop the )unction +ast! which consumes a !non-empt2-+istof"I;5H# and produces the last I;5H in that list, >int' Replace I;5H with a )i8ed class o) data to de+elop an initial dra)t o) +ast, 1hen )inished! replace the class with I;5H throughout the )unction de+elopment, Solution

Computing borrows the term DDabstractCC )rom mathematics, A mathematician re)ers to DD9CC as an abstract number because it onl$ represents all di))erent wa$s o) naming si8 things, In contrast! DD9 inchesCC or DD9 eggsCC are concrete instances o) DD9CC because the$ e8press a measurement and a count,
67

69

The word DDpol$CC means DDman$CC and DDmorphicCC means shape,

Section 2. Functions are "alues


The )unctions o) section (> stretch our understanding o) e+aluation, It is eas$ to understand how )unctions consume numbers and s$mbolsE cosuming structures and lists is a bit more complicated! but still within our graspE but )unctions consuming )unctions is a strange idea, As a matter o) )act! the )unctions o) section (> +iolate the Scheme grammar o) section <, In this section! we discuss how to adFust SchemeCs grammar and e+aluation rules so that we can understand the role o) )unctions as data or +alues, 1ithout a good understanding o) these ideas! we cannot hope to abstract )unctions, @nce we understand these ideas! we can turn to the problem o) writing contracts )or such )unctions, Finall$! the last part o) the section introduces )unctions that produce )unctions! another power)ul abstraction techni?ue,

"8#$ Synta, and Semantics


The abstract )unctions o) section (> +iolate SchemeCs basic grammar in two wa$s, First! the names o) )unctions and primiti+e operations are used as arguments in applications, An argument! though! is an e8pression! and the class o) e8pressions does not contain primiti+e operations and )unction names, It does contain +ariables! but we agreed that the$ are onl$ those +ariables mentioned in +ariable de)initions and as )unction parameters, Second! parameters are used as i) the$ were )unctions! that is! the )irst position o) applications, But the grammar o) section < allows onl$ the names o) )unctions and primiti+e operations in this place,

O /define /?0ar/ ?0ar/ ...?0ar/0 ?e*p/0 X /define ?0ar/ ?e*p/0 X /define2struct ?0ar/ /?0ar/ ?0ar/ ...?0ar/00 ?e*p/ O ?0ar/ X ?8oo/ X ?s2m/ X ?prm/ X empt$ X /?e*p/ ?e*p/ ...?e*p/0 X /cond /?e*p/ ?e*p/0 .../?e*p/ ?e*p/00 X /cond /?e*p/ ?e*p/0 .../else ?e*p/00 X /local /?def/ ...?def/0 ?e*p/0
?def/

O * X area-of-dis- X circ.mference X ... ?8oo/ O tr.e X fa+se ?s2m/ O 'a X 'do++ X 's.m X ... ?n.m/ O 1 X -1 X 3/5 X 1.22 X ... ?prm/ O + X - X cons X first X rest X ... Figure $&' Intermediate"Ct.dent Scheme: The grammar
?0ar/

Spelling out the problem suggests the necessar$ changes, First! we should include the names o) )unctions and primiti+e operations in the de)inition o) ?e*p/, Second! the )irst position in an application should allow things other than )unction names and primiti+e operationsE at a minimum! it must allow +ariables that pla$ the role o) )unction parameters, In anticipation o) other uses o) )unctions! we agree on allowing e8pressions in that position, Here is a summar$ o) the three changes: O ?0ar/ X ?prm/ X /?e*p/ ?e*p/ ...?e*p/0 Figure 79 displa$s the entire Scheme grammar! with all the e8tensions we ha+e encountered so )ar, It shows that the accommodation o) abstract )unctions does not lengthen the grammar! but ma.es it simpler,
?e*p/

The same is true o) the e+aluation rules, Indeed! the$ donCt change at all, 1hat changes is the set o) +alues, To accommodate )unctions as arguments o) )unctions! the simplest change is to sa$ that the set o) +alues includes the names o) )unctions and primiti+e operations:

O ?8oo/ X ?s2m/ X ?n.m/ X empt$ X ?+st/ X ?0ar/ /names o) defined )unctions0 X ?prm/ ?+st/ O empt$ X /cons ?0a+/ ?+st/0
?0a+/

Put di))erentl$! i) we now wish to decide whether we can appl$ the substitution rule )or )unctions! we must still ensure that all arguments are +alues! but we must recogni*e that )unction names and primiti+e operations count as +alues! too, E ercise 2.<1<1< Assume the Definitions window in DrScheme contains !define !f"*#"*#, Identi)$ the +alues among the )ollowing e8pressions: (, !cons"f"empt2# &, !f"f# 5, !cons"f"!cons"1%"!cons"!f"1%#"empt2### #8plain wh$ the$ are +alues and wh$ the remaining e8pressions are not +alues, Solution E ercise 2.<1<2< Argue wh$ the )ollowing sentences are legal de)initions: (, !define"!f"*#"!*"1%## &, !define"!f"*#"f# 5, !define"!f"*"2#"!*"'a"2"'8##

Solution E ercise 2.<1<!< De+elop a-f.nction&A, The )unction determines whether two )unctions )rom numbers to numbers produce the same results )or 1.2! 3! and -5.7,

Can we hope to de)ine f.nction&A! which determines whether two )unctions /)rom numbers to numbers0 are e?ualH Solution

"8#" Contracts for

&stract and Polymorphic +unctions

1hen we )irst abstracted 8e+ow and a8o0e into fi+ter1! we did not )ormulate a contract, Anli.e the )unctions we had de)ined be)ore! fi+ter1 consumed a t$pe o) +alues that we ne+er be)ore used as data: primiti+e operations and other )unctions, Still! we e+entuall$ agreed in plain #nglish writing that fi+ter1Cs )irst argument! re+-op! would alwa$s be a )unction that consumes two numbers and produces a boolean +alue, I)! in the past! we had been as.ed to write a contract )or re+-op! we would ha+e written
66"re+-op":"n.m8er"n.m8er""-/""8oo+ean

Considering that )unctions and primiti+e operations are +alues! this contract sa$s that an arrow s$mbol! "-/"! describes a class o) +alues: )unctions and primiti+e operations, The names on the le)t o) "-/" speci)$ what each +alue in the class o) )unctions must be applied toE the name on the right sa$s what each +alue is going to produce i) it is applied to proper +alues, In general! we sa$ that
!'"(""-/""7#

means the class o) all )unctions and primiti+es that consume an element in ' and an element in ( and produce an element in 7, @r more succinctl$! the$ are )unctions DD)rom ' and ( to 7,CC The arrow notation is li.e the !listof"...# notation )rom the pre+ious section, Both speci)$ a class o) data +ia a combination o) other classes, For listof! we used data de)initions to agree on what the$ mean, @thers can )ollow the e8ample and introduce their own abbre+iations based on data de)initions, For arrows! we Fust made an agreement! and it sta$s with us )or good, Asing the arrow notation! we can )ormulate a )irst contract and a proper purpose statement )or fi+ter1:
66"fi+ter1":"!n.m8er"n.m8er""-/""8oo+ean#"+on"n.m8er""-/""+on" 66"to"constr.ct"the"+ist"of"those"n.m8ers"n"on"a+on"for"which 66"!re+-op"n"t#"e0a+.ates"to"tr.e !define"!fi+ter1"re+-op"a+on"t#"...#

The unusual part o) the contract is that it speci)ies the class to which the )irst argument must belong not with a name introduced b$ a data de)inition but with a direct data de)inition! using the arrow notation, More concretel$! it speci)ies that the )irst argument must be a )unction or a primiti+e operation and! as discussed! what .ind o) arguments it consumes and what .ind o) +alue it produces,

E ercise 2.<2<1< #8plain the )ollowing classes o) )unctions: (, !n.m8er""-/""8oo+ean#! &, !8oo+ean"s2m8o+""-/""8oo+ean#! 5, !n.m8er"n.m8er"n.m8er""-/""n.m8er#! 6, !n.m8er""-/""!listof"n.m8er##! and

7, !!listof"n.m8er#""-/""8oo+ean#,

Solution

E ercise 2.<2<2< Formulate contracts )or the )ollowing )unctions: (, sort! which consumes a list o) numbers and a )unction that consumes two numbers /)rom the list0 and produces a booleanE sort produces a list o) numbers, &, map! which consumes a )unction )rom numbers to numbers and a list o) numbersE it also produces a list o) numbers, 5, proSect! which consumes a list o) lists o) s$mbols and a )unction )rom lists o) s$mbols to s$mbolsE it produces a list o) s$mbols, Solution

The second +ersion o) fi+ter1 was the result o) abstracting 8e+ow and 8e+ow-ir, Its de)inition did not di))er )rom the )irst +ersion! but the process o) abstracting )rom 8e+ow-ir clari)ied that fi+ter1 could be applied to all .inds o) lists! not Fust lists o) numbers, To describe all .inds o) lists! we use !listof"R#, Here is a )irst attempt at a contract )or fi+ter1:
66"fi+ter1":"..."!listof"R#"n.m8er""-/""!listof"R#"

The .e$ to using fi+ter1 with di))erent classes o) lists is to use a comparison )unction that can compare the items on the list with the second argument! which is a number, That is! the )irst argument is a )unction in the class
!R"n.m8er""-/""8oo+ean#

which means it consumes an element o) R and a number! and produces a boolean, Put together! we get the )ollowing contract )or fi+ter1:
66"fi+ter1":"!R"n.m8er""-/""8oo+ean#"!listof"R#"n.m8er""-/" !listof"R#"

As in our contract )or +ength! R here stands )or an arbitrar$ collection o) Scheme data, 1e can replace it with an$thing! as long as all three occurrences are replaced b$ the same thing, Hence! b$ using R in the description o) the )irst parameter! the second parameter! and the result! we speci)$ that re+-op consumes elements o) class R! that the second argument is a list o) Rs! and that the result o) fi+ter1 is also a list o) Rs, 1hen we wish to appl$ fi+ter1! we must chec. that the arguments ma.e sense, Suppose we wish to e+aluate
!fi+ter1"?"!+ist"3"$"1%#"2#

Be)ore we do that! we should con)irm that fi+ter1 can indeed consume ? and !+ist"3 $"1%#! gi+en its contract, A ?uic. chec. shows that ? ma.es sense because it belongs to the class
!n.m8er"n.m8er""-/""8oo+ean#

and !+ist"3"$"1%# ma.es sense because it belongs to


!listof"n.m8er#

The two classes are identical to the )irst two argument parts o) fi+ter1Cs contract i) R is replaced b$ n.m8er, More generall$! to ensure that arguments ma.e sense! we must )ind replacements o) the +ariables in contracts so that the )unctions contract and the classes o) the arguments match, For a second e8ample! consider
!fi+ter1"?ir"LNIQ"1%#

Here! we must replace R with IQ! because ?ir has the contract
!IQ"n.m8er""-/""8oo+ean#

and LNIQ belongs to !listof"IQ#, Again! the application is legitimate because all the arguments belong to the re?uired collections o) data, "et us loo. at one more e8ample: the use o) fi+ter1 to e8tract all to$s with the same name )rom a list o) in+entor$ records:
66"find":"!listof"IQ#"s2m8o+""-/""!listof"IQ# !define"!find"a+oir"t# ""!fi+ter1"e)-irA"a+oir"t##

66"e)-irA":"IQ"s2m8o+""-/""8oo+ean !define"!e)-irA"ir"p# ""!s2m8o+&A"!ir-name"ir#"p##

It is straight)orward to chec. with e8amples that the )unction wor.s properl$, @ur tas. here is to understand how this agrees with fi+ter1Cs contract, The ob+ious problem is that the DDthresholdCC argument is a s$mbol! not a number, The use o) fi+ter1 is there)ore in con)lict with its current contract, To o+ercome this de)icienc$! we must introduce another +ariable! sa$! ;= )or thresholds! that stands )or some collection o) data:
66"fi+ter1":"!R";=""-/""8oo+ean#"!listof"R#";=""-/""!listof"R#"

-ow we can replace R with the name o) one data collection and ;= with that o) a second one or possibl$ the same, In particular! the application
!fi+ter1"e)-irA"LNIQ"'do++#

wor.s because a replacement o) R b$ IQ and ;= b$ s$mbol in fi+ter1Cs contract shows that the arguments are legitimate, E ercise 2.<2<!< Ase fi+ter1 to de+elop a )unction that consumes a list o) s$mbols and e8tracts all those that are not e?ual to 'car, =i+e fi+ter1Cs corresponding contract, Solution E ercise 2.<2<#< Formulate genera! contracts )or the )ollowing )unctions: (, sort! which consumes a list o) items and a )unction that consumes two items /)rom the list0 and produces a booleanE it produces a list o) items, &, map! which consumes a )unction )rom list items to Rs and a listE it produces a list o) Rs, 5, proSect! which consumes a list o) lists and a )unction )rom lists to RsE it produces a list o) Rs, Compare with e8ercise &',&,&, Solution

Contracts and T%pes: In summar$! the contracts )or )unctions are made up o) t$pes, A T3P# is either (, a basic t$pe! such as number! s$mbol! boolean! or empt2E

&, a de)ined t$pe! such as in0entor2-record! +ist-of-n.m8ers! or fami+2treeE 5, a )unction t$pe! such as !n.m8er""-/""n.m8er# or !8oo+ean""-/""s2m8o+#E 6, a parametric t$pe! which is either a de)ined t$pe or a )unction t$pe with t$pe +ariables, 1hen we wish to use a )unction with a parametric t$pe! we must )irst )ind a replacement )or all the +ariables in the )unctionCs contract so that we .now the arguments belong to proper classes, I) this cannot be done! we must either re+ise the contract or ?uestion our decision to reuse this )unction,

Section 21 Designing +bstractions from E amples


1hen we )irst learn to add! we use concrete e8amples, "ater on! we stud$ how to add two arbitrar$ numbersE that is! we )orm an abstraction o) the addition operation, Much later still! we learn to )ormulate abstractions directl$ as e8pressions: e8pressions that compute the wage o) some emplo$ee! e8pressions that con+ert temperatures! or e8pressions that determine the area o) a geometric shape, In short! we initiall$ go )rom concrete e8amples to abstraction! but e+entuall$ we learn to )orm abstractions directl$ without thin.ing /much0 about concrete instances, In this section! we discuss a design recipe )or creating abstractions )rom concrete e8amples, "ater! in sections &(,7 and && we stud$ additional approaches to )unction abstraction,

"$#$

&stracting from E,amples

Forming abstractions )rom e8amples is eas$, As we ha+e seen in section (>! we start )rom two concrete )unction de)initions! compare them! mar. the di))erences! and abstract, "et us )ormulate these steps as a recipe: The comparison'

1hen we )ind two )unction de)initions that are almost the same e8cept at a )ew places and )or their names! we compare them and mar. the di))erences with bo8es, I) the bo8es contain onl$ +alues! we can abstract, @arning' +bstracting o1er Non21alues: The recipe re?uires a substantial modi)ication )or non2+alues, Here is a pair o) similar )unction de)initions:
66"con0ert7>":"+on""-/" +on !define"!con0ert7>"a+on# ""!cond """"9!empt2A"a+on#"empt2: """"9else """"""!cons"!7-/>"!first a+on## !con0ert7>"!rest a+on###:## 66"names":"+oIQ""-/""+os !define"!names"a+oIQ# ""!cond """"9!empt2A"a+oIQ#"empt2: """"9else """"""!cons"!IQ-name !first"a+oIQ## !names"!rest a+oIQ###:##

The two )unctions appl$ a )unction to each item in a list, The$ di))er in onl$ one aspect: what the$ appl$ to each item on the list, The two bo8es emphasi*e the di))erence, #ach contains a )unctional +alue! so we can abstract, The abstraction' -e8t we replace the contents o) corresponding pairs o) bo8es with new names and add these names to the parameter list, For e8ample! i) there are three pairs o) bo8es! we need three new names, The two de)initions must now be the same! e8cept )or the )unction name, To obtain the abstraction! we s$stematicall$ replace the )unction names with one new name, For our running e8ample! we obtain the )ollowing pair o) )unctions:
!define"!con0ert7>"f"a+on# ""!cond """"9!empt2A"a+on#"empt2: """"9else """"""!cons"!f"!first a+on## !con0ert7>"f"!rest a+on###:## !define"!names"f"a+oIQ# ""!cond """"9!empt2A"a+oIQ# empt2: """"9else """"""!cons"!f"!first a+oIQ## !names"f"!rest a+oIQ###:## with f and added f as a parameter, -ow we

1e ha+e replaced the bo8ed names replace con0ert7> and names with a new name and thus obtain the abstract )unction:
!define"!map"f"+on# ""!cond """"9!empt2A"+on#"empt2: """"9else"!cons"!f"!first"+on## """"!map"f"!rest"+on###:##

1e use the name map )or the result in our running e8ample! because it is the traditional name in programming languages )or this speci)ic )unction, The test'

-ow we must +alidate that the new )unction is a correct abstraction o) the original concrete )unctions, The +er$ de)inition o) abstraction suggests that we de)ine the original )unctions in terms o) the abstract one and test the new +ersions with the original e8amples, In most cases! de)ining the original )unction based on the abstract one is straight)orward, Suppose the abstract )unction is called f-a8stract! and )urthermore suppose that one original )unction is called f-origina+ and consumes one argument, I) f-origina+ di))ers )rom the other concrete )unction in the use o) one +alue! sa$! 8o*ed-0a+.e! then we de)ine the )ollowing )unction:
!define"!f-from-a8stract"*# ""!f-a8stract"8o*ed-0a+.e"*##

For e+er$ proper +alue W! !f-from-a8stract"W# now produces the same answer as !f-origina+"W#, "et us return to our e8ample, Here are the two new de)initions:
66"con0ert7>-from-map":"+on "-/""+on !define"!con0ert7>-from-map a+on# ""!map"C-/F"a+on## 66"names-from-map":"+oIQ "-/""+os !define"!names-from-map a+oIQ# ""!map"IQ-name"a+oIQ##

To ensure that these two de)initions are e?ui+alent to the old one and! indirectl$! that map is a correct abstraction! we now appl$ these two )unctions to the e8amples that we speci)ied )or the de+elopment o) con0ert7> and names, The contract' To ma.e the abstraction trul$ use)ul! we must also )ormulate a contract, I) the bo8ed +alues in stage & o) our recipe are )unctions! a contract re?uires the use o) arrow t$pes, Furthermore! to obtain a widel$ usable contract! we ma$ ha+e to de+elop or use parametric data de)initions and )ormulate a parametric t$pe, A case in point is the contract )or map, @n one hand! i) we +iew map as an abstraction o) con0ert7>! the contract could be construed as
66"map":"!n.m8er""-/""n.m8er#"!listof"n.m8er#""-/""!listof n.m8er#

@n the other hand! i) we +iew map as an abstraction o) names! the contract could be construed as
66"map":"!IQ""-/""s2m8o+#"!listof"IQ#""-/""!listof"s2m8o+#

But the )irst contract would be useless in the second case! and +ice +ersa, To accommodate both cases! we must understand what map does and then )i8 a contract,

B$ loo.ing at the de)inition! we can see that map applies its )irst argument! a )unction! to e+er$ item on the second argument! a list, This implies that the )unction must consume the class o) data that the list contains, That is! we .now f has the contract
66"f":"R""-/""AAA

i) +on contains Rs, Furthermore! map creates a list )rom the results o) appl$ing f to each item, Thus! i) f produces Is! then map produces a list o) Is, Translated into our language o) contracts we get this:
66"map":"!R""-/""I#"!listof"R#""-/""!listof"I#

This contract sa$s that map can produce a list o) Is )rom a list o) Rs and a )unction )rom R to I 22 no matter )or what collection o) R and I stand, @nce we ha+e abstracted two /or more0 )unctions! we should chec. whether there are other uses )or the abstract )unction, In man$ cases! an abstract )unction is use)ul in a much broader arra$ o) conte8ts than we )irst anticipate and ma.es )unctions easier to read! understand! and maintain, For e8ample! we can now use map e+er$ time we need a )unction to produce a new list b$ processing all items on an e8isting list, I) that )unction is a primiti+e operation or a )unction we ha+e de)ined! we donCt e+en write a )unction, Instead! we simpl$ write an e8pression that per)orms the tas., An)ortunatel$! there is no recipe that guides this disco+er$ process, 1e must practice it and de+elop an e$e )or matching abstract )unctions to situations, E ercise 21<1<1< De)ine ta8.+ate! which is the abstraction o) the )ollowing two )unctions:
66"ta8.+ate-sin":"n.m8er "-/""+on 66"to"ta8.+ate"sin"8etween"n 66"and"%"!inc+.si0e#"in"a +ist !define"!ta8.+ate-sin"n# ""!cond """"9!&"n"%#"!+ist"!sin"%##: """"9else """"""!cons"!sin"n# !ta8.+ate-sin"!s.81 n###:## 66"ta8.+ate-s)rt":"n.m8er "-/""+on 66"to"ta8.+ate"s)rt"8etween"n 66"and"%"!inc+.si0e#"in"a +ist !define"!ta8.+ate-s)rt"n# ""!cond """"9!&"n"%#"!+ist"!s)rt"%##: """"9else """"""!cons"!s)rt"n# !ta8.+ate-s)rt"!s.81 n###:## ta8.+ate, Also use ta8.+ate to de)ine

Be sure to de)ine the two )unctions in terms o) a tabulation )unction )or s)r and tan, 1hat would be a good! general contractH Solution

E ercise 21<1<2< De)ine fo+d! which is the abstraction o) the )ollowing two )unctions:

66"s.m":"!listof"n.m8er# "-/""n.m8er 66"to"comp.te"the"s.m"of" 66"the"n.m8ers"on"a+on !define"!s.m"a+on# ""!cond """"9!empt2A"a+on#"%: """"9else"!+"!first"a+on# """""!s.m"!rest a+on###:## DonCt )orget to test fo+d,

66"prod.ct":"!listof"n.m8er# "-/""n.m8er 66"to"comp.te"the"prod.ct"of" 66"the"n.m8ers"on"a+on !define"!prod.ct"a+on# ""!cond """"9!empt2A"a+on#"1: """"9else"!*"!first"a+on# """""!prod.ct"!rest a+on###:##

A)ter fo+d is de)ined and tested! use it to de)ine append! which Fu8taposes the items o) two lists or! e?ui+alentl$! replaces empt2 at the end o) the )irst list with the second list:
!e).a+A"!append"!+ist"1"2"3#"!+ist"4"5" "7"$## """"""""!+ist"1"2"3"4"5" "7"$##

Finall$! de)ine map using fo+d, Compare the )our e8amples to )ormulate a contract, Solution

E ercise 21<1<!< De)ine nat.ra+-f! which is the abstraction o) the )ollowing two )unctions:
66"cop2":"N"R""-/""!listof"R# 66"n-adder":"N"n.m8er""-/" 66"to"create"a"+ist"that n.m8er contains 66"to"add"n"to"*".sing 66"o8S"n"times 66"!+"1"...#"on+2 !define"!cop2"n"o8S# !define"!n-adder"n"*# ""!cond ""!cond """"9!@eroA"n#"empt2: """"9!@eroA"n#"*: """"9else"!cons"o8S" """"9else"!+"1 """"""""""""""""!cop2"!s.81"n#" """""""""""""!n-adder"!s.81 o8S##:## n#"*##:## DonCt )orget to test nat.ra+-f, Also use nat.ra+-f to de)ine n-m.+tip+ier! which consumes n and * and produces n times * with additions onl$, Ase the e8amples to

)ormulate a contract, >int' The two )unction di))er more than! sa$! the )unctions s.m and prod.ct in e8ercise &(,(,&, In particular! the base case in one instance is a argument o) the )unction! where in the other it is Fust a constant +alue, Solution Formulating 4eneral Contracts: To increase the use)ulness o) an abstract )unction! we must )ormulate a contract that describes its applicabilit$ in the most general terms possible, In principle! abstracting contracts )ollows the same recipe that we use )or abstracting )unctions, 1e compare and contrast the old contractsE then we replace the di))erences with +ariables, But the process is complicated and re?uires a lot o) practice, "et us start with our running e8ample: con0ert7> and names:

!listof"n.m8er# "-/" !listof"n.m8er# !listof"IQ# "-/" !listof"s2m8o+#

Comparing the two contracts shows that the$ di))er in two places, To the le)t o) "-/"! we ha+e n.m8er and IQE to the right! it is n.m8er +ersus s2m8o+, Consider the second stage o) our abstraction recipe, The most natural contracts are as )ollows:
!n.m8er""-/""n.m8er# !listof"n.m8er# "-/" !listof"n.m8er# !IQ""-/""s2m8o+# !listof"IQ# "-/" !listof"s2m8o+#

These new contracts suggest a pattern, Speci)icall$! the$ suggest that the )irst argument! a )unction! consumes the items on the second argument! a list! and )urthermore! that the results produced b$ these applications ma.e up the output, The second contract is particularl$ telling, I) we replace IQ and s2m8o+ with +ariables! we get an abstract contract! and it is indeed a contract )or map:
map":"!R""-/""I#"!listof"R#""-/""!listof"I#

It is straight)orward to chec. that b$ replacing R with n.m8er and I with n.m8er! we get the )irst o) the intermediate contracts, Here is a second pair o) e8amples:
n.m8er !listof"n.m8er# "-/" !listof"n.m8er# n.m8er !listof"IQ# "-/" !listof"IQ#

The$ are the contracts )or 8e+ow and 8e+ow-ir, The contracts di))er in two places: the lists consumed and produced, As usual! the )unctions o) the second stage consume an additional argument:
!n.m8er"n.m8er""-/""8oo+ean# n.m8er !listof"n.m8er# "-/" !listof"n.m8er# !n.m8er"IQ""-/""8oo+ean# n.m8er !listof"IQ# "-/" !listof"IQ#

The new argument is a )unction! which in the )irst case consumes a number! and in the second case an IQ, A comparison o) the two contracts suggests that n.m8er and IQ occup$ related positions and that we should replace them with a +ariable, Doing so ma.es the two contracts e?ual:
!n.m8er"R""-/""8oo+ean# n.m8er !listof"R# "-/" !listof"R# !n.m8er"R""-/""8oo+ean# n.m8er !listof"R# "-/" !listof"R#

A closer inspection o) fi+ter1Cs de)inition shows that we can also replace n.m8er with I because the second argument is alwa$s Fust the )irst argument o) fi+ter1Cs )irst argument, Here is the new contract:

The Hence we ha+e )ound the most general contract possible,

fi+ter1":"!I"R""-/""8oo+ean#"I"!listof"R#""-/""!listof"R# result o) the )irst argument must be 8oo+ean! because it is used as a condition,

The two e8amples illustrate how to )ind general contracts, 1e compare the contracts o) the e8amples )rom which we create abstractions, B$ replacing speci)ic! distinct classes in corresponding positions! one at a time! we ma.e the contract graduall$ more general, To ensure that our generali*ed contract wor.s! we chec. that the contract describes the speci)ic instances o) the abstracted )unction properl$,

"$#" +inger E,ercises !ith

&stract List +unctions

Scheme pro+ides a number o) abstract )unctions )or processing lists, Figure 7; collects the speci)ication o) the most important ones, Asing these )unctions greatl$ simpli)ies man$ programming tas.s and helps readers understand programs ?uic.l$, The )ollowing e8ercises pro+ide an opportunit$ to get ac?uainted with these )unctions,

66"8.i+d-+ist":"N"!N""-/""R#""-/""!listof"R# 66"to"constr.ct"!+ist"!f"%#"..."!f"!-"n"1### !define"!8.i+d-+ist"n"f#"...# 66"fi+ter":"!R""-/""8oo+ean#"!listof"R#""-/""!listof"R# 66"to"constr.ct"a"+ist"from"a++"those"items"on"a+o*"for"which"p ho+ds" !define"!fi+ter"p"a+o*#"...# 66").ic-sort":"!listof"R#"!R"R""-/""8oo+ean#""-/""!listof"R# 66"to"constr.ct"a"+ist"from"a++"items"on"a+o*"in"an"order according"to"cmp !define"!).ic-sort"a+o*"cmp#"...# 66"map":"!R""-/""I#"!listof"R#""-/""!listof"I# 66"to"constr.ct"a"+ist"82"app+2ing"f"to"each"item"on"a+o* 66"that"is<"!map"f"!+ist"*-1"..."*-n##"&"!+ist"!f"*-1#"..."!f"*n## !define"!map"f"a+o*#"...# 66"andmap":"!R""-/""8oo+ean#"!listof"R#""-/""8oo+ean 66"to"determine"whether"p"ho+ds"for"e0er2"item"on"a+o* 66"that"is<"!andmap"p"!+ist"*-1"..."*-n##"&"!and"!p"*-1#"!and"... !p"*-n### !define"!andmap"p"a+o*#"...# 66"ormap":"!R""-/""8oo+ean#"!listof"R#""-/""8oo+ean 66"to"determine"whether"p"ho+ds"for"at"+east"one"item"on"a+o* 66"that"is<"!ormap"p"!+ist"*-1"..."*-n##"&"!or"!p"*-1#"!or"..."!p *-n### !define"!ormap"p"a+o*#"...# 66"fo+dr":"!R"I""-/""I#"I"!listof"R#""-/""I 66"!fo+dr"f"8ase"!+ist"*-1"..."*-n##"&"!f"*-1"..."!f"*-n"8ase##" !define"!fo+dr"f"8ase"a+o*#"...# 66"fo+d+":"!R"I""-/""I#"I"!listof"R#""-/""I 66"!fo+d+"f"8ase"!+ist"*-1"..."*-n##"&"!f"*-n"..."!f"*-1"8ase##" !define"!fo+d+"f"8ase"a+o*#"...# 66"assf":"!R""-/""8oo+ean#"!listof"!+ist"R"I##""-/""!+ist"R"I#"or fa+se 66"to"find"the"first"item"on"a+op"for"whose"first"item"pA"ho+ds

/define /ass) pH alop0 ,,,0 Figure $(' SchemeCs built2in abstract )unctions )or list2processing E ercise 21<2<1< Ase 8.i+d-+ist (, to create the lists !+ist"%"..."3# and !+ist"1"..."4#E &, to create the list !+ist".1".%1".%%1".%%%1#E 5, to de)ine e0ens! which consumes a natural number n and creates the list o) the )irst n e+en numbersE

6, to de)ine ta8.+ate )rom e8ercise &(,(,(E and 7, to de)ine diagona+! which consumes a natural number n and creates a list o) lists o) % and 1, #8ample:
. !e).a+A"!diagona+"3# 7. """"""""!+ist" $. ""!+ist"1"%"%# ,. ""!+ist"%"1"%# 1%. ""!+ist"%"%"1###

Ase local i) )unction de)initions re?uire au8iliar$ )unctions, E ercise 21<2<2< Ase map to de)ine the )ollowing )unctions:

Solution

(, con0ert-e.ro! which con+erts a list o) A,S, dollar amounts into a list o) euro amounts based on an e8change rate o) (,&& euro )or each dollarE &, con0ert>7! which con+erts a list o) Fahrenheit measurements to a list o) Celsius measurementsE 5, mo0e-a++! which consumes a list o) posn structures and translates each b$ adding 3 to the +2component, Solution E ercise 21<2<!< Here is the +ersion o) fi+ter that DrScheme pro+ides:
66"fi+ter":"!R""-/""8oo+ean#"!listof"R#""-/""!listof"R# 66"to"constr.ct"a"+ist"of"R"from"a++"those"items"on"a+on 66"for"which"predicateA"ho+ds" !define"!fi+ter"predicateA"a+on# ""!cond """"9!empt2A"a+on#"empt2: """"9else"!cond """"9!predicateA"!first"a+on##" """""!cons"!first"a+on#"!fi+ter"predicateA"!rest"a+on###: """"9else"!fi+ter"predicateA"!rest"a+on##:#:##

Ase fi+ter to de)ine the )ollowing )unctions: (, e+iminate-e*p! which consumes a number! .a! and a list o) to$ structures /containing name and price0 and produces a list o) all those descriptions whose price is below .aE

&, reca++! which consumes the name o) a to$! called t2! and a list o) names! called +on! and produces a list o) names that contains all components o) +on with the e8ception o) t2E 5, se+ection! which consumes two lists o) names and selects all those )rom the second one that are also on the )irst, Solution

"$#(

&straction and a Single Point of Control

Just li.e editing papers! abstracting programs has man$ ad+antages, Creating an abstraction o)ten simpli)ies other de)initions, The process o) abstracting ma$ unco+er problems with e8isting )unctions, But! the single most important ad+antage o) abstraction is that it creates a SI-="# P@I-T @F C@-TR@" )or the )unctionalit$ in a program, In other words! it /as much as possible0 puts in one place the de)initions related to some speci)ic tas., Putting the de)initions )or a speci)ic tas. in one place ma.es it easier to maintain a program, Roughl$ put! program maintenance means )i8ing the program so that it )unctions properl$ in pre+iousl$ untested casesE e8tending the program so that it can deal with new or un)oreseen situationsE or changing the representation o) some in)ormation as data /)or e8ample! calendar dates0, 1ith e+er$thing in one place! )i8ing an error means )i8ing it in one )unction! not )our or )i+e similar +ersions, #8tending a )unctionCs capabilities means )i8ing one )unction! not its related copies, And changing a data representation means changing a general data2tra+ersal )unction! not all those that came )rom the same template, Translated into a guideline! this becomes:

=uideline on Creating Abstractions


Form an abstraction instead o) cop$ing and modi)$ing a piece o) a program, #8perience teaches us that maintaining so)tware is e8pensi+e, Programmers can reduce the maintenance cost b$ organi*ing programs correctl$, The )irst principle o) )unction organi*ation is to match the )unctionCs structure to the structure o) its input data, I) e+er$ programmer )ollows this rule! it is eas$ to modi)$ and e8tend )unctions when the set o) possible input data changes, The second principle is to introduce proper abstractions, #+er$ abstracted )unction creates a single point o) control )or at least two di))erent )unctions! o)ten )or se+eral more, A)ter we ha+e abstracted! we o)ten )ind more uses o) the new )unction, @ur design recipe )or abstracting )unctions is the most basic tool to create abstractions, To use it re?uires practice, As we practice! we e8pand our capabilities )or building and using abstractions, The best programmers are those who acti+el$ edit their programs to build new abstractions so that the$ collect things related to a tas. at a single point, Here we use )unctional abstraction to stud$ this practice, 1hile not all languages pro+ide the )reedom to abstract )unctions as easil$ as Scheme! modern languages o)ten support

similar concepts and practicing in power)ul languages such as Scheme is the best possible preparation,6;

"$#) E,tended E,ercise. /oving Pictures2

gain

In sections 9,9! ;,6! and (',5! we studied the problem o) mo+ing pictures across a can+as, The problem had two parts: mo+ing indi+idual shapes and mo+ing a picture! which is a list o) shapes, For the )irst part! we need )unctions to draw! clear! and translate a shape, For the second part! we need )unctions that draw all shapes on a list! that clear all shapes on a list! and that translate all shapes on a list, #+en the most cursor$ loo. at the )unctions shows man$ repetitions, The )ollowing e8ercises aim to eliminate these repetitions +ia manual abstraction and SchemeCs built2in operations, E ercise 21<#<1< Abstract the )unctions draw-a-circ+e and c+ear-a-circ+e into a single )unction process-circ+e, De)ine trans+ate-circ+e using process-circ+e, >int' I) a primiti+e )unction doesnCt ?uite )it an abstraction! we ha+e to de)ine au8iliar$ )unctions, For now! use define to do so, Interme**o 6 introduces a hand$ and important short2hand )or that purpose, Solution E ercise 21<#<2< Abstract the )unctions draw-a-rectang+e and c+ear-a-rectang+e into a single )unction process-rectang+e, De)ine trans+ate-rectang+e using process-rectang+e, Solution

E ercise 21<#<!< Abstract the )unctions draw-shape and c+ear-shape into a single )unction process-shape, Compare the )unction with the template f.n-for-shape, De)ine trans+ate-shape using process-shape, Solution

E ercise 21<#<#< Ase SchemeCs map and andmap to de)ine draw-+osh! c+ear-+osh! and trans+ate-+osh, Solution

Figure $)' The Apollo (( lunar lander


-ASA: -ational Space Science Data Center

E ercise 21<#<$< Modi)$ the )unctions o) e8ercises &(,6,5 and &(,6,6 so that pictures mo+e up and down on a can+as, Modi)$ all de)initions so that a shape can also be a lineE a line has a start position! an end position! and a color, De)ine LPJ'Q! a list that s.etches a lunar lander picture /see )igure 7<0, The list should consist o) rectangles! circles! and lines, De+elop the program +.nar-+ander, It places "A-AR at the top o) a can+as and then uses the modi)ied )unctions to mo+e the lander up or down, Ase the teachpac. arrow.ss to gi+e users control o+er how )ast and when the lunar lander should mo+e:
!start"5%%"1%%# !draw"LPJ'Q#

!contro+-.p-down"LPJ'Q"1%"mo0e-+ander"draw-+osh#

I) time permits! modi)$ the )unction so that a pla$er can mo+e the lander up! down! le)t or right, Ase contro++er )rom arrow.ss to control the mo+ements in all directions, Solution

"$#* %ote. Designing

&stractions from Templates

At the +er$ beginning o) this part o) the boo.! we discussed how we design sets o) )unctions )rom the same template, More speci)icall$! when we design a set o) )unctions that all consume the same .ind o) data! we reuse the same template o+er and o+er again, It is there)ore not surprising that the )unction de)initions loo. similar and that we will abstract them later, Indeed! we could abstract )rom the templates directl$, 1hile this topic is highl$ ad+anced and still a subFect o) research in the area o) programming languages! we can discuss it with a short e8ample, Consider the template )or lists:
!define"!f.n-for-+"+# ""!cond """"9!empt2A"+#"...: """"9else"..."!first"+#"..."!f.n-for-+"!rest"+##"...:##

It contains two gaps! one in each clause, 1hen we de)ine a list2processing )unction! we )ill these gaps, In the )irst clause! we t$picall$ place a plain +alue, For the second one! we combine !first"+# and !f"!rest"+## where f is the recursi+e )unction, 1e can abstract o+er this programming tas. with the )ollowing )unction:
66"red.ce":"R"!R""I""-/""I#"!listof"I#""-/""I !define"!red.ce"8ase"com8ine"+# ""!cond """"9!empt2A"+#"8ase: """"9else"!com8ine"!first"+# """"!red.ce"8ase"com8ine"!rest"+###:##

It consumes two e8tra arguments: 8ase! which is the +alue )or the base case! and com8ine! which is a )unction that per)orms the +alue combination )or the second clause, Asing red.ce we can de)ine man$ plain list2processing )unctions as well as almost all the )unctions o) )igure 7;, Here are two o) them:
66"s.m":"!listof"n.m8er# "-/""n.m8er !define"!s.m"+#"!red.ce"%"+ +## s.m! the base case alwa$s produces %E 66"prod.ct":"!listof"n.m8er# "-/""n.m8er !define"!prod.ct"+#"!red.ce"1 *"+##

For adding the )irst item and the result o) the natural recursion combines the +alues o) the second clause, Analogous reasoning e8plains prod.ct,

To de)ine sort! we need to de)ine an au8iliar$ )unction )irst:


66"sort":"!listof"n.m8er#""-/""!listof"n.m8er# !define"!sort"+# ""!local"!!define"!insert"an"a+on# """"!cond """"""9!empt2A"a+on#"!+ist"an#: """"""9else"!cond """"""9!/"an"!first"a+on##"!cons"an"a+on#: """"""9else"!cons"!first"a+on#"!insert"an"!rest a+on###:#:### """"!red.ce"empt2"insert"+###

@ther list2processing )unctions can be de)ined in a similar manner,

A currentl$ popular method o) abstraction is I-H#RITA-C# in class2based obFect2 oriented programming languages, Inheritance is ?uite similar to )unctional abstraction! though it emphasi*es those aspects that change o+er those that sta$ the same,
6;

Section 22 Designing +bstractions 3ith First2Class Functions


1e ha+e seen that )unctions can consume )unctions and how important that is )or creating single points o) control in a )unction, But )unctions not onl$ can consume )unctions! the$ can also produce them, More precisel$! e8pressions in the new Scheme can e+aluate to )unctions, Because the bod$ o) a )unction de)inition is also an e8pression! a )unction can produce a )unction, In this section! we )irst discuss this surprising idea and then show how it is use)ul )or abstracting )unctions and in other conte8ts,

""#$ +unctions that Produce +unctions


1hile the idea o) producing a )unction ma$ seem strange at )irst! it is e8tremel$ use)ul, Be)ore we can discuss the use)ulness o) the idea! though! we must e8plore how a )unction can produce a )unction, Here are three e8amples:
!define"!f"*#"first# !define"!g"*#"f#

!define"!h"*#" ""!cond """"!!empt2A"*#"f# """"!!consA"*#"g###

The bod$ o) f is first! a primiti+e operation! so appl$ing f to an$ argument alwa$s e+aluates to first, Similarl$! the bod$ o) g is f! so appl$ing g to an$ argument alwa$s e+aluates to f, Finall$! depending on what .ind o) list we suppl$ as an argument to h! it produces f or g, -one o) these e8amples is use)ul but each illustrates the basic idea, In the )irst two cases! the bod$ o) the )unction de)inition is a )unction, In the last case! it e+aluates to a )unction, The e8amples are useless because the results do not contain or re)er to the argument, For a )unction f to produce a )unction that contains one o) fCs arguments! f must de)ine a )unction and return it as the result, That is! fCs bod$ must be a local2 e8pression, Recall that local2e8pressions group de)initions and as. DrScheme to e+aluate a single e8pression in the conte8t o) these de)initions, The$ can occur where+er an e8pression can occur! which means the )ollowing de)inition is legal:
!define"!add"*# ""!local"!!define"!*-adder"2#"!+"*"2### """"*-adder##

The )unction add consumes a numberE a)ter all! * is added to 2, It then de)ines the )unction *-adder with a local2e8pression, The bod$ o) the local2e8pression is *-adder! which means the result o) add is *-adder, To understand add better! let us loo. at how an application o) add to some number e+aluates:
""!define"f"!add"5## &"!define"f"!local"!!define"!*-adder"2#"!+"5"2### """"""*-adder## &"!define"f"!local"!!define"!*-adder5"2#"!+"5"2### """"""*-adder5## &"!define"!*-adder5"2#"!+"5"2## ""!define"f"*-adder5#

The last step adds the )unction *-adder5 to the collection o) our de)initionsE the e+aluation continues with the bod$ o) the local2e8pression! *-adder5! which is the name o) a )unction and thus a +alue, -ow f is de)ined and we can use it:
""!f"1%# &"!*-adder5"1%# &"!+"5"1%# &"15

That is! f stands )or *-adder5! a )unction! which adds 5 to its argument,

Asing this e8ample! we can write addCs contract and a purpose statement:
66"add":"n.m8er""-/""!n.m8er""-/""n.m8er# 66"to"create"a"f.nction"that"adds"*"to"its"inp.t !define"!add"*# ""!local"!!define"!*-adder"2#"!+"*"2### """"*-adder##

The most interesting propert$ o) add is that its result DDremembersCC the +alue o) *, For e8ample! e+er$ time we use f! it uses 5! the +alue o) *! when add was used to de)ine f, This )orm o) DDmemor$CC is the .e$ to our simple recipe )or de)ining abstract )unctions! which we discuss in the ne8t section,

""#" Designing

&stractions !ith +unctions7as7'alues

The combination o) local2e8pressions and )unctions2as2+alues simpli)ies our recipe )or creating abstract )unctions, Consider our +er$ )irst e8ample in )igure 75 again, I) we replace the contents o) the bo8es with re+-op! we get a )unction that has a )ree +ariable, To a+oid this! we can either add re+-op to the parameters or we can wrap the de)inition in a local and pre)i8 it with a )unction that consumes re+-op, Figure 7> shows what happnes when we use this idea with fi+ter, I) we also ma.e the locall$ de)ined )unction the result o) the )unction! we ha+e de)ined an abstraction o) the two original )unctions,
!define"!fi+ter2"re+-op# ""!local"!!define"!a8s-f.n"a+on"t# """"!cond """"""9!empt2A"a+on#"empt2: """"""9else !cond ""9!re+-op"!first"a+on#"t# """!cons"!first"a+on# """""!a8s-f.n"!rest"a+on#"t##: ""9else """""!a8s-f.n"!rest"a+on#"t#:#:###

abs2)un00

Figure $-' Abstracting with local Put di))erentl$! we )ollow the e8ample o) add in the preceding section, "i.e add! fi+ter2 consumes an argument! de)ines a )unction! and returns this )unction as a result, The result remembers the re+-op argument )or good as the )ollowing e+aluation shows:
""!fi+ter2"?# &"!local"!!define"!a8s-f.n"a+on"t# """"!cond """"""9!empt2A"a+on#"empt2: """"""9else !cond ""9!?"!first"a+on#"t# """!cons"!first"a+on# """""!a8s-f.n"!rest"a+on#"t##: ""9else """""!a8s-f.n"!rest"a+on#"t#:#:### """"a8s-f.n#

&"!define"!8e+ow3"a+on"t# """"!cond """"""9!empt2A"a+on#"empt2: """"""9else !cond ""9!?"!first"a+on#"t# """!cons"!first"a+on# """""!8e+ow3"!rest"a+on#"t##: ""9else """"!8e+ow3"!rest"a+on#"t#:#:## """8e+ow3

Remember that as we li)t a local de)inition to the top2le+el de)initions! we also rename the )unction in case the same local is e+aluated again, Here we choose the name 8e+ow3 to indicate what the )unction does, And indeed! a comparison between 8e+ow and 8e+ow3 re+eals that the onl$ di))erence is the name o) the )unction, From the calculation! it )ollows that we can gi+e the result o) !fi+ter2"?# a name and use it as i) it were 8e+ow, More succinctl$!
!define"8e+ow2"!fi+ter2"?##

is e?ui+alent to
!define"!8e+ow3"a+on"t# """"!cond """"""9!empt2A"a+on#"empt2: """"""9else !cond ""9!?"!first"a+on#"t# """!cons"!first"a+on# """""!8e+ow3"!rest"a+on#"t##: ""9else """"!8e+ow3"!rest"a+on#"t#:#:## !define"8e+ow2"8e+ow3#

which means 8e+ow2 is Fust another name )or 8e+ow3 and which directl$ pro+es that our abstract )unction correctl$ implements 8e+ow, The e8ample suggests a +ariant o) the abstraction recipe )rom section &(: The comparison' The new recipe still re?uires us to compare and to mar. the di))erences, The abstraction' The new step concerns the wa$ we de)ine the abstract )unction, 1e place one o) the )unctions into a local2e8pression and use the name o) the )unction as the bod$ o) the local:
!local"!!define"!concrete-f.n"*"2"@# ""..."op1"..."op2"...## ""concrete-f.n#

From that! we can create the abstract )unction b$ listing the names in the bo8es as parameters:

!define"!a8s-f.n"op1"op2# ""!local"!!define"!concrete-f.n"*"2"@# """"..."op1"..."op2"...## """"concrete-f.n##

I) op1 or op2 is a special s$mbol! sa$ ?! we name it something that is more meaning)ul in the new conte8t, The test' To test the abstract )unction! we de)ine the concrete )unctions again! as be)ore, Consider the e8ample o) 8e+ow and a8o0e, @btaining 8e+ow and a8o0e as instances o) fi+ter2 is now straight)orward:
!define"8e+ow2"!fi+ter2"?## !define"a8o0e2"!fi+ter2"/##

1e simpl$ appl$ fi+ter2 to the contents o) the bo8 in the respecti+e concrete )unction and that application produces the old )unction, The contract' The contract o) an abstract )unction contains two arrows, A)ter all! the )unction produces a )unction! and to describe this relationship the t$pe to the right o) the )irst arrow must contain another arrow, Here is the contract )or fi+ter2:
66"fi+ter2":"!R"I""-/""8oo+ean#""-/""!!listof"R#"I""-/" !listof"R##

It consumes a comparison )unction and produces a concrete )ilter2st$le )unction, The generali*ation o) the contract wor.s as be)ore, =i+en our e8perience with the )irst design recipe! the second one is onl$ a ?uestion o) practice, E ercise 22<2<1< De)ine an abstraction o) the )unctions con0ert7> and names )rom section &(,( using the new recipe )or abstraction, Solution E ercise 22<2<2< De)ine an abstract +ersion o) sort /see e8ercise (>,(,90 using the new recipe )or abstraction, Solution E ercise 22<2<!< De)ine fo+d using the new recipe )or abstraction, Recall that fo+d abstracts the )ollowing pair o) )unctions:

66"s.m":"!listof"n.m8er# "-/""n.m8er 66"to"comp.te"the"s.m"of a+on !define"!s.m"a+on# ""!cond """"9!empt2A"a+on#"%: """"9else"!+"!first"a+on# """""!s.m"!rest a+on###:##

66"prod.ct":"!listof"n.m8er# "-/""n.m8er 66"to"comp.te"the"prod.ct"of a+on !define"!prod.ct"a+on# ""!cond """"9!empt2A"a+on#"1: """"9else"!*"!first"a+on# """""!prod.ct"!rest a+on###:##

Solution

""#(

+irst Look at 5raphical <ser 3nterfaces

Functions as )irst2class +alues pla$ a central role in the design o) graphical user inter)aces, The term DDinter)aceCC re)ers to the boundar$ between the program and a user, As long as we are the onl$ users! we can appl$ )unctions to data in DrSchemeCs Interactions window, I) we want others to use our programs! though! we must pro+ide a wa$ to interact with the program that does not re?uire an$ programming .nowledge, The interaction between a program and a casual user is the AS#R I-T#RFAC#, A =RAPHICA" AS#R I-T#RFAC# /=AI0 is the most con+enient inter)ace )or casual users, A =AI is a window that contains =AI items, Some o) these items permit users to enter te8tE others are included so that users can appl$ a speci)ic )unctionE and $et others e8ist to displa$ a )unctionCs results, #8amples include b ttons! which the user can clic. with the mouse and which trigger a )unction applicationE choice men s! )rom which the user can choose one o) a collection o) +aluesE te+t fie!ds! into which the user can t$pe arbitrar$ te8tE and message fie!ds! into which a program can draw te8t,

Figure &.' A simple =AI )or loo.ing up a phone number Ta.e a loo. at the simple =AI in )igure 9', The le)t2most picture shows its initial state, In that state! the =AI contains a te8t )ield labeled DD-ameCC and a message )ield labeled DD-umberCC plus a DD"oo.ApCC button, In the second picture! the user has entered the name DDSeanCC but hasnCt $et clic.ed the DD"oo.ApCC button,6< Finall$! the right2most picture shows how the =AI displa$s the phone number o) DDSeanCC a)ter the user clic.s the DD"oo.ApCC button, The core o) the program is a )unction that loo.s up a phone number )or a name in a list, 1e wrote se+eral +ersions o) this )unction in part II but alwa$s used it with DrSchemeCs Interactions window, Asing the =AI o) )igure 9'! people who .now nothing about Scheme can now use our )unction! too,

To build a graphical user inter)ace! we build structures6> that correspond to the =AI items and hand them o+er to a =AI manager, The latter constructs the +isible window )rom these items, Some o) the structuresC )ields describe the +isual properties o) the =AICs elements! such as the label o) a button! the initial content o) a message )ield! or the a+ailable choices on a menu, @ther )ields stand )or )unctions, The$ are called CA""2 BAC FA-CTI@-S because the =AI manager calls 22 or applies 22 these )unctions when the user manipulates the corresponding =AI element, Apon application! a call2bac. )unction obtains strings and /natural0 numbers )rom the elements o) the =AI and then applies the )unction proper, This last step computes answers! which the call2bac. )unction can place into =AI elements Fust li.e graphics )unctions draw shapes on a can+as,

Figure &1' The model2+iew arrangement The ideal program consists o) two completel$ separate components: the M@D#"! which is the .ind o) program we are learning to design! and a 4I#1! which is the =AI program that manages the displa$ o) in)ormation and the userCs mouse and .e$board manipulations, The bridge between the two is the C@-TR@" e8pression, Figure 9( graphicall$ illustrates the organi*ation! .nown as the M@D#"24I#12C@-TR@" architecture, The lowest arrow indicates how a program ma.es up a button along with a call2bac. )unction, The le)t2to2right arrow depicts the mouse2clic. e+ent and how it triggers an application o) the call2bac. )unction, It! in turn! uses other =AI )unctions to obtain user input be)ore it applies a core )unction or to displa$ results o) the core )unction, The separation o) the program into two parts means that the de)initions )or the model contain no re)erences to the +iew! and that the de)initions )or the +iew contain no re)erences to the data or the )unctionalit$ o) the model, The organi*ation principle e+ol+ed o+er two decades )rom man$ good and bad e8periences, It has the ad+antage that! with an adaptation o) Fust the bridge e8pression! we can use one and the same program with di))erent =AIs and +ice +ersa, Furthermore! the construction o) +iews re?uires di))erent tools than does the construction o) models, Constructing +iews is a labor2intensi+e e))ort and in+ol+es graphical design! but )ortunatel$! it is o)ten possible to generate large portions automaticall$, The construction o) models! in contrast! will alwa$s demand a serious program design e))ort,

A g i-item is either (, !ma-e-8.tton"string"!R""-/""tr.e## &, !ma-e-te*t"string# 5, !ma-e-choices"!listof"string## or 6, !ma-e-message"string#,


66"create-window":"!listof"!listof"g.i-item##""-/""tr.e" 66"to"add"g.i-items"to"the"window"and"to"show"the"window 66"each"+ist"of"g.i-items"defines"one"row"of"g.i"items"in"the window 66"hide-window":"R""-/""tr.e" 66"to"hide"the"window 66"ma-e-8.tton":"string"!e0entF""-/""tr.e#""-/""g.i-item" 66"to"create"a"8.tton"with"+a8e+"and"ca++-8ac-"f.nction" 66"ma-e-message":"string""-/""g.i-item" 66"to"create"an"item"that"disp+a2s"a"message 66"draw-message":"g.i-item9messageF:"string""-/""tr.e" 66"to"disp+a2"a"message"in"a"message"item" 66"it"erases"the"c.rrent"message" 66"ma-e-te*t":"string""-/""g.i-item" 66"to"create"an"item"!with"+a8e+#"that"a++ows".sers"to"enter"te*t 66"te*t-contents":"g.i-item9te*tF:""-/""string" 66"to"determine"the"contents"of"a"te*t"fie+d" 66"ma-e-choice":"!listof"string#""-/""g.i-item" 66"to"create"a"choice"men."that"permits".sers"to"choose"from"some 66"string"a+ternati0es" 66"choice-inded":"g.i-item9choiceF:""-/""n.m" 66"to"determine"which"choice"is"c.rrent+2"se+ected"in"a"choiceitem"

EE the result is the '2based inde8 in the choice menu Figure &2' The gui.ss operations

Here we stud$ the simpli)ied =AI world o) the teachpac. gui.ss, Figure 9& speci)ies the operations that the teachpac. pro+ides,7' The =AI manager is represented b$ the )unction create-window, Its contract and purpose statement are instructi+e, The$ e8plain that we create a window )rom a list, The )unction arranges these lists in a corresponding number o) rows on the +isible window, #ach row is speci)ied as a list o) g.i-items, The data de)inition )or g.i-items in )igure 9& shows that there are )our .inds: te t fields,

which are created with !ma-e-te*t"a-string# and allow users to enter arbitrar$ te8t into an area in the windowE buttons, which are created with !ma-e-8.tton"a-string"a-f.nction# and allow users to appl$ a )unction with the clic. o) a mouse buttonE choice menus, which are created with !ma-e-choice"a-+ist-of-strings# and allow users to pic. a choice )rom a speci)ied set o) choicesE and message fields, which are created with !ma-e-message"a-string# and enable the model to in)orm users o) results, The )unction that goes with a button is a )unction o) one argument: an e+ent, For most uses! we can ignore the e+entE it is simpl$ a to.en that signals the userCs clic. action, How all this wor.s is best illustrated with e8amples, @ur )irst e8ample is a canonical =AI program:
!create-window"!+ist"!+ist"!ma-e-8.tton"17+ose1"hide-window####

It creates a window with a single button and e?uips it with the simplest o) all call2bac.s: hide-window! the )unction that hides the window, 1hen the user clic.s the button labeled 17+ose1! the window disappears, The second sample =AI copies what the user enters into a te8t )ield to a message )ield, 1e )irst create a te8t )ield and a message )ield:
!define"a-te*t-fie+d ""!ma-e-te*t"15nter";e*t:1## !define"a-message ""!ma-e-message"1[=e++o"Oor+dK"is"a"si++2"program.1##

-ow we can re)er to these )ields in a call2bac. )unction:


66"echo-message":"R""-/""tr.e 66"to"e*tract"the"contents"of"a-te*t-fie+d"and"to"draw"it"into"amessage" !define"!echo-message"e# ""!draw-message"a-message"!te*t-contents"a-te*t-fie+d###

The de)inition o) the call2bac. )unction is based on our /domain0 .nowledge about the g.i-items, Speci)icall$! the )unction echo-message obtains the current contents o) the te8t )ield with te*t-contents as a string! and it draws this string into the message )ield with the draw-message )unction, To put e+er$thing together! we create a window with two rows:
!create-window "!+ist"!+ist"a-te*t-fie+d"a-message# """""""!+ist"!ma-e-8.tton"17op2"Jow1"echo-message####

The )irst row contains the te8t and the message )ieldE the second one contains a button with the label 17op2"Jow1 whose call2bac. )unction is echo-message, The user can now enter te8t into the te8t )ield! clic. the button! and see the te8t appear in the message )ield o) the window, The purpose o) the third and last e8ample is to create a window with a choice menu! a message )ield! and a button, Clic.ing the button puts the current choice into the message )ield, As be)ore! we start b$ de)ining the input and output g.i-items:
!define";=5-7=NI75C ""!+ist"1green1"1red1"12e++ow1## !define"a-choice ""!ma-e-choice";=5-7=NI75C## !define"a-message ""!ma-e-message"!first";=5-7=NI75C###

Because the list o) choices is used more than once in the program! it is speci)ied in a separate +ariable de)inition, As be)ore! the call2bac. )unction )or the button interacts with a-choice and a-message:
66"echo-choice":"R""-/""tr.e 66"to"determine"the"c.rrent"choice"of"a-choice"and 66"to"draw"the"corresponding"string"into"a-message" !define"!echo-choice"e# ""!draw-message"a-message """"""""""""""""!+ist-ref";=5-7=NI75C """"""""""!choice-inde*"a-choice####

Speci)icall$! the call2bac. )unction )inds the %2based inde8 o) the userCs current choice with choice-inde*! uses SchemeCs +ist-ref )unction to e8tract the corresponding string )rom ;=5-7=NI75C! and then draws the result into the message )ield o) the window, To create the window! we arrange a-choice and a-message in one row and the button in a row below:
!create-window "!+ist"!+ist"a-choice"a-message# """""""!+ist"!ma-e-8.tton"17onfirm"7hoice1"echo-choice####

66"Hode+: 66"8.i+d-n.m8er":"!listof"digit#""-/""n.m8er 66"to"trans+ate"a"+ist"of"digits"into"a"n.m8er 66"e*amp+e:"!8.i+d-n.m8er"!+ist"1"2"3##"&"123 !define"!8.i+d-n.m8er"*#"...# 66"

66"Wiew: 66"the"ten"digits"as"strings" !define"DIGI;C ""!8.i+d-+ist"1%""n.m8er-/"string## 66"a"+ist"of"three"digit"choice"men.s" !define"digit-choosers ""!local"!!define"!8.i+der"i#"!ma-e-choice"DIGI;C### """"!8.i+d-+ist"3"8.i+der### 66"a"message"fie+d"for"sa2ing"he++o"and"disp+a2ing"the"n.m8er" !define"a-msg ""!ma-e-message"1Oe+come1## 66"

66"7ontro++er:" 66"chec--ca++-8ac-":"R""-/""tr.e 66"to"get"the"c.rrent"choices"of"digits<"con0ert"them"to"a"n.m8er< 66"and"to"draw"this"n.m8er"as"a"string"into"the"message"fie+d" !define"!chec--ca++-8ac-"8# ""!draw-message"a-msg" """"""""""""""""!"n.m8er-/"string """""""""""""""""!8.i+d-n.m8er" """"""""""""""""""!map"choice-inde*"digit-choosers##### !create-window" "!+ist" ""!append"digit-choosers"!+ist"a-msg##

/list /ma.e2button ZChec. =uessZ chec.2call2bac.0000 Figure &!' A =AI )or echoing digits as numbers -ow that we ha+e e8amined some basic =AI programs! we can stud$ a program with )ull2)ledged core and =AI components, Ta.e a loo. at the de)initions in )igure 95, The programCs purpose is to echo the +alues o) se+eral digit choice menus as a number into some message )ield, The model consists o) the 8.i+d-n.m8er )unction! which con+erts a list o) /three0 digits into a number, 1e ha+e de+eloped se+eral such )unctions! so the )igure mentions onl$ what it does, The =AI component o) the program sets up three choice menus! a message )ield! and a button, The control part consists o) a single call2 bac. )unction! which is attached to the single button in the window, It determines the /list o)0 current choice indices! hands them o+er to 8.i+d-n.m8er! and draws the result as a string into the message )ield, "etCs stud$ the organi*ation o) the call2bac. )unctions in more detail, It composes three .inds o) )unctions:

(, The innermost )unction determines the current state o) the g.i-items, This is the userCs input, 1ith the gi+en )unctions! we can determine the string that the user entered into either a te8t )ield or the '2based inde8 o) a choice menu, &, This user input is consumed b$ the main )unction o) the model, The call2bac. )unction ma$ con+ert the userCs string into some other data! sa$! a s$mbol or a number, 5, The result o) the model )unction! in turn! is drawn into a message )ield! possibl$ a)ter con+erting it to a string )irst, The control component o) a program is also responsible )or the +isual composition o) the window, The teachpac. pro+ides onl$ one )unction )or this purpose: createwindow, Standard =AI toolbo8es pro+ide man$ more )unctions! though all o) these toolbo8es di))er )rom each other and are changing rapidl$, E ercise 22<!<1< Modi)$ the program o) )igure 95 so that it implements the number2 guessing game )rom e8ercises 7,(,&! 7,(,5! and >,7,7, Ma.e sure that the number o) digits that the pla$er must guess can be changed b$ editing a single de)inition in the program, >int' Recall that e8ercise ((,5,( introduces a )unction that generates random numbers, Solution E ercise 22<!<2< De+elop a program )or loo.ing up phone numbers, The programCs =AI should consist o) a te8t )ield! a message )ield! and a button, The te8t )ield permits users to enter names, The message )ield should displa$ the number that the model )inds or the message 1name"not"fo.nd1! i) the model produces fa+se, =enerali*e the program so that a user can also enter a phone number /as a se?uence o) digits containing no other characters0, >ints' /(0 Scheme pro+ides the )unction string-/sym*ol )or con+erting a string to a s$mbol, /&0 It also pro+ides the )unction string-/n.m8er! which con+erts a string to a number i) possible, I) the )unction consumes a string that doesnCt represent a number! it produces fa+se:
""!"string-/"n.m8er"1 &" 7%%%4 ""!"string-/"n.m8er"1 &"fa+se 7%%%41# 7-%%%41#

The generali*ation demonstrates how one and the same =AI can use two distinct models, 0eal23orld 48Is: The graphical user inter)ace in )igure 9' was not constructed )rom the items pro+ided b$ the teachpac., =AIs constructed with the teachpac.Cs g.i-items are primiti+e, The$ are su))icient! howe+er! to stud$ the basic principles o) =AI programming, The design o) real2world =AIs in+ol+es graphics designers and tools that generate =AI programs /rather than ma.ing them b$ hand0, Solution E ercise 22<!<!< De+elop pad-/gui, The )unction consumes a title /string0 and a g.ita8+e, It turns the table into a list o) lists o) g.i-items that create-window can consume, Here is the data de)inition )or g.i-ta8+es: A ce!! is either (, a number! &, a s$mbol, A g i-tab!e is a !listof"!listof"ce++## , Here are two e8amples o) gui2tables:
!define"pad ""'!!1"2"3# """"!4"5" # """"!7"$",# """"!Z#"%"*### !define"pad2" ""'!!1"2"3""+# """"!4"5" ""-# """"!7"$",""*# """"!%"&"Z."/###

The table on the le)t la$s out a +irtual phone pad! the right one a calculator pad, The )unction pad-/gui should turn each cell into a button, The resulting list should be pre)i8ed with two messages, The )irst one displa$s the title and ne+er changes, The second one displa$s the latest button that the user clic.ed, The two e8amples abo+e should produce the )ollowing two =AIs:

>int' The second message header re?uires a short string! )or e8ample! 1J1! as the initial +alue, Solution

The program has also cleared the result )ield to a+oid an$ misunderstanding, Similarl$! the user could also Fust hit the enter .e$ instead o) clic.ing the button, 1e ignore such subtleties here,
6<

More precisel$! we construct an obFect! but we do not need to understand the distinction between a structure and an obFect here,
6>

The g.i-items arenCt reall$ structures! which e8plains the )ont o) the operationsC names,
7'

Section 2! /athematical E amples


Appl$ing mathematics to real2world problems re?uires programs that implement mathematical )unctions, In man$ cases! the programs also emplo$ )unctions that consume and produce )unctions, Mathematics is there)ore a great starting point )or practicing programming with )unctions and! more generall$! )or creating abstract )unctions, The )irst subsection co+ers se?uences and series! a .e$ element o) mathematics, The second section discusses integration! which relies hea+il$ on series, Finall$! the third section introduces )unction di))erentiation,

"(#$ Se:uences and Series


In pre2algebra and algebra! we encounter se& ences /also .nown as progressions0 o) numbers, Here are three e8amples: (, '! &! 6! 9! <E &, (! 5! 7! ;! >E 5, 7! ('! (7! &'! &7, The )irst two enumerate the )irst )i+e e+en and odd natural numbers! respecti+el$E the last one lists the )irst )i+e positi+e integers! e+enl$ di+isible b$ 7, Se?uences can also be in)inite: (, '! &! 6! 9! <! ...E &, (! 5! 7! ;! >! ...E 5, 7! ('! (7! &'! &7! ... Following mathematical tradition! in)inite se?uences end in DD...CC and the reader must determine how to )ind more o) the terms in the se?uence, @ne wa$ to understand se?uences o) numbers! especiall$ in)inite ones! is to match them up with an enumeration o) the natural numbers, For e8ample! the e+en and odd /natural0 numbers match up li.e this:

It is eas$ to see )rom this table that e+er$ e+en number is & P i )or its inde8 i and that an odd number is & P i I (, Both statements can be translated into simple Scheme )unctions:

66"ma-e-e0en":"N""-/""N 9e0en: 66"to"comp.te"the"i-th"e0en n.m8er !define"!ma-e-e0en"i# ""!*"2"i##

66"ma-e-odd":"N""-/""N9odd: 66"to"comp.te"the"i-th"odd n.m8er !define"!ma-e-odd"i# ""!+"!*"2"i#"1##

In short! )unctions )rom natural numbers to numbers are representations o) in)inite se?uences, A mathematical series is the sum o) a se?uence, The three )inite se?uences ha+e the sums &'! &7! and ;7! respecti+el$, In the case o) in)inite se?uences it is o)ten interesting to consider a )inite portion! staring with the )irst one,7( For e8ample! adding the )irst (' e+en numbers $ields >'! and adding the )irst (' odd numbers $ields ('', Computing a series is clearl$ a Fob )or a computer, Here are )unctions that add up the )irst n odd or e+en numbers! respecti+el$! using ma-e-e0en and ma-e-odd to compute the re?uired numbers:
66"series-e0en":"N""-/" n.m8er 66"series-odd":"N""-/" n.m8er

EE to sum up the )irst

EE to sum up the )irst

66"n"e0en"n.m8ers !define"!series-e0en"n# ""!cond """"9!&"n"%#"!ma-e-e0en"n#: """"9else"!+"!ma-e-e0en"n#" """""!series-e0en"!-"n 1###:##

66"n"odd"n.m8ers !define"!series-odd"n# ""!cond """"9!&"n"%#"!ma-e-odd"n#: """"9else"!+"!ma-e-odd"n# """""!series-odd"!-"n 1###:##

The two )unctions are natural candidates )or abstraction and here is the result o) )ollowing our basic abstraction recipe:
66"series":"N"!N""-/""n.m8er#""-/""n.m8er 66"to"s.m".p"the"first"n"n.m8ers"in"the"se).ence"a-term< !define"!series"n"a-term# ""!cond """"9!&"n"%#"!a-term"n#: """"9else"!+"!a-term"n# """""!series"!-"n"1#"a-term##:##

The )irst argument speci)ies where the addition starts, The second argument o) series is a )unction that maps a natural number to the corresponding term in the series, To test series! we appl$ it to ma-e-e0en and ma-e-odd:
66"series-e0en1":"N""-/" n.m8er !define"!series-e0en1"n# ""!series"n"ma-e-e0en## 66"series-odd1":"N""-/" n.m8er !define"!series-odd1"n# ""!series"n"ma-e-odd##

For o+er a centur$! mathematicians ha+e used the =ree. s$mbol Sigma to communicate about series, The two series abo+e would be e8pressed as

A true /la*$0 mathematician would also replace ma-e-e0en and ma-e-odd b$ their de)initions! that is! & P i and & P i I (! but we re)rain )rom doing so to emphasi*e the analog$ to our /well2organi*ed0 )unctions, E ercise 2!<1<1< Ase local to create series-+oca+ )rom series-e0en and series-odd, Show with a hand2e+aluation that !series-+oca+"ma-e-e0en# is e?ui+alent to series-e0en, Solution

"(#"

rithmetic Se:uences and Series

In an arithmetic se?uence

each successor term anI( is the result o) adding a )i8ed constant to an, Here is a concrete e8ample! matched up with the natural numbers:

Here the starting point is 5 and the constant is 7, From these two )acts! called starting point and s mmand! respecti+el$! all other terms in the se?uence can be determined, E ercise 2!<2<1< De+elop the recursi+e )unction a-fi0es! which consumes a natural number and recursi+el$ determines the corresponding term in the abo+e series, Solution E ercise 2!<2<2< De+elop the non2recursi+e )unction a-fi0es-c+osed, It consumes a natural number and determines the corresponding term in the abo+e series, A non2 recursi+e )unction is sometimes called a c!osed form, Solution E ercise 2!<2<!< Ase series to determine the sum o) the a-fi0es se?uence )or the bounds 5! ;! and <<, Can an in)inite arithmetic series ha+e a sumH Solution E ercise 2!<2<#< De+elop the )unction se)-a-fi0es! which consumes a natural number n and creates the se?uence o) the )irst n terms according to a-fi0es or afi0es-c+osed, >int' Ase 8.i+d-+ist, Solution E ercise 2!<2<$< De+elop arithmetic-series, The )unction consumes two numbers: start and s, Its result is a )unction that represents the arithmetic series whose starting point is start and whose summand is s, For e8ample! !arithmetic-series"3"5# $ields a-fi0es /or a-fi0es-c+osed0, Similarl$! !arithmetic-series"%"2# produces a )unction that represents the series o) e+en numbers, Solution

"(#( 5eometric Se:uences and Series


In a geometric se?uence

each succesor term gnI( is the result o) multipl$ing a )i8ed constant with gn, Here is a concrete e8ample! matched up with the natural numbers:

Here the starting point is 5 and the constant is 7, From these! called starting point and factor! respecti+el$! e+er$ other term in the se?uence is determined, E ercise 2!<!<1< De+elop the recursi+e )unction g-fi0es! which consumes a natural number and recursi+el$ determines the corresponding term in the abo+e geometric se?uence, Solution E ercise 2!<!<2< De+elop the non2recursi+e )unction g-fi0es-c+osed, It consumes a natural number and determines the corresponding term in the abo+e series, Solution E ercise 2!<!<!< De+elop the )unction se)-g-fi0es! which consumes a natural number n and creates the se?uence o) the )irst n terms according to g-fi0es or gfi0es-c+osed, >int' Ase 8.i+d-+ist, Solution E ercise 2!<!<#< De+elop geometric-series, The )unction consumes two numbers: start and s, Its result is a )unction that represents the geometric series whose starting point is start and whose )actor is s, For e8ample! !geometric-series"3"5# $ields gfi0es /or g-fi0es-c+osed0, Solution E ercise 2!<!<$< Ase series to determine the sum o) the g-fi0es se?uence )or the bounds 5! ;! and <<, Ase series to determine the sum o) !geometric-series"1".1# )or the bounds 5! ;! <<, Can an in)inite geometric series ha+e a sumH Solution

Ta%lor Series
Mathematical constants li.e and e or )unctions li.e sin! cos! log are di))icult to compute, Since these )unctions are important )or man$ dail$ engineering applications! mathematicians ha+e spent a lot o) time and energ$ loo.ing )or better wa$s to compute these )unctions, @ne method is to replace a )unction with its Ta$lor series! which is! roughl$ spea.ing! an in)initel$ long pol$nomial,

A Tay!or series is the sum o) a se?uence o) terms, In contrast to arithmetic or geometric se?uences! the terms o) a Ta$lor series depend on two un.nowns: some +ariable * and the position i in the se?uence, Here is the Ta$lor series )or the e8ponential )unction:

That is! i) we wish to compute e+ )or an$ speci)ic +! we replace + with the number and determine the +alue o) the series, In other words! )or a speci)ic +alue o) *! sa$! (! the Ta$lor series becomes an ordinar$ series! that is! a sum o) some se?uence o) numbers:

1hile this series is the sum o) an in)initel$ long se?uence! it actuall$ is a number! and it o)ten su))ices to add Fust the )irst )ew terms to ha+e an idea what the number is, The .e$ to computing a Ta$lor series is to )ormulate each term in the underl$ing se?uence as a )unction o) * and its position i, In our running e8ample! the Ta$lor se?uence )or the e8ponential )unction has the shape

Assuming a )i8ed *! here is an e?ui+alent Scheme de)inition:


66"e-ta2+or":"N""-/""n.m8er !define"!e-ta2+or"i# ""!/"!e*pt"*"i#"!D"i### 66"D":"N""-/""n.m8er !define"!D"n# ""!cond """"9!&"n"%#"1: """"9else"!*"n"!D"!s.81"n###:##

The )irst )unction computes the termE the second computes the )actorial o) a natural number, To compute the +alue o) e+! we now Fust need to as. )or !series"1%"eta2+or#! assuming we want the )irst 1% items o) the se?uence included, Putting e+er$thing together! we can de)ine a )unction that computes the *th power o) e, Since the )unction re?uires two au8iliaries! we use a local:
!define"!e-power"*# ""!local"!!define"!e-ta2+or"i# """"!/"!e*pt"*"i#"!D"i### ""!define"!D"n# """"!cond """"""9!&"n"%#"1: """"""9else"!*"n"!D"!s.81"n###:### """"!series"1%"e-ta2+or###

E ercise 2!<!<&< Replace 1% b$ 3 in the de)inition o) e-power and e+aluate !e-power 1# b$ hand, Show onl$ those lines that contain new applications o) e-ta2+or to a number, The results o) e-power are )ractions with large numerators and denominators, In contrast! SchemeCs built2in e*p )unction produces an ine8act number, 1e can turn e8act )ractions into ine8act numbers with the )ollowing )unction:
66""e*act-/"ine*act":"n.m8er"9e*act:""-/""n.m8er"9ine*act:"

Test the )unction and add it to e-powerCs bod$, Then compare the results o) e*p and epower, Increase the number o) items in the series until the di))erence between the results is small, Solution E ercise 2!<!<(< De+elop the )unction +n! which computes the Ta$lor series )or the natural logarithm, The mathematical de)inition o) the series is

This Ta$lor series has a +alue )or all * that are greater than %, DrScheme also pro+ides +og! a primiti+e )or computing the natural logarithm, Compare the results )or +n and +og, Then use e*act-/ine*act /see e8ercise &5,5,90 to get results that are easier to compare, Solution E ercise 2!<!<)< De+elop the )unction m2-sin! which computes the Ta$lor series )or sin! one o) the trigonometric )unctions, The Ta$lor series is de)ined as )ollows:

It is de)ined )or all *, >int' The sign o) a term is positi+e i) the inde8 is e+en and negati+e otherwise, Mathematicians compute / - (0i to determine the signE programmers can use cond instead, Solution E ercise 2!<!<-< Mathematicians ha+e used series to determine the +alue o) )or man$ centuries, Here is the )irst such se?uence! disco+ered b$ =regor$ /(95<2(9;70:

De)ine the )unction greg! which maps a natural number to the corresponding term in this se?uence, Then use series to determine appro8imations o) the +alue o) , Note on : The appro8imation impro+es as we increase the number o) items in the series, An)ortunatel$! it is not practical to compute with this de)inition, Solution

"(#) The

rea <nder a +unction

Consider the )unction graph in )igure 96, Suppose we wish to .now the area between the + a8is! the )at lines labeled a and b! and the graph, Determining the area under the graph o) a )unction )or some speci)ic inter+al is called integrating a f nction, Since engineers had to sol+e this .ind o) problem be)ore computers were a+ailable! mathematicians ha+e studied it e8tensi+el$, For a small class o) )unctions! it is indeed possible to determine the area e8actl$, For the other cases! mathematicians ha+e de+eloped se+eral methods to determine close estimates, Since these methods in+ol+e lots o) mechanical calculations! the$ are natural candidates )or computer )unctions,

Figure &#' Integrating a )unction f between a and b A general integration )unction must consume three inputs: a! 8! and the )unction f, The )ourth part! the + a8is! is implied, This suggests the )ollowing contract:
66"integrate":"!n.m8er""-/""n.m8er#"n.m8er"n.m8er""-/""n.m8er 66"to"comp.te"the"area".nder"the"graph"of"f"8etween"a"and"8 !define"!integrate"f"a"8#"...#

epler suggested one simple integration method, It consists o) three steps: (, di+ide the inter+al into two parts: Va!/a I bK&0W and V/a I bK&0!bWE

&, compute the area o) each trape'oidE and 5, add the two areas to get an estimate at the integral, E ercise 2!<#<1< De+elop the )unction integrate--ep+er, It computes the area under some the graph o) some )unction f between +eft and right using eplerCs rule, Solution Another simple method is to thin. o) the area as a se?uence o) man$ small rectangles, #ach rectangle is as tall as the )unction graph in! sa$! the middle o) the rectangle, Figure 96 shows two e8amples, B$ adding up the area o) the rectangles! we get a good estimate at the area under the graph, The more rectangles we consider! the closer the estimate is to the actual area, "et us agree that Q stands )or the number o) rectangles that we wish to consider, To determine how large these rectangles are! we need to )igure out how large their sides are, The length o) the side on the + a8is is the length o) the inter+al di+ided b$ the number o) rectangles:

For the height o) the rectangle! we need to determine its midpoint and then the +alue o) f at the midpoint, The )irst midpoint is clearl$ at a plus hal) o) the width o) the rectangle! that is! i)

the area is

where # stands )or -idth and 6 )or step )rom now on, To get )rom the rectangle starting at a to the ne8t one on the right! we must add the width o) one rectangle, That is! the ne8t midpoint /called +( in )igure 960 is at

the third one at

and so on, The )ollowing table e8plains the three se?uences that are in+ol+ed in the usual manner:

In the second row! M stands )or midpoint, The )irst rectangle has inde8 '! the last one : - (, Asing this se?uence o) rectangles! we can now determine the area under the graph as a series:

E ercise 2!<#<2< De+elop the )unction integrate, It computes the area under some the graph o) some )unction f between +eft and right using the rectangle2series method, Ase test cases )or f! a! and 8 )or which one can determine the area e8actl$ and easil$ b$ hand! )or e8ample! !define"!id"*#"*#, Compare the results with those o) integrate )rom e8ercise &5,6,(, Ma.e Q a top2le+el constant:
66"Q":"n.m8er"of"rectang+es"to"appro*imate"integra+ !define"Q"...#

Test integrate on sin and increase Q graduall$ )rom 1% to 1%%%%, 1hat happens to the resultH Solution

"(#* The Slope of a +unction


"et us ta.e another loo. at the )unction graph in )igure 96, For man$ problems! we need to be able to draw a line that has the same slope as some cur+e at a certain point, Indeed! computing the slope is o)ten the true goal, In economics problems! the slope is the growth rate o) a compan$ i) the cur+e represents the income o+er time, In a ph$sics problem! the cur+e could represent the +elocit$ o) some obFectE its slope! at an$ point! is then the current acceleration o) the obFect, Determining the slope o) some )unction f at some point + is to differentiate the )unction, The di))erential operator /also called a )unctional0 returns a )unction fC /pronounced DD) primeCC0, It tells us )or an$ + what the slope o) f is at that point, Computing fC is complicated! so it is again a good tas. )or a computer program, The program consumes some )unction f and produces fC,

Figure &$' The graph o) some )unction To design a DDdi))erentiatorCC we must stud$ how we could construct lines that ha+e the same slope as a cur+e, In principle! such a line touches the cur+e at Fust that point, But suppose we rela8 this constraint )or a moment and loo. at straight lines that intersect the cur+e close to the point o) interest, 1e pic. two points that are e?uall$ )ar awa$ )rom +! sa$! + - and + I E the constant ! pronounced epsilon! represents some small distance, Asing the two corresponding points on the cur+e! we can determine a straight line that has the proper slope, The situation is s.etched in )igure 97, I) the point o) interest has coordinate +! the two points are /+!f/+ - 00 and /+!f/+ I 00, Hence the slope o) the line is

That is! the di))erence between the height o) the right point and the le)t point di+ided b$ their hori*ontal distance, Determining the line )rom the slope and one o) the points or e+en )rom two points is an e8ercise, E ercise 2!<$<1< The e?uation )or a line is

B$ now! it is straight)orward to translate this e?uation into Scheme:


!define"!2"*# ""!+"!*"a"*#"8##

To obtain a concrete line we must replace a and 8 with numbers,

The teachpac. graphing.ss pro+ides one operation )or drawing lines: graph-+ine, The operation consumes a line li.e 2 and a color! sa$! 'red, Ase graph-+ine to draw the graphs o) the )ollowing lines: (, y(/+0 O + I 6 &, y&/+0 O 6 - + 5, y5/+0 O + I (' 6, y6/+0 O (' - + 7, y7/+0 O (&

Solution E ercise 2!<$<2< It is a standard mathematical e8ercise to de+elop the e?uation )or a line )rom a point on the line and its slope, "oo. up the method in $our mathematics boo., Then de+elop the )unction +ine-from-point+s+ope! which implements the method, The )unction consumes a posn /the point0 and a number /the slope0, It produces a )unction that represents the line in the spirit o) e8ercise &5,7,(, Testing a )unction2producing )unction li.e +ine-from-point+s+ope can be done in two wa$s, Suppose we appl$ the )unction to /'!60 and (, The result should be line y( )rom e8ercise &5,7,(, To chec. this! we can either appl$ the result o)
!+ine-from-point+s+ope"!ma-e-posn"%"4#"1#

to some numbers! or we can draw the result using the operations in graphing.ss, In the )irst case! we must use y( to compare outputsE in the second case we can draw the result in one color and the hand2constructed line in a di))erent one and obser+e the e))ect, Solution @nce we ha+e an intersecting line through /+!f/+ - 00 and /+!f/+ I 00! we can also get a line with the proper slope, B$ decreasing until it is /almost0 indistinguishable )rom '! the two intersection points mo+e closer and closer until the$ are one! namel$! /+!f/+00! the point )or which we wish to .now the slope,7& E ercise 2!<$<!< Ase the operation graph-f.n in the teachpac. graphing.ss to draw the mathematical )unction

The operation wor.s Fust li.e draw-+ine /see e8ercise &5,7,(,0 Suppose we wish to determine the slope at + O &, Pic. an S ' and determine the slope o) the line that goes through /+!f/+ - 00 and /+!f/+ I 00 with the abo+e )ormula, Compute the line with +ine-from-point+s+ope )rom e8ercise &5,7,& and use draw-+ine to draw it into the same coordinate s$stem as 2, Repeat the process with K& and then with K6, Solution I) our goal is to de)ine the di))erential operator as a Scheme )unction! we can appro8imate it b$ setting to a small number and b$ translating the mathematical )ormula into a Scheme e8pression:
66"d/d*":"!n.m""-/""n.m#""-/""!n.m""-/""n.m# 66"to"comp.te"the"deri0ati0e"f.nction"of"f"n.merica++2 !define"!d/d*"f# ""!local"!!define"!fprime"*# """"!/"!-"!f"!+"*" ##"!f"!-"*" ### """""""!*"2" ### ""!define" "...## """"fprime##

-ote that d/d* consumes and produces )unctions 22 Fust li.e the di))erential operator in mathematics, As mentioned in the introduction to this section! the di))erential operator computes the )unction fC )rom some )unction f, The )ormer computes the slope o) f )or an$ +, For straight lines! the slope is alwa$s .nown, Hence a )unction that represents a straight line is an ideal test case )or d/d*, "et us consider
!define"!a-+ine"*# ""!+"!*"3"*#"1##

The e+aluation o) !d/d*"a-+ine# proceeds as )ollows:


""!d/d*"a-+ine# &"!local"!!define"!fprime"*# """"!/"!-"!a-+ine"!+"*" ##"!a-+ine"!-"*" ### """""""!*"2" ### ""!define" "...## """"fprime# &"!define"!fprime"*# """"!/"!-"!a-+ine"!+"*" ##"!a-+ine"!-"*" ### """""""!*"2" ### ""!define" "...# ""fprime

-ow! i) we thin. o) !+"*" # and !-"*" # as numbers! we can e+aluate the application o) a-+ine in the de)inition o) fprime:75

""!define"!fprime"*# """"!/"!-"!+"!*"3"!+"*" ##"1#"!+"!*"3"!-"*" ##"1## """""""!*"2" ### &"!define"!fprime"*# """"!/"!-"!*"3"!+"*" ##"!*"3"!-"*" ### """""""!*"2" ### &"!define"!fprime"*# """"!/"!*"3"!-"!+"*" #"!-"*" ### """""""!*"2" ### &"!define"!fprime"*# """"!/"!*"3"!*"2" ## """""""!*"2" ### &"!define"!fprime"*# """"3#

In other words! the result o) !d/d*"a-+ine# alwa$s returns 5! which is the slope o) a+ine, In short! we not onl$ got a close appro8imation because is small! we actuall$ got the correct answer, In general! howe+er! the answer will depend on and will not be precise, E ercise 2!<$<#< Pic. a small and use d/d* to compute the slope o)

at + O &, How does the result compare with $our calculation in e8ercise &5,7,5H Solution E ercise 2!<$<$< De+elop the )unction +ine-from-two-points, It consumes two points p1 and p2, Its result is a Scheme )unction that represents the line through p1 and p2, Buestion: Are there an$ situations )or which this )unction ma$ )ail to compute a )unctionH I) so! re)ine the de)inition to produce a proper error message in this case, Solution E ercise 2!<$<&< Compute the slope o) the )ollowing )unction
!define"!f"*#" ""!+"!*"1/ %"!*"*"*"*## """""!*"-1/1%"!*"*"*## """""5##

at + O 6, Set to 2! 1! .5, Tr$ the same )or some other +alue o) *,

Solution

In some cases! an in)inite se?uence ma$ also ha+e a sum, Speci)icall$! adding up more and more o) the terms o) a se?uence produces numbers that are closer and closer to some number! which we call the sum, For e8ample! the sum o) the se?uence
7(

is &, In contrast! the se?uence

does not ha+e a sum, The process o) decreasing to ' is a con+ergence /or limit0 process, It does not alwa$s succeed! that is! )or some )unction graphs! the process does not end properl$, 1e ignore those cases! but the$ are common and re?uire special attention,
7&

I) * is a number! then adding or subtracting $ields a number, I)! b$ accident! we appl$ fprime to something else! both e8pressions signal an error, It is there)ore acceptable to
75

act as i) the e8pressions were +alues, In general! this is not true,

Section 2# Interme**o #' Defining Functions on the Fl%


Man$ uses o) abstract )unctions re?uire the de)inition o) au8iliar$ )unctions, Consider fi+ter1! which consumes a )iltering )unction! a list! and a )iltering item, In the pre+ious section alone! we encountered three uses o) fi+ter1 with three di))erent au8iliar$ )unctions: s).aredA! ?ir! and e)-irA, Since these au8iliar$ )unctions are onl$ used as arguments to fi+ter1! we should emplo$ the program organi*ation guidelines )rom the preceding interme**o /(<0, That is! we should use a local2e8pression to indicate that the application o) fi+ter1 and the au8iliar$ )unction de)inition belong together, Here is one possible arrangement )or the fi+ter1-e)-irA combination:
66"find":"+ist-of-IQs"s2m8o+""-/""8oo+ean !define"!find"a+oir"t# ""!local"!!define"!e)-irA"ir"p# """"!s2m8o+&A"!ir-name"ir#"p### """"!fi+ter1"e)-irA"a+oir"t###

An alternati+e arrangement places the local2e8pression where the )unction is needed:


66"find":"+ist-of-IQs"s2m8o+""-/""8oo+ean !define"!find"a+oir"t# ""!fi+ter1"!local"!!define"!e)-irA"ir"p# """""!s2m8o+&A"!ir-name"ir#"p### """""e)-irA# """""""""""a+oir"t##

This alternati+e is )easible because the names o) )unctions 22 li.e e)-irA 22 are now legitimate e8pressions and can pla$ the role o) localCs bod$, Thus the local2e8pression introduces a )unction de)inition and returns the )unction as its result, Because good programmers use abstract )unctions and organi*e their programs in a tid$ manner! it is not surprising that Scheme pro+ides a short2hand )or this particular! )re?uent use o) local, The short2hand is called a lambda2e8pression and greatl$ )acilitates the introduction o) )unctions li.e e)-irA! s).aredA! or ?ir, The )ollowing two subsections introduce the s$nta8 and semantics o) lambda2e8pressions, The last subsection discusses its pragmatics,

S%nta of lambda

A lambda2e8pression is Fust a new )orm o) e8pression:


?e*p/

O /lambda /?0ar/ ,,, ?0ar/0 ?e*p/0

Its distinguishing characteristic is the .e$word lambda, It is )ollowed b$ a se?uence o) +ariables! enclosed in a pair o) parentheses, The last component is an e8pression, Here are three use)ul e8amples: (, !lambda"!*"c#"!/"!*"*"*#"c## &, !lambda"!ir"p#"!?"!ir-price"ir#"p## 5, !lambda"!ir"p#"!s2m8o+&A"!ir-name"ir#"p## The$ correspond to s).aredA! ?ir! and e)-irA! respecti+el$! the three moti+ating e8amples discussed abo+e, A lambda2e8pression de)ines an anon$mous )unction! that is! a )unction without a name, The se?uence o) +ariables behind lambda are the )unctionCs parametersE the third component is the )unctionCs bod$,

Scope and Semantics of lambda


As discussed in the introduction! a lambda2e8pression is Fust a short2hand )or a local2 e8pression, In general! we can thin. o)
!lambda"!*-1"...""*-n#"e*p#

as The name o)
!local"!!define"!a-new-name"*-1"..."*-n#"e*p## ""a-new-name# the )unction! a-new-name! ma$ not occur in e*p,

The short2hand e8planation suggests that


!lambda"!*-1"...""*-n#"e*p#

introduces *-1 ...*-n as binding occurrences and that the scope o) parameters is e*p, @) course! i) e*p contains )urther binding constructs /sa$! a nested local2e8pression0! then the scope o) the +ariables ma$ ha+e a hole, Similarl$! the e8planation implies basic )acts that go+ern the e+aluation o) lambda2 e8pressions:

(, A lambda2e8pression is a +alue because )unctions are +alues, &, The application o) lambda2e8pressions to +alues proceeds according to our usual laws o) )unction application! assuming we e8pand the short2hand )irst, Here is a sample use o) lambda:
""!fi+ter1"!lambda"!ir"p#"!?"!ir-price"ir#"p## """""""""""!+ist"!ma-e-ir"'do++"1%## """$#

The application o) fi+ter1 consumes the lambda2e8pression! a /short0 list o) in+entor$ records! and a threshold, =i+en our suggestion! the e+aluation can be understood b$ an e8pansion o) the lambda2e8pression into a corresponding local2e8pression:
... &"!fi+ter1"!local"!!define"!?ir"ir"p#"!?"!ir-price"ir#"p###"?ir# """""""""""!+ist"!ma-e-ir"'do++"1%## """$# &"!fi+ter1"?ir" """""""""""!+ist"!ma-e-ir"'do++"1%## """$#

For the last step! the local de)inition o) ?ir is li)ted and added to the top2le+el de)initions, From here! the e+aluation proceeds as in section (>,&, 1hile it is natural to thin. o) lambda as a short2hand! the last two points also suggest a wa$ o) understanding lambda2e8pressions directl$, In particular! we can adapt the law o) application to lambda2e8pressions:
""!!lambda"!*-1"..."*-n# e*p#""" """0a+-1"..."0a+-n#"" "" "" ""&"e*p """"with"a++"occ.rrences"of"*1"..."*-n """"rep+aced"82"0a+-1"..."0a+-n ""

That is! the application o) a lambda2e8pression proceeds Fust li.e that o) an ordinar$ )unction, 1e replace the parameters o) the )unction with the actual argument +alues and compute the +alue o) the )unction bod$, "et us reconsider the abo+e e8ample in this light:
""!fi+ter1"!lambda"!ir"p#"!?"!ir-price"ir#"p## """""""""""!+ist"!ma-e-ir"'do++"1%## """""""""""$# 's".s.a+<"this"app+ication"is"rep+aced"82"the"8od2"of"fi+ter1 with"a++"parameters"rep+aced"82"their"0a+.es.";his"step"p+aces"a lambda-e*pression"into"the"f.nction"position"of"an"app+ication: &"!cond """"9!!lambda"!ir"p#"!?"!ir-price"ir#"p## """"""!ma-e-ir"'do++"1%#"$#" """""!cons"!first"!+ist"!ma-e-ir"'do++"1%###

"""""""!fi+ter1"!lambda"!ir"p#"!?"!ir-price"ir#"p## """"""""!rest"!+ist"!ma-e-ir"'do++"1%### """"""""$##: """"9else """"""!fi+ter1"!lambda"!ir"p#"!?"!ir-price"ir#"p## "" """""""!rest"!+ist"!ma-e-ir"'do++"1%### """""""$#:# &"!cond """"9!?"!ir-price"!ma-e-ir"'do++"1%##"$# """""!cons"!first"!+ist"!ma-e-ir"'do++"1%### """""""!fi+ter1"!lambda"!ir"p#"!?"!ir-price"ir#"p## """"""""!rest"!+ist"!ma-e-ir"'do++"1%### """"""""$##: """"9else """"""!fi+ter1"!lambda"!ir"p#"!?"!ir-price"ir#"p## "" """""""!rest"!+ist"!ma-e-ir"'do++"1%### """""""$#:# &"...

From here! the e+aluation proceeds as usual, Still! e+en this short2hand e+aluation shows that! while using lambda2e8pressions in programs is con+enient! replacing it with a named )unction /o)ten0 simpli)ies calculations, E ercise 2#<.<(< Decide which o) the )ollowing phrases are legal lambda2e8pressions: (, !lambda"!*"2#"!*"2"2## &, !lambda"!#"1%# 5, !lambda"!*#"*# 6, !lambda"!*"2#"*# 7, !lambda"*"1%#

#8plain wh$ the$ are legal or illegal,

Solution

E ercise 2#<.<)< Draw arrows )rom the underlined occurrences o) * to their binding occurrences in each o) the )ollowing three lambda2e8pressions: (,
2. !lambda"!*"2#

3. ""!+"+"!*"*"2###

6,
5. . 7. $. ,. !lambda"!*"2# ""!+"+ """""!local"!!define"*"!*"2"2### """""""!+"!*"3"+# ""!/"1"*#####

(',
11.!lambda"!*"2# 12.""!+"+ 13."""""!!lambda"!*# 14. !+"!*"3"+# 15. """!/"1"*### 1 .""""""!*"2"2####

Also draw a bo8 )or the corresponding scope o) each underlined * and holes in the scope where necessar$, Solution E ercise 2#<.<-< #+aluate the )ollowing e8pressions b$ hand: (,
2. !!lambda"!*"2# 3. """!+"+"!*"*"2### 4. "1"2#

7,
. !!lambda"!*"2# 7. """!+"+ $. """"""!local"!!define"*"!*"2"2### ,. !+"!*"3"+# 1%. """!/"1"*##### 11."1"2#

(&,
13.!!lambda"!*"2# 14."""!+"+ 15.""""""!!lambda"!*# 1 . "!+"!*"3"+# 17. """"!/"1"*### 1$."""""""!*"2"2#### 1,."1"2#

Solution

Pragmatics of lambda

The guideline )or using lambda2e8pressions is straight)orward:

=uideline on "ambda #8pressions


Ase lambda2e8pressions when a )unction is not recursi+e and is onl$ needed once in an argument position, I) we were to appl$ the guideline to the programs in the preceding sections! we would ?uic.l$ see how much lambda simpli)ies the use o) abstracted )unctions, For that reason! Scheme o))ers man$ abstracted )unctions in its libraries, In )uture sections! we will encounter man$ more e8amples where lambda2e8pressions are con+enient,

Part " 4enerati1e 0ecursion Section 2$ + Ne3 Form of 0ecursion


The )unctions we ha+e de+eloped so )ar )all into two broad categories, @n one hand! we ha+e the categor$ o) )unctions that encapsulate domain .nowledge, @n the other hand! we ha+e )unctions that consume structured data, These )unctions t$picall$ decompose their arguments into their immediate structural components and then process those components, I) one o) the immediate components belongs to the same class o) data as the input! the )unction is recursi+e, For that reason! we re)er to these )unctions as /STRACTARA""30 R#CARSI4# FA-CTI@-S, In some cases! howe+er! we also need )unctions based on a di))erent )orm o) recursion! namel$! generati+e recursion, The stud$ o) this )orm o) recursion is as old as mathematics and is o)ten called the stud$ o) A"=@RITHMS, The inputs o) an algorithm represent a problem, #8cept )or rare occasions! the problem is an instance o) a large class o) problems and the algorithm wor.s )or all o) these problems, In general! an algorithm partitions a problem into other! smaller problems and sol+es those, For e8ample! an algorithm )or planning a +acation trip re?uires arrangements )or a trip )rom our home to a nearb$ airport! a )light to an airport near our +acation spot! and a trip )rom that airport to our +acation hotel, The entire problem is sol+ed b$ combining the solutions )or these problems, Designing an algorithm distinguishes two .inds o) problems: those that are TRI4IA""3 S@"4AB"#76 and those that are not, I) a gi+en problem is tri+iall$ sol+able! an algorithm produces the matching solution, For e8ample! the problem o) getting )rom our home to a nearb$ airport might be tri+iall$ sol+able, 1e can dri+e there! ta.e a cab! or as. a )riend to drop us o)), I) not! the algorithm generates a new problem and sol+es those new problems, A multistage trip is an e8ample o) a problem that is non2tri+ial and can be sol+ed b$ generating new! smaller problems, In a computational setting one o) the smaller problems o)ten belongs to the same class o) problems as the original one! and it is )or this reason that we call the approach =#-#RATI4# R#CARSI@-,

In this part o) the boo.! we stud$ the design o) algorithms! that is! )unctions based on generati+e recursion, From the description o) the idea! we .now that this process is much more o) an ad hoc acti+it$ than the data2dri+en design o) structurall$ recursi+e )unctions, Indeed! it is almost better to call it in+enting an algorithm than designing one, In+enting an algorithm re?uires a new insight 22 a DDeure.a,CC Sometimes +er$ little insight is re?uired, For e8ample! sol+ing a DDproblemCC might Fust re?uire the enumeration o) a series o) numbers, At other times! howe+er! it ma$ rel$ on a mathematical theorem concerning numbers, @r! it ma$ e8ploit a series o) mathematical results on s$stems o) e?uations, To ac?uire a good understanding o) the design process! it is necessar$ to stud$ e8amples and to de+elop a sense )or the +arious classes o) e8amples, In practice! new comple8 algorithms are o)ten de+eloped b$ mathematicians and mathematical computer scientistsE programmers! though! must throughl$ understand the underl$ing ideas so that the$ can in+ent the simple algorithms on their own and communicate with scientists about the others, The two subsections illustrate two +astl$ di))erent algorithms, The )irst one is an e8ample o) something programmers in+ent on a dail$ basis, The second one describes a )ast sorting algorithm! one o) the )irst applications o) generati+e recursion in computing, Terminolog%: Mathematical computer scientists o)ten do not distinguish between structural recursion and generati+e recursion and re)er to both .inds o) )unctions as algorithms, Instead the$ use the terminolog$ o) R#CARSI4# and IT#RATI4# methods, The latter re)ers to a subclass o) )unction de)initions whose recursi+e )unction applications are in a particular position in the de)inition, 1e will strictl$ adhere to the terminolog$ o) algorithm and generati+e recursion when we wor. with this class o) )unctions because this classi)ication matches our thin.ing o) design recipes better than the purel$ s$ntactic classi)ication o) applied mathematicians,

"*#$ /odeling a Ball on a Ta&le


"etCs consider the simple2loo.ing problem o) modeling the mo+es o) a ball across a table, Assume the ball rolls at a constant speed until it drops o)) the table, 1e can model the table with a can+as o) some )i8ed width and height, The ball is a dis. that mo+es across the can+as! which we e8press with drawing the dis.! waiting! and clearing it! until it is out o) bounds,

66";each3ac-:"draw.ss" !define-struct"8a++"!*"2"de+ta-*"de+ta-2## 66"'"*all"is"a"str.ct.re:" 66"""!ma-e-8a++"n.m8er"n.m8er"n.m8er"n.m8er# 66"draw-and-c+ear":"a-8a++""-/""tr.e 66"draw<"s+eep<"c+ear"a"dis-"from"the"can0as" 66"str.ct.ra+"design<"Ccheme"-now+edge !define"!draw-and-c+ear"a-8a++# ""!and """!draw-so+id-dis-"!ma-e-posn"!8a++-*"a-8a++#"!8a++-2"a-8a++##"5 'red# """!s+eep-for-a-whi+e"DELAY# """!c+ear-so+id-dis-"!ma-e-posn"!8a++-*"a-8a++#"!8a++-2"a-8a++##"5 'red### 66"mo0e-8a++":"8a++""-/""8a++ 66"to"create"a"new"8a++<"mode+ing"a"mo0e"82"a-8a++ 66"str.ct.ra+"design<"ph2sics"-now+edge !define"!mo0e-8a++"a-8a++#" ""!ma-e-8a++"!+"!8a++-*"a-8a++#"!8a++-de+ta-*"a-8a++## """""""""""""!+"!8a++-2"a-8a++#"!8a++-de+ta-2"a-8a++## """""""""""""!8a++-de+ta-*"a-8a++# """""""""""""!8a++-de+ta-2"a-8a++### 66"Dimension"of"can0as" !define"OID;="1%%# !define"=5IG=;"1%%#

/define DE,+C ,(0 Figure &&' Au8iliaries )or move- nti!-o t Figure 99 collects the )unction! structure! data! and +ariable de)initions that model the ball: (, A ball is a structure with )our )ields: the current position and the +elocit$ in each direction, That is! the )irst two numbers in a 8a++ structure are the current position on the can+as! and the ne8t two numbers describe how )ar the ball mo+es in the two directions per step, &, The )unction mo0e-8a++ models the ph$sical mo+ement o) the ball, It consumes a ball and creates a new one! modeling one step, 5, The )unction draw-and-c+ear draws the ball at its current position! then waits )or a short time! and clears it again, The +ariable de)initions speci)$ the dimensions o) the can+as and the dela$ time, To mo+e the ball a )ew times we can write
!define"the-8a++"!ma-e-8a++"1%"2%"-5"+17##

!and "!draw-and-c+ear"the-8a++# "!and" """!draw-and-c+ear"!mo0e-8a++"the-8a++## """...##

though this gets tedious a)ter a while, 1e should instead de+elop a )unction that mo+es the ball until it is out o) bounds, The eas$ part is to de)ine o.t-of-8o.ndsA! a )unction that determines whether a gi+en ball is still +isible on the can+as:
66"o.t-of-8o.ndsA":"a-8a++""-/""8oo+ean 66"to"determine"whether"a-8a++"is"o.tside"of"the"8o.nds 66"domain"-now+edge<"geometr2 !define"!o.t-of-8o.ndsA"a-8a++# ""!not """!and """""!?&"%"!8a++-*"a-8a++#"OID;=# """""!?&"%"!8a++-2"a-8a++#"=5IG=;####

1e ha+e de)ined numerous )unctions li.e o.t-of-8o.ndsA in the )irst )ew sections o) the boo., In contrast! writing a )unction that draws the ball on the can+as until it is out o) bounds belongs to a group o) programs that we ha+enCt encountered thus )ar, "etCs start with the basics o) the )unction:
66"mo0e-.nti+-o.t":"a-8a++""-/""tr.e 66"to"mode+"the"mo0ement"of"a"8a++".nti+"it"goes"o.t"of"8o.nds !define"!mo0e-.nti+-o.t"a-8a++#"...#

Because the )unction consumes a ball and draws its mo+ement on a can+as! it produces tr.e li.e all other )unctions that draw onto a can+as, Designing it with the recipe )or structures ma.es no sense! howe+er, A)ter all! it is alread$ clear how to draw-andc+ear the ball and how to mo+e it! too, 1hat is needed instead is a case distinction that chec.s whether the ball is out o) bounds or not, "et us re)ine the )unction header with an appropriate cond2e8pression:
!define"!mo0e-.nti+-o.t"a-8a++# ""!cond """"9!o.t-of-8o.ndsA"a-8a++#"...: """"9else"...:##

1e ha+e alread$ de)ined the )unction o.t-of-8o.ndsA because it was clear )rom the problem description that DDbeing out o) boundsCC was a separate concept, I) the ball consumed b$ mo0e-.nti+-o.t is outside o) the can+asCs boundaries! the )unction can produce tr.e! )ollowing the contract, I) the ball is still inside the

boundaries! two things must happen, First! the ball must be drawn and cleared )rom the can+as, Second! the ball must be mo+ed! and then we must do things all o+er again, This implies that a)ter mo+ing the ball! we appl$ mo0e-.nti+-o.t again! which means the )unction is recursi+e:
66"mo0e-.nti+-o.t":"a-8a++""-/""tr.e 66"to"mode+"the"mo0ement"of"a"8a++".nti+"it"goes"o.t"of"8o.nds !define"!mo0e-.nti+-o.t"a-8a++# ""!cond """"9!o.t-of-8o.ndsA"a-8a++#"tr.e: """"9else"!and"!draw-and-c+ear"a-8a++# """""""""""""""!mo0e-.nti+-o.t"!mo0e-8a++"a-8a++###:##

Both !draw-and-c+ear"a-8a++# and !mo0e-.nti+-o.t"!mo0e-8a++"a-8a++## produce true! and both e8pressions must be e+aluated, So we combine them with an and2e8pression, 1e can now test the )unction as )ollows:
!start"OID;="=5IG=;# !mo0e-.nti+-o.t"!ma-e-8a++"1%"2%"-5"+17## !stop#

This creates a can+as o) proper si*e and a ball that mo+es le)t and down, A close loo. at the )unction de)inition re+eals two peculiarities, First! although the )unction is recursi+e! its bod$ consists o) a cond2e8pression whose conditions ha+e nothing to do with the input data, Second! the recursi+e application in the bod$ does not consume a part o) the input, Instead! mo0e-.nti+-o.t generates an entirel$ new and di))erent 8a++ structure! which represents the original ball a)ter one step! and uses it )or the recursion, Clearl$! none o) our design recipes could possibl$ produce such a de)inition, 1e ha+e encountered a new wa$ o) programming, E ercise 2$<1<1< 1hat happens i) we place the )ollowing three e8pressions
!start"OID;="=5IG=;# !mo0e-.nti+-o.t"!ma-e-8a++"1%"2%"%"%## !stop#

at the bottom o) the Definitions window and clic. 5*ec.teH Does the second e8pression e+er produce a +alue so that the third e8pression is e+aluated and the can+as disappearsH Could this happen with an$ o) the )unctions designed according to our old recipesH Solution E ercise 2$<1<2< De+elop mo0e-8a++s, The )unction consumes a list o) balls and mo+es each one until all o) them ha+e mo+ed out o) bounds,

>int' It is best to write this )unction using fi+ter! andmap! and similar abstract )unctions )rom part I4, Solution

"*#" Sorting =uickly


HoareCs ?uic.sort algorithm is the classic e8ample o) generati+e recursion in computing, "i.e sort in section (&,&! )sort is a )unction that consumes a list o) numbers and produces a +ersion that contains the same numbers in ascending order, The di))erence between the two )unctions is that sort is based on structural recursion and )sort is based on generati+e recursion, The underl$ing idea o) the generati+e step is a time2honored strateg$: di+ide and con?uer, That is! we di+ide the non2tri+ial instances o) the problem into two smaller! related problems! sol+e those smaller problems! and combine their solutions into a solution )or the original problem, In the case o) )sort! the intermediate goal is to di+ide the list o) numbers into two lists: one that contains all the items that are strictl$ smaller than the )irst item! and another one with all those items that are strictl$ larger than the )irst item, Then the two smaller lists are sorted using the same procedure, @nce the two lists are sorted! we simpl$ Fu8tapose the pieces, @wing to its special role! the )irst item on the list is o)ten called the pivot item,
!+ist"11"$"14"7# !+ist"$"7# !+ist"7# empt2 7 empt2 !+ist"7# !+ist"7"$# !+ist"7"$"11"14# $ empt2 11 !+ist"14# empt2 14 empt2 !+ist"14#

Figure &(' A tabular illustration o) & ic$-sort To de+elop a better understanding o) the process! letCs wal. through one step o) the e+aluation b$ hand, Suppose the input is
!+ist"11"$"14"7#

The pi+ot item is 11, Partioning the list into items larger and smaller than 11 produces two lists:
!+ist"$"7#

and
!+ist"14#

The second one is alread$ sorted in ascending orderE sorting the )irst one produces !+ist"7"$#, This lea+es us with three pieces )rom the original list: (, !+ist"7"$#! the sorted +ersion o) the list with the smaller numbersE &, 11E and 5, !+ist"14#! the sorted +ersion o) the list with the larger numbers, To produce a sorted +ersion o) the original list! we concatenate the three pieces! which $ields the desired result: !+ist"7"$"11"14#, @ur illustration lea+es open how )sort .nows when to stop, Since it is a )unction based on generati+e recursion! the general answer is that it stops when the sorting problem has become tri+ial, Clearl$! empt2 is one tri+ial input )or )sort! because the onl$ sorted +ersion o) it is empt2, For now! this answer su))icesE we will return to this ?uestion in the ne8t section, Figure 9; pro+ides a tabular o+er+iew o) the entire sorting process )or !+ist"11"$"14 7#, #ach bo8 has three compartments: list to be sorted sort process )or partition with items sort process )or partition with items pi+ot sma!!er than pi+ot !arger than pi+ot item sorted list

The top compartment shows the list that we wish to sort! and the bottommost contains the result, The three columns in the middle displa$ the sorting process )or the two partitions and the pi+ot item,

E ercise 2$<2<1< Simulate all )sort steps )or !+ist"11","2"1$"12"14"4"1#, Solution -ow that we ha+e a good understanding o) the generati+e step! we can translate the process description into Scheme, The description suggests that )sort distinguishes two cases, I) the input is empt2! it produces empt2, @therwise! it per)orms a generati+e recursion, This case2split suggests a cond2e8pression:

66").ic--sort":"!listof"n.m8er#""-/""!listof"n.m8er# 66"to"create"a"+ist"of"n.m8ers"with"the"same"n.m8ers"as 66"a+on"sorted"in"ascending"order !define"!).ic--sort"a+on# ""!cond """"9!empt2A"a+on#"empt2: """"9else"...:##

The answer )or the )irst case is gi+en, For the second case! when )sortCs input is non2 empt2! the algorithm uses the )irst item to partition the rest o) the list into two sublists: a list with all items smaller than the pi+ot item and another one with those larger than the pi+ot item, Since the rest o) the list is o) un.nown si*e! we lea+e the tas. o) partitioning the list to two au8iliar$ )unctions: sma++er-items and +arger-items, The$ process the list and )ilter out those items that are smaller and larger! respecti+el$! than the )irst one, Hence each au8iliar$ )unction accepts two arguments! namel$! a list o) numbers and a number, De+eloping these )unctions is! o) course! an e8ercise in structural recursionE their de)initions are shown in )igure 9<,
66").ic--sort":"!listof"n.m8er#""-/""!listof"n.m8er# 66"to"create"a"+ist"of"n.m8ers"with"the"same"n.m8ers"as 66"a+on"sorted"in"ascending"order 66"ass.me"that"the"n.m8ers"are"a++"distinct" !define"!).ic--sort"a+on# ""!cond """"9!empt2A"a+on#"empt2: """"9else"!append"!).ic--sort"!sma++er-items"a+on"!first"a+on###" """" ""!+ist"!first"a+on##" ""!).ic--sort"!+arger-items"a+on"!first"a+on####:## 66"+arger-items":"!listof"n.m8er#"n.m8er""-/""!listof"n.m8er# 66"to"create"a"+ist"with"a++"those"n.m8ers"on"a+on"" 66"that"are"+arger"than"thresho+d !define"!+arger-items"a+on"thresho+d# ""!cond """"9!empt2A"a+on#"empt2: """"9else"!if"!/"!first"a+on#"thresho+d#" """"""!cons"!first"a+on#"!+arger-items"!rest"a+on#"thresho+d## """"""!+arger-items"!rest"a+on#"thresho+d##:## 66"sma++er-items":"!listof"n.m8er#"n.m8er""-/""!listof"n.m8er# 66"to"create"a"+ist"with"a++"those"n.m8ers"on"a+on"" 66"that"are"sma++er"than"thresho+d !define"!sma++er-items"a+on"thresho+d# ""!cond """"9!empt2A"a+on#"empt2: """"9else"!if"!?"!first"a+on#"thresho+d#" """"""!cons"!first"a+on#"!sma++er-items"!rest"a+on# thresho+d##

/smaller2items /rest alon0 threshold00W00 Figure &)' The ?uic.2sort algorithm

#ach sublist is sorted separatel$! using ).ic--sort, This implies the use o) recursion and! more speci)icall$! the )ollowing two e8pressions:

(, !).ic--sort"!sma++er-items"a+on"!first"a+on###! which sorts the list o) items smaller than the pi+otE and &, !).ic--sort"!+arger-items"a+on"!first"a+on###! which sorts the list o) items larger than the pi+ot, @nce we get the sorted +ersions o) the two lists! we need a )unction that combines the two lists and the pi+ot item, SchemeCs append )unction accomplishes this:
!append"!).ic--sort"!sma++er-items"a+on"!first"a+on### """"""""!+ist"!first"a+on## """"""""!).ic--sort"!+arger-items"a+on"!first"a+on####

Clearl$! all items in list ( are smaller than the pi+ot and the pi+ot is smaller than all items in list &! so the result is a sorted list, Figure 9< contains the )ull )unction, It includes the de)inition o) ).ic--sort! sma++er-items! and +arger-items, "etCs ta.e a loo. at the beginning o) a sample hand e+aluation:
""!).ic--sort"!+ist"11"$"14"7## &"!append"!).ic--sort"!+ist"$"7## ""!+ist"11# """"""""""!).ic--sort"!+ist"14### &"!append"!append"!).ic--sort"!+ist"7## """"""""""!+ist"$# ""!).ic--sort"empt2## ""!+ist"11# """"""""""!).ic--sort"!+ist"14### &"!append"!append"!append"!).ic--sort"empt2# """"""""""!+ist"7# ""!).ic--sort"empt2## """"""""""!+ist"$# ""!).ic--sort"empt2## ""!+ist"11# """"""""""!).ic--sort"!+ist"14### &"!append"!append"!append"empt2 """"""""""!+ist"7# ""empt2# """"""""""!+ist"$# ""empt2# ""!+ist"11# """"""""""!).ic--sort"!+ist"14### &"!append"!append"!+ist"7# """"""""""!+ist"$# ""empt2# ""!+ist"11# """"""""""!).ic--sort"!+ist"14### &"..."

The calculation shows the essential steps o) the sorting process! that is! the partitioning steps! the recursi+e sorting steps! and the concatenation o) the three parts, From this calculation! we can see that ).ic--sort implements the process illustrated in )igure 9;, E ercise 2$<2<2< Complete the abo+e hand2e+aluation,

The hand2e+aluation o) !).ic--sort"!+ist"11"$"14"7## suggests an additional tri+ial case )or ).ic--sort, #+er$ time ).ic--sort consumes a list o) one item! it produces the +er$ same list, A)ter all! the sorted +ersion o) a list o) one item is the list itsel), Modi)$ the de)inition o) ).ic--sort to ta.e ad+antage o) this obser+ation, Hand2e+aluate the same e8ample again, How man$ steps does the e8tended algorithm sa+eH Solution E ercise 2$<2<!< 1hile ).ic--sort ?uic.l$ reduces the si*e o) the problem in man$ cases! it is inappropriatel$ slow )or small problems, Hence people o)ten use ).ic--sort to reduce the si*e o) the problem and switch to a di))erent sort )unction when the list is small enough, De+elop a +ersion o) ).ic--sort that uses sort )rom section (&,& i) the length o) the input is below some threshold, Solution E ercise 2$<2<#< I) the input to ).ic--sort contains the same number se+eral times! the algorithm returns a list that is strictl$ shorter than the input, 1h$H Fi8 the problem so that the output is as long as the input, Solution E ercise 2$<2<$< Ase the fi+ter )unction to de)ine sma++er-items and +argeritems as one2liners, Solution E ercise 2$<2<&< De+elop a +ariant o) ).ic--sort that uses onl$ one comparison )unction! sa$! ?, Its partitioning step di+ides the gi+en list a+on into a list that contains the items o) a+on smaller than !first"a+on# and another one with those that are not smaller, Ase local to combine the )unctions into a single )unction, Then abstract the new +ersion to consume a list and a comparison )unction:
66"genera+-).ic--sort":"!R"R""-/""8oo+#"!+ist"R#""-/""!+ist"R# !define"!genera+-).ic--sort"a-predicate"a-+ist#"...#

Solution

76

For this part o) the boo.! trivia! is a technical term, It will be e8plained in section &9,

Section 2& Designing +lgorithms


At )irst glance! the algorithms mo0e-.nti+-o.t and ).ic--sort ha+e little in common, @ne processes structuresE the other processes lists, @ne creates a new structure )or the generati+e stepE the other splits up a list into three pieces and recurs on two o) them, In short! a comparison o) the two e8amples o) generati+e recursion suggests that the design o) algorithms is an ad hoc acti+it$ and that it is impossible to come up with a general design recipe, A closer loo.! howe+er! suggests a di))erent picture, First! e+en though we spea. o) algorithms as processes that sol+e problems! the$ are still )unctions that consume and produce data, In other words! we still choose data to represent a problem! and we must de)initel$ understand the nature o) our data i) we wish to understand the process, Second! we describe the processes in terms o) data! )or e8ample! DDcreating a new structureCC or DDpartitioning a list o) numbers,CC Third! we alwa$s distinguish between input data )or which it is tri+ial to produce a solution and those )or which it is not, Fourth! the generation o) problems is the .e$ to the design o) algorithms, Although the idea o) how to generate a new problem might be independent o) a data representation! it must certainl$ be implemented )or whate+er )orm o) representation we choose )or our problem, Finall$! once the generated problems ha+e been sol+ed! the solutions must be combined with other +alues, "et us e8amine the si8 general stages o) our structural design recipe in light o) our discussion: Data anal%sis and design' The choice o) a data representation )or a problem o)ten a))ects our thin.ing about the process, Sometimes the description o) a process dictates a particular choice o) representation, @n other occasions! it is possible and worthwhile to e8plore alternati+es, In an$ case! we must anal$*e and de)ine our data collections, Contract, purpose, header' 1e also need a contract! a de)inition header! and a purpose statement, Since the generati+e step has no connection to the structure o) the data de)inition! the purpose statement should not onl$ speci)$ 3hat the )unction does but should also include a comment that e8plains in general terms ho3 it wor.s, Function e amples' In our pre+ious design recipes! the )unction e8amples merel$ speci)ied which output the )unction should produce )or some gi+en input, For algorithms! e8amples should illustrate ho3 the algorithm proceeds )or some gi+en input, This helps us to design! and readers to understand! the algorithm, For )unctions such as mo0e-.nti+-o.t the process is tri+ial and doesnCt need more than a )ew

words, For others! including! ).ic--sort! the process relies on a non2tri+ial idea )or its generati+e step! and its e8planation re?uires a good e8ample such as the one in )igure 9;, Template' @ur discussion suggests a general template )or algorithms:
!define"!generati0e-rec.rsi0e-f.n"pro8+em# ""!cond """"9!tri0ia++2-so+0a8+eA"pro8+em# """""!determine-so+.tion"pro8+em#: """"9else """""!com8ine-so+.tions """""""..."pro8+em"... """""""!generati0e-rec.rsi0e-f.n"!generate-pro8+em-1 pro8+em## """"""" """""""!generati0e-rec.rsi0e-f.n"!generate-pro8+em-n pro8+em###:##

Definition' @) course! this template is onl$ a suggesti+e blueprint! not a de)initi+e shape, #ach )unction in the template is to remind us that we need to thin. about the )ollowing )our ?uestions: (, 1hat is a tri+iall$ sol+able problemH &, 1hat is a corresponding solutionH 5, How do we generate new problems that are more easil$ sol+able than the original problemH Is there one new problem that we generate or are there se+eralH 6, Is the solution o) the gi+en problem the same as the solution o) /one o)0 the new problemsH @r! do we need to combine the solutions to create a solution )or the original problemH And! i) so! do we need an$thing )rom the original problem dataH To de)ine the algorithm! we must e8press the answers to these )our ?uestions in terms o) our chosen data representation, Test' @nce we ha+e a complete )unction! we must also test it, As be)ore! the goal o) testing is to disco+er bugs and to eliminate them, Remember that testing cannot +alidate that the )unction wor.s correctl$ )or all possible inputs, Also remember that it is best to )ormulate tests as boolean2+alued e8pressions that automaticall$ compare the e8pected +alue with the computed +alue /see section (;,<0, E ercise 2&<.<(< Formulate in)ormal answers to the )our .e$ ?uestions )or the problem o) modeling a ballCs mo+ement across a can+as until it is out o) bounds, Solution

E ercise 2&<.<)< Formulate in)ormal answers to the )our .e$ ?uestions )or the ).ic-sort problem, How man$ instances o) generate-pro8+em are thereH Solution

"-#$ Termination
An)ortunatel$! the standard recipe is not good enough )or the design o) algorithms, Ap to now! a )unction has alwa$s produced an output )or an$ legitimate input, That is! the e+aluation has alwa$s stopped, A)ter all! b$ the nature o) our recipe! each natural recursion consumes an immediate piece o) the input! not the input itsel), Because data is constructed in a hierarchical manner! this means that the input shrin.s at e+er$ stage, Hence the )unction sooner or later consumes an atomic piece o) data and stops, 1ith )unctions based on generati+e recursion! this is no longer true, The internal recursions donCt consume an immediate component o) the input but some new piece o) data! which is generated )rom the input, As e8ercise &7,(,( shows! this step ma$ produce the input o+er and o+er again and thus pre+ent the e+aluation )rom e+er producing a result, 1e sa$ that the program "@@PS or is in an I-FI-IT# "@@P, In addition! e+en the slightest mista.e in translating the process description into a )unction de)inition ma$ cause an in)inite loop, The problem is most easil$ understood with an e8ample, Consider the )ollowing de)inition o) sma++er-items! one o) the two DDproblem generatorsCC )or ).ic--sort:
66"sma++er-items":"!listof"n.m8er#"n.m8er""-/""!listof"n.m8er# 66"to"create"a"+ist"with"a++"those"n.m8ers"on"a+on"" 66"that"are"sma++er"than"or"e).a+"to"thresho+d !define"!sma++er-items"a+on"thresho+d# ""!cond """"9!empt2A"a+on#"empt2: """"9else"!if"!?&"!first"a+on#"thresho+d#" """"""!cons"!first"a+on#"!sma++er-items"!rest"a+on#"thresho+d## """"""!sma++er-items"!rest"a+on#"thresho+d##:##

Instead o) ? it emplo$s ?& to compare numbers, As a result! this )unction produces !+ist"5# when applied to !+ist"5# and 5, 1orse! i) the ).ic--sort )unction )rom )igure 9< is combined with this new +ersion o) sma++er-items! it doesnCt produce an$ output )or !+ist"5#:
""!).ic--sort"!+ist"5## &"!append"!).ic--sort"!sma++er-items"5"!+ist"5### """"""""""!+ist"5# """"""""""!).ic--sort"!+arger-items"5"!+ist"5#### &"!append"! """ ).ic--sort"! " ""+ist "" "" 5"" ## " """"""""""!+ist"5# """"""""""!).ic--sort"!+arger-items"5"!+ist"5####

The )irst recursi+e use demands that ).ic--sort sol+e the problem o) sorting !+ist 5# 22 but that is the e8act problem that we started with, Since this is a circular

e+aluation! !).ic--sort"!+ist"5## ne+er produces a result, More generall$! there is no guarantee that the si*e o) the input )or a recursi+e call brings us closer to a solution than the original input, Phase =oal #8amples to characteri*e the input2 output relationship and the computational process +ia e8amples Bod$ to de)ine an algorithm Acti+it$ create and show e8amples o) tri+iall$ sol+able problems create and show e8amples that re?uire recursi+e processing illustrate how to wor. through the e8amples

)ormulate tests )or tri+iall$ sol+able problems )ormulate answers )or the tri+ial cases determine how to generate new problems )rom the gi+en problem! possibl$ using au8iliar$ )unctions determine how to combine the solutions o) these problems into a solution )or the gi+en problem

Termin,

to argue that the show that the inputs to the recursi+e applications algorithm terminates are smaller than the gi+en input )or all possible inputs

Figure &-' Designing algorithms The lesson )rom this e8ample is that the design o) algorithms re?uires one more step in our design recipe: a T#RMI-ATI@- AR=AM#-T! which e8plains wh$ the process produces an output )or e+er$ input and how the )unction implements this ideaE or a warning! which e8plains when the process ma$ not terminate, For ).ic--sort! the argument might loo. li.e this: At each step! ).ic--sort partitions the list into two sublists using sma++er-items and +arger-items, #ach )unction produces a list that is smaller than the input /the second argument0! e+en i) the threshold /the )irst argument0 is an item on the list, Hence each recursi+e application o) ).ic--sort consumes a strictl$ shorter list than the gi+en one, #+entuall$! ).ic--sort recei+es and returns empt2, 1ithout such an argument an algorithm must be considered incomplete, A good termination argument ma$ on occasion also re+eal additional termination cases, For e8ample! !sma++er-items"J"!+ist"J## and !+arger-items"J"!+ist"J## alwa$s produce empt2 )or an$ J, There)ore we .now that ).ic--sortCs answer )or !+ist"J# is !+ist"J#,77 To add this .nowledge to ).ic--sort! we simpl$ add a cond2 clause:
!define"!).ic--sort"a+on#

""!cond """"9!empt2A"a+on#"empt2: """"9!empt2A"!rest"a+on##"a+on: """"9else"!append" """"!).ic--sort"!sma++er-items"a+on"!first"a+on###" """"!+ist"!first"a+on##" """"!).ic--sort"!+arger-items"a+on"!first"a+on####:##

The condition !empt2A"!rest"a+on## is one wa$ to as. whether a+on contains one item, Figure 9> summari*es the suggestions on the design o) algorithms, The dots indicate that the design o) an algorithm re?uires a new step: the termination argument, Read the table in conFunction with those o) the preceding chapters, E ercise 2&<1<1< De)ine the )unction ta8.+ate-di0! which accepts a number n and tabulates the list o) all o) its di+isors! starting with 1 and ending in n, A number d is a di+isior o) a number n i) the remainder o) di+iding n b$ d is %! that is! !&"!remainder n"d#"%# is true, The smallest di+isior o) an$ number is 1E the largest one is the number itsel), Solution E ercise 2&<1<2< De+elop the )unction merge-sort! which sorts a list o) numbers in ascending order! using the )ollowing two au8iliar$ )unctions: (, The )irst one! ma-e-sing+es! constructs a list o) one2item lists )rom the gi+en list o) numbers, For e8ample!
2. !e).a+A"!ma-e-sing+es"!+ist"2"5","3## 3. """"""""!+ist"!+ist"2#"!+ist"5#"!+ist",#"!+ist"3###

6, The second one! merge-a++-neigh8ors! merges pairs o) neighboring lists, More speci)icall$! it consumes a list o) lists /o) numbers0 and merges neighbors, For e8ample!
5. !e).a+A"!merge-a++-neigh8ors"!+ist"!+ist"2#"!+ist"5#"!+ist ,#"!+ist"3### . """"""""!+ist"!+ist"2"5#"!+ist"3",### 7. $. !e).a+A"!merge-a++-neigh8ors"!+ist"!+ist"2"5#"!+ist"3",### ,. """"""""!+ist"!+ist"2"3"5",###

In general! this )unction $ields a list that is appro8imatel$ hal) as long as the input, 1h$ is the output not alwa$s hal) as long as the inputH Ma.e sure to de+elop the )unctions independentl$,

The )unction merge-sort )irst uses ma-e-sing+es to create a list o) single listsE then it relies on merge-a++-neigh8ors to shorten the list o) lists until it contains a single list, The latter is the result, Solution

"-#" Structural versus 5enerative Recursion


The template )or algorithms is so general that it e+en co+ers )unctions based on structural recursion, Consider the +ersion with one termination clause and one generation step:
!define"!generati0e-rec.rsi0e-f.n"pro8+em# ""!cond """"9!tri0ia++2-so+0a8+eA"pro8+em# """""!determine-so+.tion"pro8+em#: """"9else """"""!com8ine-so+.tions pro8+em !generati0e-rec.rsi0e-f.n"!generate-pro8+em"pro8+em###:##

I) we replace tri0ia++2-so+0a8+eA with empt2A and generate-pro8+em with rest! the outline is a template )or a list2processing )unction:
!define"!generati0e-rec.rsi0e-f.n"pro8+em# ""!cond """"9!empt2A"pro8+em#"!determine-so+.tion"pro8+em#: """"9else """"""!com8ine-so+.tions pro8+em !generati0e-rec.rsi0e-f.n"!rest"pro8+em###:##

E ercise 2&<2<1< De)ine determine-so+.tion and com8ine-so+.tions so that the )unction generati0e-rec.rsi0e-f.n computes the length o) its input, Solution This discussion raises the ?uestion o) whether there is a di))erence between between )unctions based on structural recursion and those based on generati+e recursion, The answer is DDit depends,CC @) course! we could sa$ that all )unctions using structural recursion are Fust special cases o) generati+e recursion, This DDe+er$thing is e?ualCC attitude! howe+er! is o) no help i) we wish to understand the process o) designing )unctions, It con)uses two classes o) )unctions that are designed with di))erent approaches and that ha+e di))erent conse?uences, @ne relies on a s$stematic data anal$sis and not much moreE the other re?uires a deep! o)ten mathematical! insight into the problem2sol+ing process itsel), @ne leads programmers to naturall$ terminating )unctionsE the other re?uires a termination argument, A simple inspection o) a )unctionCs de)inition ?uic.l$ shows whether a )unction uses structural or generati+e recursion, All sel)2applications o) a structurall$ recursi+e )unction alwa$s recei+e an immediate component o) the current input )or )urther processing, For e8ample! )or a constructed list! the immediate components are the first item and the rest o) the list, Hence! i) a )unction consumes a plain list and its recursi+e use does not consume the rest o) the list! its de)inition is not structural but

generati+e, @r! put positi+el$! properl$ recursi+e algorithms consume newl$ generated input! which ma$ or ma$ not contain components o) the input, In an$ case! the new piece o) data represents a di))erent problem than the gi+en one! but still a problem o) the same general class o) problems,

"-#( /aking Choices


A user cannot distinguish sort and ).ic--sort, Both consume a list o) numbersE both produce a list that consists o) the same numbers arranged in ascending order, To an obser+er! the )unctions are completel$ e?ui+alent,79 This raises the ?uestion o) which o) the two a programmer should pro+ide, More generall$! i) we can de+elop a )unction using structural recursion and an e?ui+alent one using generati+e recursion! what should we doH To understand this choice better! letCs discuss another classical e8ample o) generati+e recursion )rom mathematics: the problem o) )inding the greatest common di+isor o) two positi+e natural numbers,7; All such numbers ha+e at least one di+isor in common: (, @n occasion! this is also the onl$ common di+isor, For e8ample! & and 5 ha+e onl$ ( as common di+isor because & and 5! respecti+el$! are the onl$ other di+isors, Then again! 9 and &7 are both numbers with se+eral di+isors: (, 9 is e+enl$ di+isible b$ (! &! 5! and 9E &, &7 is e+enl$ di+isible b$ (! 7! and &7, Still! the greatest common di+isior o) &7 and 9 is (, In contrast! (< and &6 ha+e man$ common di+isors: (, (< is e+enl$ di+isible b$ (! &! 5! 9! >! and (<E &, &6 is e+enl$ di+isible b$ (! &! 5! 6! 9! <! (&! and &6, The greatest common di+isor is 9, Following the design recipe! we start with a contract! a purpose statement! and a header:
66"gcd":"N9/&"1:"N9/&"1:""-/""N 66"to"find"the"greatest"common"di0isior"of"n"and"m !define"!gcd"n"m#" ""...#

The contract speci)ies the precise inputs: natural numbers that are greater or e?ual to 1 /not %0, -ow we need to ma.e a decision whether we want to pursue a design based on structural or on generati+e recursion, Since the answer is b$ no means ob+ious! we de+elop both, For the structural +ersion! we must consider which input the )unction should process: n! m! or both, A momentCs consideration suggests that what we reall$ need is a )unction that starts with the smaller o) the two and outputs the )irst number smaller or e?ual to this input that e+enl$ di+ides both n and m,
66"gcd-str.ct.ra+":"N9/&"1:"N9/&"1:""-/""N 66"to"find"the"greatest"common"di0isior"of"n"and"m 66"structural"rec.rsion".sing"data"definition"of"N9/&"1: !define"!gcd-str.ct.ra+"n"m# ""!local"!!define"!first-di0isior-?&"i# """"!cond """"""9!&"i"1#"1: """"""9else"!cond """"""9!and"!&"!remainder"n"i#"%#" """"!&"!remainder"m"i#"%## """""""i: """"""9else"!first-di0isior-?&"!-"i"1##:#:###

/)irst2di+isior2UO /min m n0000 Figure (.' Finding the greatest common di+isor +ia structural recursion 1e use local to de)ine an appropriate au8iliar$ )unction: see )igure ;', The conditions DDe+enl$ di+isibleCC ha+e been encoded as !&"!remainder"n"i#"%# and !&"!remainder m"i#"%#, The two ensure that i di+ides n and m without a remainder, Testing gcdstr.ct.ra+ with the e8amples shows that it )inds the e8pected answers, Although the design o) gcd-str.ct.ra+ is rather straight)orward! it is also nai+e, It simpl$ tests )or e+er$ number whether it di+ides both n and m e+enl$ and returns the )irst such number, For small natural numbers! this process wor.s Fust )ine, Consider the )ollowing e8ample! howe+er:
!gcd-str.ct.ra+"1%1135$53"45%14 4%#

The result is 177 and to get there gcd-str.ct.ra+ had to compare ('((579;9! that is! ('((57<75 - (;;! numbers, This is a large e))ort and e+en reasonabl$ )ast computers spend se+eral minutes on this tas., E ercise 2&<!<1< #nter the de)inition o) gcd-str.ct.ra+ into the Definitions window and e+aluate !time"!gcd-str.ct.ra+"1%1135$53"45%14 4%## in the Interactions window, >int' A)ter testing gcd-str.ct.ra+ conduct the per)ormance tests in the Full Scheme language /without debugging0! which e+aluates e8pressions )aster than the lower

language le+els but with less protection, Add !re).ire-+i8rar2"1core.ss1# to the top o) the Definitions window, Ha+e some reading hand$L Solution Since mathematicians recogni*ed the ine))icienc$ o) the DDstructural algorithmCC a long time ago! the$ studied the problem o) )inding di+isiors in more depth, The essential insight is that )or two natural numbers +arger and sma++er! their greatest common di+isor is e?ual to the greatest common di+isior o) sma++er and the remainder o) +arger di+ided into sma++er, Here is how we can put this insight into e?uational )orm:
""!gcd"+arger"sma++er#" &"!gcd"sma++er"!remainder"+arger"sma++er##

Since !remainder"+arger"sma++er# is smaller than both +arger and sma++er! the right2hand side use o) gcd consumes sma++er )irst, Here is how this insight applies to our small e8ample: (, The gi+en numbers are 1$ and 24, &, According to the mathematiciansC insight! the$ ha+e the same greatest common di+isor as 1$ and , 5, And these two ha+e the same greatest common di+isor as and %,

And here we seem stuc. because % is nothing e8pected, But! % can be e+enl$ di+ided b$ e+er$ number! so we ha+e )ound our answer: , 1or.ing through the e8ample not onl$ e8plains the idea but also suggests how to disco+er the case with a tri+ial solution, 1hen the smaller o) the two numbers is %! the result is the larger number, Putting e+er$thing together! we get the )ollowing de)inition:
66"gcd-generati0e":"N9/&"1:"N9/&1:""-/""N 66"to"find"the"greatest"common"di0isior"of"n"and"m 66"generative"rec.rsion:"!gcd"n"m#"&"!gcd"n"!remainder"m"n##"if !?&"m"n# !define"!gcd-generati0e"n"m# ""!local"!!define"!c+e0er-gcd"+arger"sma++er# """"!cond """"""9!&"sma++er"%#"+arger: """"""9else"!c+e0er-gcd"sma++er"!remainder"+arger sma++er##:### """"!c+e0er-gcd"!ma*"m"n#"!min"m"n####

The local de)inition introduces the wor.horse o) the )unction: c+e0er-gcd! a )unction based on generati+e recursion, Its )irst line disco+ers the tri+iall$ sol+able case b$ comparing sma++er to % and produces the matching solution, The generati+e step uses

as the new )irst argument and !remainder"+arger"sma++er# as the new second argument to c+e0er-gcd! e8ploiting the abo+e e?uation,
sma++er

I) we now use gcd-generati0e with our comple8 e8ample )rom abo+e:


!gcd-generati0e"1%1135$53"45%14 4%#

we see that the response is nearl$ instantaneous, A hand2e+aluation shows that c+e0ergcd recurs onl$ nine times be)ore it produces the solution: 177, In short! generati+e recursion has helped )ind us a much )aster solution to our problem, E ercise 2&<!<2< Formulate in)ormal answers to the )our .e$ ?uestions )or gcdgenerati0e, Solution E ercise 2&<!<!< De)ine gcd-generati0e and e+aluate
!time"!gcd-generati0e"1%1135$53"45%14 4%##

in the Interactions window, #+aluate !c+e0er-gcd"1%1135$53"45%14 4%# b$ hand, Show onl$ those lines that introduce a new recursi+e call to c+e0er-gcd, Solution E ercise 2&<!<#< Formulate a termination argument )or gcd-generati0e, Solution Considering the abo+e e8ample! it is tempting to de+elop )unctions using generati+e recursion, A)ter all! the$ produce answers )asterL This Fudgment is too rash )or three reasons, First! e+en a well2designed algorithm isnCt alwa$s )aster than an e?ui+alent structurall$ recursi+e )unction, For e8ample! ).ic--sort wins onl$ )or large listsE )or small ones! the standard sort )unction is )aster, 1orse! a badl$ designed algorithm can wrea. ha+oc on the per)ormance o) a program, Second! it is t$picall$ easier to design a )unction using the recipe )or structural recursion, Con+ersel$! designing an algorithm re?uires an idea o) how to generate new! smaller problems! a step that o)ten re?uires deep mathematical insight, Finall$! people who read )unctions can easil$ understand structurall$ recursi+e )unctions! e+en without much documentation, To understand an algorithm! the generati+e step must be well e8plained! and e+en with a good e8planation! it ma$ still be di))icult to grasp the idea, #8perience shows that most )unctions in a program emplo$ structural recursionE onl$ a )ew e8ploit generati+e recursion, 1hen we encounter a situation where a design could use either the recipe )or structural or generati+e recursion! the best approach is o)ten to start with a structural +ersion, I) it turns out to be too slow! the alternati+e design using

generati+e recursion should be e8plored, I) it is chosen! it is important to document the problem generation with good e8amples and to gi+e a good termination argument, E ercise 2&<!<$< #+aluate
!).ic--sort"!+ist"1%" "$","14"12"3"11"14"1 "2##

b$ hand, Show onl$ those lines that introduce a new recursi+e call to ).ic--sort, How man$ recursi+e applications o) ).ic--sort are re?uiredH How man$ recursi+e applications o) appendH Suggest a general rule )or a list o) length J, #+aluate
!).ic--sort"!+ist"1"2"3"4"5" "7"$","1%"11"12"13"14##

b$ hand, How man$ recursi+e applications o) ).ic--sort are re?uiredH How man$ recursi+e applications o) appendH Does this contradict the )irst part o) the e8erciseH Solution E ercise 2&<!<&< Add sort and ).ic--sort to the Definitionswindow, Test the )unctions and then e8plore how )ast each wor.s on +arious lists, The e8periment should con)irm the claim that the plain sort )unction wins /in man$ comparisons0 o+er ).ic-sort )or short lists and +ice +ersa, Determine the cross2o+er point, Then build a sort).ic--sort )unction that beha+es li.e ).ic--sort )or large lists and switches o+er to the plain sort )unction )or lists below the cross2o+er point, >ints' /(0 Ase the ideas o) e8ercise &9,5,7 to create test cases, /&0 De+elop createtests! a )unction that creates large test cases randoml$, Then e+aluate
!define"test-case"!create-tests"1%%%%## !co++ect-gar8age# !time"!sort"test-case## !co++ect-gar8age# !time"!).ic--sort"test-case##

The uses o) co++ect-gar8age helps DrScheme deal with large lists,

Solution

@) course! we could ha+e Fust argued that the sorted +ersion o) a one2item list is the list! which is the basis o) e8ercise &7,&,&,
77

The concept o) obser+abl$ e?ui+alent )unctions and e8pressions pla$s a central role in the stud$ o) programming languages and their meaning,
79

7;

The material on the greatest common di+isor was suggested b$ John Stone,

Section 2( "ariations on a Theme


As we ha+e seen in the pre+ious two sections! the design o) an algorithm usuall$ starts with an in)ormal description o) a mechanism, The .ernel o) this description is about how to create a problem that is more easil$ sol+able than the gi+en one and whose solution contributes to the solution o) the gi+en problem, Coming up with such ideas re?uires stud$ing man$ di))erent e8amples, This section presents se+eral illustrati+e e8amples o) the design recipe )or generati+e recursion, Some are directl$ drawn )rom mathematics! which is the source o) man$ ideas )or general problem2sol+ing processesE others come )rom computational conte8ts, The important point is to understand the generati+e ideas behind the algorithms so that the$ can be applied in other conte8ts, The )irst e8ample is a graphical illustration o) our principle: the Sierpins.i triangle, The second one concerns DDparsing!CC that is! the process o) dissecting se?uences o) s$mbols, The third one e8plains the di+ide2and2con?uer principle with a simple mathematical e8ample: )inding the root o) a )unction, Man$ mathematical processes e8ploit this idea! and it is important to understand the idea )or applied mathematics, In the )ourth section! we discuss $et another wa$ o) )inding a root! this time based on -ewtonCs method, The last section is an e8tended e8erciseE it introduces =aussian elimination! the )irst step in sol+ing a s$stem o) e?uations,

"0#$ +ractals
Fractals pla$ an important role in computational geometr$, Fla.e /The 2omp tationa! 1ea ty of /at re! The MIT Press! (>><0 sa$s that DDgeometr$ can be e8tended to account )or obFects with a )ractional dimension, Such obFects! .nown as fracta!s! come +er$ close to capturing the richness and +ariet$ o) )orms )ound in nature, Fractals possess structural sel)2similarit$ on multiple ... scales! meaning that a piece o) a )ractal will o)ten loo. li.e the whole,CC

Figure (1' The Sierpins.i triangle Figure ;( displa$s an e8ample o) a )ractal! widel$ .nown as the Sierpins.i triangle, The basic shape is an /e?uilateral0 triangle! as shown in the le)t2most picture, In the right2 most e8ample we see that the triangle is repated man$ times and in man$ si*es inside o) the outermost triangle, The picture in the middle is a snapshot )rom the middle o) the drawing process, The middle picture also suggests what the generati+e step might loo. li.e, =i+en the three endpoints o) a triangle! we draw the triangle and then compute the midpoint o) each side, I) we were to connect these midpoints to each other! we would di+ide the gi+en triangle into )our triangles, The middle picture illustrates this idea, The Sierpins.i triangle is the result o) repeating the process )or the three outer triangles and lea+ing the inner one alone, A )unction that draws this nest o) triangles must mirror this process, Its input data must represent the triangle that we start with, The process stops when the input data speci)ies a triangle that is too small to be drawn, Since all o) our drawing )unctions produce tr.e when the$ are done! we agree that our Sierpins.i )unction should also produce tr.e, I) the gi+en triangle is still large enough! the )unction must draw the triangle and possibl$ some nested ones, The tric. is to translate the partitioning o) the triangle into Scheme, "et us summari*e our discussion with a s.eletal Scheme de)inition:
66"sierpins-i":"posn"posn"posn""-/""tr.e 66"to"draw"a"Cierpins-i"triang+e"down"at"a<"8<"and"c<" 66"ass.ming"it"is"+arge"eno.gh !define"!sierpins-i"a"8"c# ""!cond """"9!too-sma++A"a"8"c#"tr.e: """"9else"..."!draw-triang+e"a"8"c#"...":##

The )unction consumes three posn structures and returns tr.e when it is done, The cond2e8pression re)lects the general outline o) an algorithm, It is our tas. to de)ine toosma++A! the )unction that determines whether the problem is tri+iall$ sol+able! and

draw-triang+e,

In addition! we must still add a Scheme e8pression that )ormulates the partitioning o) the triangle, The partitioning step re?uires the )unction to determine the three mid2points between the three end2points, "et us call these new mid2points a-8! 8-c! and c-a, Together with the gi+en endpoints! a! 8! and c! the$ determine )our triangles: a,"a-8,"c-aE 8,"a-8, 8-cE c,"c-a,"8-cE a-8,"8-c,"c-a, Thus! i) we wanted to create the Sierpins.i triangle )or! sa$! the )irst listed triangle! we would use !sierpins-i"a"a-8"c-a#, Since each midpoint is used twice! we use a local2e8pression to translate the generati+e step into Scheme, The local2e8pression introduces the three new midpoints, Its bod$ contains three recursi+e applications o) sierpins-i and the draw-triang+e application mentioned earlier, To combine the solutions o) the three problems! we use an and2e8pression! which ensures that all three recursions must succeed, Figure ;& collects all the rele+ant de)initions! including two small )unctions based on domain .nowledge )rom geometr$,
66"sierpins-i":"posn"posn"posn""-/""tr.e 66"to"draw"a"Cierpins-i"triang+e"down"at"a<"8<"and"c< 66"ass.ming"it"is"+arge"eno.gh !define"!sierpins-i"a"8"c# ""!cond """"9!too-sma++A"a"8"c#"tr.e: """"9else" """"""!local"!!define"a-8"!mid-point"a"8## """"""!define"8-c"!mid-point"8"c## """"""!define"c-a"!mid-point"a"c### !and ""!draw-triang+e"a"8"c# """" ""!sierpins-i"a"a-8"c-a# ""!sierpins-i"8"a-8"8-c# ""!sierpins-i"c"c-a"8-c###:## 66"mid-point":"posn"posn""-/""posn 66"to"comp.te"the"mid-point"8etween"a-posn"and"8-posn !define"!mid-point"a-posn"8-posn# ""!ma-e-posn """"!mid"!posn-*"a-posn#"!posn-*"8-posn## """"!mid"!posn-2"a-posn#"!posn-2"8-posn#### 66"mid":"n.m8er"n.m8er""-/""n.m8er 66"to"comp.te"the"a0erage"of"*"and"2 !define"!mid"*"2#

/K /I 8 $0 &00 Figure (2' The Sierpins.i algorithm Since sierpins-i is based on generati+e recursion! collecting the code and testing it is not the last step, 1e must also consider wh$ the algorithm terminates )or an$ gi+en legal input, The inputs o) sierpins-i are three positions, The algorithm terminates i) the corresponding triangle is too small, But! each recursi+e step subdi+ides the triangle so that the sum o) its sides is onl$ hal) o) the gi+en triangle, Hence the si*e o) the triangles indeed decreases and sierpins-i is bound to produce tr.e,

E ercise 2(<1<1< De+elop the )unctions (, EE draw-triang+e":"posn"posn"posn""-/""tr.e &, EE too-sma++A":"posn"posn"posn""-/""8oo+ to complete the de)initions in )igure ;&, Ase the teachpac. draw.ss to test the code, For a )irst test o) the complete )unction! use the )ollowing de)initions:
!define"'"!ma-e-posn"2%%"%## !define"("!ma-e-posn"27"3%%## !define"7"!ma-e-posn"373"3%%#

Create a can+as with !start"4%%"4%%#, #8periment with other end points and can+as dimensions, Solution E ercise 2(<1<2< The process o) drawing a Sierpins.i triangle usuall$ starts )rom an e?uilateral shape, To compute the endpoints o) an e?uilateral Sierpins.i triangle! we can pic. a large circle and three points on the circle that are (&' degrees apart, For e8ample! the$ could be at '! (&'! &6':
!define"75J;5Q"!ma-e-posn"2%%"2%%## !define"Q'DIPC"2%%# 66"cicrc+-pt":"n.m8er""-/""posn 66"to"comp.te"a"position"on"the"circ+e"with"75J;5Q 66"and"Q'DIPC"as"defined"a8o0e" !define"!circ+e-pt"factor#"...# !define"'"!circ+e-pt"12%/3 %## !define"("!circ+e-pt"24%/3 %## !define"7"!circ+e-pt"3 %/3 %##

De+elop the )unction circ+e-pt, >ints' Recall that DrSchemeCs sin and cos compute the sine and cosine in terms o) radians! not degrees, Also .eep in mind that on2screen positions grow downwards not upwards, Solution E ercise 2(<1<!< Rewrite the )unction in )igure ;& to use structures )or the representation o) triangles, Then appl$ the new )unction to a list o) triangles and obser+e the e))ect, Solution

E ercise 2(<1<#< Ta.e a loo. at the )ollowing two pictures:

The le)t one is the basic step )or the generation o) the DDSa+annahCC tree on the right, It is analogous to the middle picture on page 56, De+elop a )unction that draws trees li.e the one in the right picture, >int' Thin. o) the problem as drawing a straight line! gi+en its starting point and an angle in! sa$! radians, Then! the generati+e step di+ides a single straight line into three pieces and uses the two intermediate points as new starting points )or straight lines, The angle changes at each step in a regular manner, Solution E ercise 2(<1<$< In mathematics and computer graphics! people must o)ten connect some gi+en points with a smooth cur+e, @ne popular method )or this purpose is due to Be*ier,7< Here is a se?uence o) pictures that illustrate the idea:

For simplicit$! we start with three points: p1! p2! and p3, The goal is to draw a smooth cur+e )rom p1 to p3! +iewed )rom p2, The original triangle is shown on the le)tE the desired cur+e appears on the right,

To draw the cur+e )rom a gi+en triangle! we proceed as )ollows, I) the triangle is small enough! draw it, It appears as a large point, I) not! generate two smaller triangles as illustrated in the center picture, The outermost points! p1 and p3! remain the respecti+e outermost points, The replacements )or the point in the middle are r2 and )2! which are the midpoints between p1 and p2 and between p2 and p3! respecti+el$, The midpoint between r2 and )2 /mar.ed with 0 is the new le)t2most and right2most endpoint! respecti+el$! )or the two new triangles, To test the )unction! use the teachpac. draw.ss, Here is some good test data:
!define"p1"!ma-e-posn"5%"5%## !define"p2"!ma-e-posn"15%"15%## !define"p3"!ma-e-posn"25%"1%%##

Ase !start"3%%"2%%# to create the can+as, #8periment with other positions, Solution

"0#" +rom +iles to Lines2 from Lists to Lists of Lists


In section (9! we discussed the organi*ation o) computer )iles! which is one wa$ to e?uip a computer with permanent memor$, 1e did not discuss the nature o) )iles per se, Roughl$ put! we can thin. o) a fi!e as a list o) s$mbols: A fi!e is either (, empt2! or &, !cons"s"f# where s is a s$mbol and f is a )ile, A )ull$ )aith)ul representation o) )iles should include onl$ s$mbols that correspond to characters! but )or our purposes we ma$ ignore this distinction, Following a tradition that predates computers!7> one s$mbol is almost alwa$s treated di))erentl$: 'JL, The s$mbol stands )or ne-!ine and separates two lines )rom each other, That is! 'JL indicates the end o) one line and the beginning o) another, In most cases! it is there)ore better to thin. o) )iles as data with more structure, In particular! a )ile could be represented as a list o) lines! where each line is a list o) s$mbols, For e8ample! the )ile
!+ist"'how"'are"'2o."'JL """"""'doing"'A"'JL """"""'an2"'progress"'A#

should be processed as a list o) three lines:

!+ist"!+ist"'how"'are"'2o.# """"""!+ist"'doing"'A# """"""!+ist"'an2"'progress"'A##

Similarl$! the )ile


!+ist"'a"'8"'c"'JL """"""'d"'e"'JL """"""'f"'g"'h"'JL#

is also represented as a list o) three lines! because! b$ con+ention! an empt$ line at the end is ignored:
!+ist"!+ist"'a"'8"'c# """"""!+ist"'d"'e# """"""!+ist"'f"'g"'h##

E ercise 2(<2<1< Determine what the list2o)2lines representation )or empt2! !+ist 'JL#! and !+ist"'JL"'JL# should be, 1h$ are these e8amples important test casesH

>int' eep in mind that an empt$ line at the end is ignored, Here are the contract! purpose statement! and header:

Solution

66"file-/list!of!lines":"fi+e""-/""!listof"!listof"s2m8o+s## 66"to"con0ert"a"fi+e"into"a"+ist"of"+ines" !define"!file-/list!of!lines"afi+e#"...#

Describing the process o) separating a )ile into a list o) lines is eas$, The problem is tri+iall$ sol+able i) the )ile is empt2E in that case! the )ile doesnCt contain a line, @therwise! the )ile contains at least one s$mbol and thus at least one line, This line must be separated )rom the rest o) the )ile! and then the rest o) the )ile must be translated into a list o) lines, "et us s.etch this process description in Scheme:
!define"!file-/list!of!lines"afi+e# ""!cond """"9!empt2A"afi+e#"...: """"9else """"""..."!first-+ine"afi+e#"... """"""..."!file-/list!of!lines"!remo0e-first-+ine"afi+e##"...:##

Because the separation o) the )irst line )rom the rest o) the )ile re?uires a scan o) an arbitraril$ long list o) s$mbols! we add two au8iliar$ )unctions to our wish list: first+ine! which collects all s$mbols up to! but e8cluding! the )irst occurrence o) 'JL or the end o) the listE and remo0e-first-+ine! which remo+es all those s$mbols and produces the remainder o) afi+e,

66"file-/list!of!lines":"fi+e""-/""!listof"!listof"s2m8o+## 66"to"con0ert"a"fi+e"into"a"+ist"of"+ines" !define"!file-/list!of!lines"afi+e# ""!cond """"9!empt2A"afi+e#"empt2: """"9else """"""!cons"!first-+ine"afi+e# """"!file-/list!of!lines"!remo0e-first-+ine"afi+e###:## 66"first-+ine":"fi+e""-/""!listof"s2m8o+# 66"to"comp.te"the"prefi*"of"afi+e".p"to"the"first"occ.rrence"of J5OLIJ5 !define"!first-+ine"afi+e# ""!cond """"9!empt2A"afi+e#"empt2: """"9else"!cond """"9!s2m8o+&A"!first"afi+e#"J5OLIJ5#"empt2: """"9else"!cons"!first"afi+e#"!first-+ine"!rest"afi+e###:#:## 66"remo0e-first-+ine":"fi+e""-/""!listof"s2m8o+# 66"to"comp.te"the"s.ffi*"of"afi+e"8ehind"the"first"occ.rrence"of J5OLIJ5 !define"!remo0e-first-+ine"afi+e# ""!cond """"9!empt2A"afi+e#"empt2: """"9else"!cond """"9!s2m8o+&A"!first"afi+e#"J5OLIJ5#"!rest"afi+e#: """"9else"!remo0e-first-+ine"!rest"afi+e##:#:##

/define -#1"I-# =-"0 Figure (!' Translating a )ile into a list o) lines From here! we can )ill the gaps easil$, In file-/list!of!lines! the answer in the )irst clause must be empt2 because an empt$ )ile does not contain an$ lines, The answer in the second clause must cons the +alue o) !first-+ine"afi+e# onto the +alue !file/list!of!lines"!remo0e-first-+ine"afi+e##! because the )irst e8pression computes the )irst line and the second one computes the rest o) the lines, Finall$! the au8iliar$ )unctions process their inputs in a structurall$ recursi+e mannerE their de+elopment is a straight)orward e8ercise, Figure ;5 collects the three )unction de)initions and a +ariable de)inition )or J5OLIJ5, "et us ta.e a loo. at the process o) turning the )irst )ile )rom abo+e into a list o) lines:
""!file-/list!of!lines"!+ist"'a"'8"'c"'JL"'d"'e"'JL"'f"'g"'h"'JL## &"!cons"!+ist"'a"'8"'c#"!file-/list!of!lines"!+ist"'d"'e"'JL"'f"'g 'h"'JL### &"!cons"!+ist"'a"'8"'c# """"""""!cons"!+ist"'d"'e# """"""!file-/list!of!lines"!+ist"'f"'g"'h"'JL#### &"!cons"!+ist"'a"'8"'c# """"""""!cons"!+ist"'d"'e# """"""!cons"!+ist"'f"'g"'h# """"!file-/list!of!lines"empt2####

&"!cons"!+ist"'a"'8"'c# """"""""!cons"!+ist"'d"'e# """"""!cons"!+ist"'f"'g"'h# """"empt2### &"!+ist"!+ist"'a"'8"'c# """"""""!+ist"'d"'e# !+ist"'f"'g"'h##

From this e+aluation we can easil$ tell that the argument o) the recursi+e application o) file-/list!of!lines is almost ne+er the rest o) the gi+en )ile, That is! it is basicall$ ne+er an immediate component o) the gi+en )ile but alwa$s a proper su))i8, The onl$ e8ception occurs when 'JL occurs twice in a row, Finall$! the e+aluation and the de)inition o) file-/list!of!lines show that its generati+e recursion is simple, #+er$ recursi+e application consumes a list that is shorter than the gi+en one, Hence the recursi+e process e+entuall$ stops because the )unction consumes empt2, E ercise 2(<2<2< @rgani*e the program in )igure ;5 using local, Abstract the )unctions first-+ine and remo0e-first-+ine, Then organi*e the resulting program using a local again, Solution E ercise 2(<2<!< Design file-/list!of!chec+s, The )unction consumes a )ile o) numbers and outputs a list o) restaurant records, A fi!e of n mbers is either (, empt2! or &, !cons"J"># where J is a number and > is a )ile! or 5, !cons"'JL">#! where > is a )ile, The output o) file-/list!of!chec+s is a list o) restaurant structures with two )ields:
!define-struct"rr"!ta8+e"costs##

The$ are: a table number and a list o) amounts charged to that table, #8ample:

!e).a+A"!file-/list!of!chec+s ""!+ist"1"2.3%"4.%%"12.5%"13.5%"'JL """"""" """"""""2"4.%%"1$.%%"'JL """"""""""""""""4"2.3%"12.5%## """"""""!+ist"!ma-e-rr"1"!+ist"2.3%"4.%%"12.5%"13.5%## """"""""""""""!ma-e-rr"2"!+ist"4.%%"1$.%%## """"""!ma-e-rr"4"!+ist"2.3%"12.5%####

Solution E ercise 2(<2<#< De+elop the )unction create-matri*, It consumes a number n and a list o) n& numbers, It produces a list o) n lists o) n numbers, #8ample:
!e).a+A"!create-matri*"2"!+ist"1"2"3"4## """"""""!+ist"!+ist"1"2# """"""!+ist"3"4###

Solution

"0#( Binary Search


Applied mathematicians model the real2world with non2linear e?uations and then tr$ to sol+e them, Here is a simplistic e8ample: =i+en a per)ect cube that encloses &;m5, 1hat area do its si8 walls co+erH 1e .now )rom geometr$ that i) the length o) a cubeCs side is +! the enclosed space is +5, Hence we need to .now the possible +alues o) + such that @nce we ha+e sol+ed the e?uation! the co+ered area is 9 P +&, In general! we are gi+en a )unction f )rom numbers to numbers! and want to .now some number r such that

The +alue r is called the root o) f, In our abo+e e8ample! f/+0 O +5 - &;! and the +alue r is the length o) the side o) the cube,9' For the past )ew centuries! mathematicians ha+e de+eloped man$ methods )or )inding the root o) di))erent t$pes o) )unctions, In this section! we stud$ a solution that is based on the Intermediate "alue Theorem! an earl$ result o) mathematical anal$sis, The resulting algorithm is a primar$ e8ample o) generati+e recursion based on a deep mathematical theorem, It has been adapted to other uses and has become .nown as the binar$ search algorithm in computer science,

Figure (#' A numeric )unction f with root in inter+al Va!bW /stage (0

The Intermediate 4alue Theorem sa$s that a continuous )unction f has a root in an inter+al Va!bW i) the signs o) f/a0 and f/b0 di))er, B$ contin o s we mean a )unction that doesnCt DDFump!CC that doesnCt ha+e gaps! and that alwa$s continues in a DDsmoothCC )ashion, The theorem is best illustrated with the graph o) a )unction, The )unction f in )igure ;6 is below the + a8is at a and abo+e the +2a8is at b, It is a continuous )unction! which we can tell )rom the uninterrupted! smooth line, And indeed! the )unction intersects the + a8is somewhere between a and b, -ow ta.e a loo. at the midpoint between a and b:

It partitions the inter+al Va!bW into two smaller! e?uall$ large inter+als, 1e can now compute the +alue o) f at m and see whether it is below or abo+e ', Here f/m0 U '! so according to the Intermediate 4alue Theorem! the root is in the right inter+al: Vm!bW, @ur picture con)irms this because the root is in the right hal) o) the inter+al! labeled DDrange &CC in )igure ;6, The abstract description o) the Intermediate 4alue Theorem and the illustrati+e e8ample describe a process )or )inding a root, Speci)icall$! we use the hal+ing step as man$ times as necessar$ to determine a tolerabl$ small range in which f must ha+e a root, "et us now translate this description into a Scheme algorithm! which we call find-root, To begin with! we must agree on the e8act tas. o) find-root, It consumes a )unction! letCs call it f! )or which we need to )ind a root, In addition! it must consume the boundaries o) the inter+al in which we e8pect to )ind a root, For simplicit$! letCs sa$ that

consumes two numbers: +eft and right, But these parameters canCt be Fust an$ two numbers, For our algorithm to wor. we must assume that
find-root !or"!?&"!f"+eft#"%"!f"right## """"!?&"!f"right#"%"!f"+eft###

holds, This assumption e8presses the condition o) the Intermediate 4alue Theorem that the )unction must ha+e di))erent signs )or +eft and right, According to the in)ormal process description! the tas. o) find-root is to )ind an inter+al that contains a root and that is tolerabl$ small, The si*e o) the gi+en inter+al is !-"right"+eft#, For the moment! we assume that the tolerance is de)ined as a top2 le+el +ariable ;NL5Q'J75, =i+en that! find-root can produce one o) the two boundaries o) the inter+al because we .now what its si*e isE letCs pic. the le)t one, Here is a translation o) our discussion into a contract! a purpose statement! and a header! including the assumption on the parameters:
66"find-root":"!n.m8er""-/""n.m8er#"n.m8er"n.m8er""-/""n.m8er 66"to"determine"Q"s.ch"that"f"has"a"root"in"9Q<!+"Q";NL5Q'J75#: 66" 66"'CCPH3;INJ:"!or"!?&"!f"+eft#"%"!f"right##"!?&"!f"right#"%"!f +eft### !define"!find-root"f"+eft"right#"...#

At this stage! we should de+elop an e8ample o) how the )unction wor.s, 1e ha+e alread$ seen oneE the )ollowing e8ercise de+elops a second one, E ercise 2(<!<1< Consider the )ollowing )unction de)inition:
66"po+2":"n.m8er""-/""n.m8er !define"!po+2"*# "!*"!-"*"2#"!-"*"4###

It de)ines a binomial )or which we can determine its roots b$ hand 22 the$ are 2 and 4, But it is also a non2tri+ial input )or find-root! so that it ma.es sense to use it as an e8ample, Mimic the root2)inding process based on the Intermediate 4alue Theorem )or po+2! starting with the inter+al 3 and , Tabulate the in)ormation as )ollows: [step !ef /f !eft0 t n O ( 5 2( n O & 5 2( righ /f right0 t 9,'' <,'' 6,&7 (,&7 mi /f mid0 d 6,7 (,&7 H H Solution

Find an inter+al o) si*e ,7 /or less0 in which po+2 contains a root,

-e8t we turn our attention to the de)inition o) find-root, 1e start )rom generati0erec.rsi0e-f.n and as. the )our rele+ant ?uestions: (, 1e need a condition that describes when the problem is sol+ed and a matching answer, This is straight)orward, The problem is sol+ed i) the distance )rom +eft to right is smaller than or e?ual to ;NL5Q'J75:
2. !?&"!-"right"+eft#";NL5Q'J75#

The matching result is +eft, 5, 1e must )ormulate an e8pression that generates new problems )or find-root, According to our in)ormal process description! this step re?uires determining the midpoint and choosing the ne8t inter+al, The midpoint is used se+eral times! so we use a local2e8pression to introduce it:
4. !local"!!define"mid"!/"!+"+eft"right#"2### 5. ""...#

Choosing an inter+al is more complicated than that, Consider the Intermediate 4alue Theorem again, It sa$s that a gi+en inter+al is an interesting candidate i) the )unction +alues at the boundaries ha+e di))erent signs, For the )unctionCs purpose statement! we e8pressed this constraint using
!or"!?&"!f"+eft#"%"!f"right##"!?&"!f"right#"%"!f"+eft###

Accordingl$! the inter+al between +eft and mid is the ne8t candidate i)
!or"!?&"!f"+eft#"%"!f"mid##"!?&"!f"mid#"%"!f"+eft###

And! the inter+al between mid and right is it! i)


!or"!?&"!f"mid#"%"!f"right##"!?&"!f"right#"%"!f"mid###

In short! the bod$ o) the local2e8pression must be a conditional:


!local"!!define"mid"!/"!+"+eft"right#"2### ""!cond """"9!or"!?&"!f"+eft#"%"!f"mid##"!?&"!f"mid#"%"!f"+eft### """""!find-root"+eft"mid#: """"9!or"!?&"!f"mid#"%"!f"right##"!?&"!f"right#"%"!f"mid### """""!find-root"mid"right#:##

In both clauses! we use find-root to continue the search, The completed )unction is displa$ed in )igure ;7, The )ollowing e8ercises suggest some tests and a termination argument,

66"find-root":"!n.m8er""-/""n.m8er#"n.m8er"n.m8er""-/""n.m8er 66"to"determine"a"n.m8er":"s.ch"that"f"has"a" 66"root"8etween"Q"and"!+"Q";NL5Q'J75#" 66" 66"'CCPH3;INJ:"f"is"contin.o.s"and"monotonic !define"!find-root"f"+eft"right# ""!cond """"9!?&"!-"right"+eft#";NL5Q'J75#"+eft: """"9else" """"""!local"!!define"mid"!/"!+"+eft"right#"2### !cond ""9!?&"!f"mid#"%"!f"right##" """""""""""!find-root"mid"right#: ""9else"

/)ind2root le)t mid0W00W00 Figure ($' The root2)inding algorithm find-root E ercise 2(<!<2< Ase po+2 )rom &;,5,( to test find-root, #8periment with di))erent +alues )or ;NL5Q'J75, Ase the strateg$ o) section (;,< to )ormulate the tests as boolean2 +alued e8pressions, Solution E ercise 2(<!<!< Suppose the original arguments o) find-root describe an inter+al o) si*e C1, How large is the distance between +eft and right )or the )irst recursi+e call to find-rootH The second oneH And the thirdH A)ter how man$ e+aluation steps is the distance between +eft and right smaller than or e?ual to ;NL5Q'J75H How does the answer to this ?uestion show that find-root produces an answer )or all inputs that satis)$ the assumptionH Solution E ercise 2(<!<#< For e+er$ midpoint m! e8cept )or the last one! the )unction find-root needs to determine the +alue o) !f"m# twice, 4alidate this claim )or one e8ample with a hand2e+aluation, Since the e+aluation o) !f"m# ma$ be time2consuming! programmers o)ten implement a +ariant o) find-root that a+oids this recomputation, Modi)$ find-root in )igure ;7 so that it does not need to recompute the +alue o) !f"mid#, >int' De)ine a help )unction find-root-a.* that ta.es two e8tra arguments: the +alues !f"+eft# and !f"right#, Solution E ercise 2(<!<$< A tab!e is a )unction that consumes natural numbers between % and WL /e8clusi+e0 and produces numbers:
66"g":"N""-/""n.m 66"'CCPH3;INJ:"i"is"8etween"%"and"WL !define"!g"i# ""!cond """"9!&"i"%#"-1%: """"9!&"i"1#"...:

""""... """"9!&"i"!-"WL"1##"...: """"9else"!error"'g"1is"defined"on+2"8etween"%"and"WL !e*c+.si0e#1#:##

The number WL is called the tab!e.s !ength, The root of a tab!e is the number in the table that is closest to %, #+en i) we canCt read the de)inition o) a table! we can )ind its root with a search )unction, De+elop the )unction find-root-+inear! which consumes a table! the tableCs length! and )inds the root o) the table, Ase structural induction on natural numbers, This .ind o) root2)inding process is o)ten called a "I-#AR S#ARCH, A table t is sorted in ascending order i) !t"%# is less then !t"1#! !t"1# is less than !t 2#! and so on, I) a table is monotonic! we can determine the root using binar$ search, Speci)icall$! we can use binar$ search to )ind an inter+al o) si*e 1 such that either the le)t or the right boundar$ is the rootCs inde8, De+elop find-root-discrete! which consumes a table and its length! and )inds the tableCs root, >ints' /(0 The inter+al boundar$ arguments )or find-root-discrete must alwa$s be natural numbers, Consider how this a))ects the midpoint computation, /&0 Also contemplate how the )irst hint a))ects the disco+er$ o) tri+iall$ sol+able problem instances, /50 Does the termination argument )rom e8ercise &;,5,5 appl$H I) the tabulating )unction is de)ined on all natural numbers between % and 1%24! and i) its root is at %! how man$ recursi+e applications are needed with find-root-discrete and find-root-+in to determine a root inter+alH Solution E ercise 2(<!<&< 1e mentioned in section &5,6 that mathematicians are interested not onl$ about the roots o) )unctions! but also in the area that a )unction encloses between two points, Mathematicall$ put! we are interested in integrating )unctions o+er some inter+al, Ta.e another loo. at the graph in )igure 96 on page &>, Recall that the area o) interest is that enclosed b$ the bold +ertical lines at a and b! the + a8is! and the graph o) the )unction, In section &5,6! we learned to appro8imate the area b$ computing and adding up the area o) rectangles li.e the two abo+e, Asing the di+ide2and2con?uer strateg$! we can also design a )unction that computes the area based on generati+e recursion, Roughl$ spea.ing! we split the inter+al into two pieces! compute the area o) each piece! and add the two areas together, Step 1: De+elop the algorithm integrate-dc! which integrates a )unction f between the boundaries +eft and right +ia the di+ide2and2con?uer strateg$ emplo$ed in findroot, Ase rectangle appro8imations when an inter+al has become small enough,

Although the area o) a rectangle is eas$ to compute! a rectangle is o)ten a bad appro8imation o) the area under a )unction graph, A better geometric shape is the trape*oid limited b$ a! !f"a#! b! and !f"8#, Its area is:

Step 2: Modi)$ integrate-dc so that it uses trape*oids instead o) rectangles, The plain di+ide2and2con?uer approach is waste)ul, Consider that a )unction graph is le+el in one part and rapidl$ changes in another, For the le+el part it is pointless to .eep splitting the inter+al, 1e could Fust compute the trape*oid o+er a and b instead o) the two hal+es, To disco+er when f is le+el! we can change the algorithm as )ollows, Instead o) Fust testing how large the inter+al is! the new algorithm computes the area o) three trape*oids: the gi+en one! and the two hal+es, Suppose the di))erence between the two is less than

This area represents a small rectangle! o) height ;NL5Q'J75! and represents the error margin o) our computation, In other words! the algorithm determines whether f changes enough to a))ect the error margin! and i) not! it stops, @therwise! it continues with the di+ide2and2con?uer approach, Step !: De+elop integrate-adapti0e! which integrates a )unction f between !eft and right according to the suggested method, Do not discuss the termination o) integrateadapti0e, +dapti1e Integration: The algorithm is called DDadapti+e integrationCC because it automaticall$ adapts its strateg$, For those parts o) f that are le+el! it per)orms Fust a )ew calculationsE )or the other parts! it inspects +er$ small inter+als so that the error margin is also decreased accordingl$, Solution

"0#) %e!ton>s /ethod


-ewton in+ented another method )or )inding the root o) a )unction, -ewtonCs method e8ploits the idea o) an appro8imation, To search a root o) some )unction f! we start with a guess! sa$! r1, Then we stud$ the tangent o) f at r1! that is! the line that goes through the Cartesian point /r1! f!r1#0 and has the same slope as f, This tangent is a linear appro8imation o) f and it has a root that is in man$ cases closer to the root o) f than our original guess, Hence! b$ repeating this process su))icientl$ o)ten! we can )ind an r )or which !f"r# is close to %,

To translate this process description into Scheme! we )ollow the )amiliar process, The )unction 22 letCs call it newton in honor o) its in+entor 22 consumes a )unction f and a number r%! the current guess, I) !f"r%# is close to %! the problem is sol+ed, @) course! close to % could be mean !f"r%# is a small positi+e number or a small negati+e number, Hence we translate this idea into
!?&"!a8s"!f"r%##";NL5Q'J75#

That is! we determine whether the absolute +alue is small, The answer in this case is r%, The generati+e step o) the algorithm consists o) )inding the root o) the tangent o) f at r%, It generates a new guess, B$ appl$ing newton to this new guess! we resume the process with what we hope is a better guess:
66"newton":"!n.m8er""-/""n.m8er#"n.m8er""-/""n.m8er 66"to"find"a"n.m8er"r"s.ch"that"!?"!a8s"!f"r##";NL5Q'J75# !define"!newton"f"r%# ""!cond """"9!?&"!a8s"!f"r%##";NL5Q'J75#"r%: """"9else"!newton"f"!find-root-tangent"f"r%##:##

Since )inding the root o) a tangent is domain .nowledge! we de)ine a separate )unction )or this purpose:
66"find-root-tangent":"!n.m8er""-/""n.m8er#"n.m8er""-/""n.m8er 66"to"find"the"root"of"the"tagent"of"f"at"r% !define"!find-root-tangent"f"r%# ""!local"!!define"fprime"!d/d*"f### """"!-"r% """""""!/"!f"r%# ""!fprime"r%#####

The )unction )irst computes !d/d*"f#! that is! the deri+ati+e o) f at r% /see section &5,70 at r%, The bod$ o) the local2e8pression computes the root )rom the current guess! !f"r%#! and the slope o) f at r%,9( The most interesting aspect o) newton is that! unli.e all other )unctions we ha+e discussed! it does not alwa$s terminate, Consider the )ollowing )unction:
66"f":"n.m8er""-/""n.m8er !define"!f"*# ""!-"!*"*"*#"*"1.$##

A simple hand2calculation shows that its deri+ati+e is


66"fprime":"n.m8er""-/""n.m8er !define"!fprime"*# ""!-"!*"2"*#"1##

I) we were to use 1/2 as the initial guess! we would ha+e to )ind the root o) a tangent with slope %! that is! a tangent that is parallel to the + a8is, @) course! such a tangent doesnCt ha+e a root, As a result! find-root-of-tangent cannot )ind a tangent and newton wonCt )ind a root,

E ercise 2(<#<1< Test newton with f, Ase the initial guesses 1! 2! and 3, Also use find-root )rom the preceding section to )ind a root, Ase a hand2e+aluation to determine how ?uic.l$ newton )inds a +alue close to the root /i) it )inds one0, Compare newtonCs beha+ior with find-rootCs beha+ior, #mplo$ the strateg$ o) section (;,< to )ormulate the tests as boolean2+alued e8pressions, Solution

"0#* E,tended E,ercise. 5aussian Elimination


Mathematicians not onl$ search )or solutions o) e?uations in one +ariableE the$ also stud$ whole s$stems o) linear e?uations, Here is a sample s$stem o) e?uations in three +ariables! +! y! and ':

A solution to a s$stem o) e?uations is a series o) numbers! one per +ariable! such that i) we replace the +ariable with its corresponding number! the two sides o) each e?uation e+aluate to the same number, In our running e8ample! the solution is + O (! y O (! and ' O &! as we can easil$ chec.:

The )irst e?uation now reads as (' O ('! the second one as 5( O 5(! and the last one as ( O (, @ne o) the most )amous methods )or )inding a solution is called =aussian elimination, It consists o) two steps, The )irst step is to trans)orm the s$stem o) e?uations into a s$stem o) di))erent shape but with the same solution, The second step is to )ind solutions to one e?uation at a time, Here we )ocus on the )irst step because it is another interesting instance o) generati+e recursion, The )irst step o) the =aussian elimination algorithm is called DDtriangulationCC because the result is a s$stem o) e?uations in the shape o) a triangle, In contrast! the original s$stem is t$picall$ a rectangle, To understand this terminolog$! ta.e a loo. at this representation o) the original s$stem:

This representation captures the essence o) the s$stem! namel$! the numeric coe))icients o) the +ariables and the right2hand sides, The names o) the +ariables donCt pla$ an$ role, The generati+e step in the triangulation phase is to subtract the )irst row /list0 o) numbers )rom all the other rows, Subtracting one row )rom another means subtracting the corresponding items in the two rows, 1ith our running e8ample! this step would $ield

when we subtract the )irst row )rom the second, The goal o) these subtractions is to put a ' into the )irst column o) all but the )irst row, To achie+e this )or the last row! we subtract the )irst row twice )rom the second one:

Put di))erentl$! we )irst multipl$ each item in the )irst row with 2 and then subtract the result )rom the last row, It is eas$ to chec. that the solutions )or the original s$stem o) e?uations and )or this new one are identical, E ercise 2(<$<1< Chec. that the )ollowing s$stem o) e?uations

has the same solution as the one labeled with /\0,

Solution

E ercise 2(<$<2< De+elop s.8tract, The )unction consumes two lists o) numbers o) e?ual length, It subtracts the )irst )rom the second! item b$ item! as man$ times as necessar$ to obtain % in the )irst position, The result is the rest o) this list, Solution Following con+ention! we drop the leading %Cs )rom the last two e?uations:

I)! in addition! we use the same process )or the remainder o) the s$stem to generate shorter rows! the )inal representation has a triangular shape,

"et us stud$ this idea with our running e8ample, For the moment we ignore the )irst row and )ocus on the rest o) the e?uations:

B$ subtracting the )irst row now 2( times )rom the second one! we get

a)ter dropping the leading %, The remainder o) this s$stem is a single e?uation! which cannot be simpli)ied an$ )urther, Here is the result o) adding this last s$stem to the )irst e?uation:

As promised! the shape o) this s$stem o) e?uations is /roughl$0 a triangle! and as we can easil$ chec.! it has the same solution as the original s$stem, E ercise 2(<$<!< Chec. that the )ollowing s$stem o) e?uations

has the same solution as the one labeled with /\0,

Solution

E ercise 2(<$<#< De+elop the algorithm triang.+ate! which consumes a rectangular representation o) a s$stem o) e?uations and produces a triangular +ersion according the =aussian algorithm, Solution An)ortunatel$! the current +ersion o) the triangulation algorithm occasionall$ )ails to produce the solution, Consider the )ollowing /representation o) a0 s$stem o) e?uations:

Its solution is + O (! y O (! and ' O (, The )irst step is to subtract the )irst row )rom the second and to subtract it twice )rom the last one! which $ields the )ollowing matri8:

-e8t our algorithm would )ocus on the rest o) the matri8:

but the )irst item o) this matri8 is %, Since we cannot di+ide b$ %! we are stuc., To o+ercome this problem! we need to use another piece o) .nowledge )rom our problem domain! namel$! that we can switch e?uations around without changing the solution, @) course! as we switch rows! we must ma.e sure that the )irst item o) the row to be mo+ed is not %, Here we can simpl$ swap the two rows:

From here we ma$ continue as be)ore! subtracting the )irst e?uation )rom the remaining ones a su))icient number o) times, The )inal triangular matri8 is:

It is eas$ to chec. that this s$stem o) e?uations still has the solution + O (! y O (! and ' O (, E ercise 2(<$<$< Re+ise the algorithm triang.+ate )rom e8ercise &;,7,6 so that it switches rows when the )irst item o) the matri8 is %, >int' DrScheme pro+ides the )unction remo0e, It consumes an item I and a list L and produces a list li.e L but with the )irst occurrence o) I remo+ed, For e8ample!
!e).a+A"!remo0e"!+ist"%"1#"!+ist"!+ist"2"1#"!+ist"%"1###" """"""""!+ist"!+ist"2"1###

Solution E ercise 2(<$<&< Some s$stems o) e?uations donCt ha+e a solution, Consider the )ollowing s$stem as an e8ample:

Tr$ to produce a triangular s$stem b$ hand and with triang.+ate, 1hat happensH Modi)$ the )unction so that it signals an error i) it encounters this situation, Solution E ercise 2(<$<(< A)ter we obtain a triangular s$stem o) e?uations such as /T0 on page 56 /or e8ercise &;,7,50! we can sol+e the e?uations, In our speci)ic e8ample! the last e?uation sa$s that ' is &, #?uipped with this .nowledge! we can eliminate ' )rom the second e?uation through a substitution:

Determine the +alue )or y, Then repeat the substitution step )or y and ' in the )irst e?uation and )ind the +alue )or +, De+elop the )unction so+0e! which consumes triangular s$stems o) e?uations and produces a solution, A triangular s$stem o) e?uations has the shape

where ai3 and bi are numbers, That is! it is a list o) lists and each o) the lists is one item shorter than the preceding one, A solution is a list o) numbers, The last number on the list is

>int' De+eloping so+0e re?uires a solution )or the )ollowing problem, Suppose we are gi+en a row:
!+ist"3","21#

and a list o) numbers that sol+e the remainder o) the s$stem:


!+ist"2#.

In the world o) e?uations! these two pieces o) data represent the )ollowing .nowledge:

and

which in turn means we must sol+e the )ollowing e?uation:

De+elop the )unction e0a+.ate! which e+aluates the rest o) the le)t2hand side o) an e?uation and subtracts the right2hand side )rom this sum, #?ui+alentl$! e0a+.ate consumes !+ist","21# and !+ist"2# and produces -3! that is! > P & - &(, -ow use e0a+.ate )or the intermediate step in so+0e, Solution Ms, =eraldine Morin suggested this e8ercise,

7<

The tradition o) brea.ing a )ile into lines is due to the use o) punch cards with earl$ mechanical computers! dating bac. to the (<>' census, It is meaningless )or )ile storage in modern computing, An)ortunatel$! this historical accident continues to a))ect the de+elopment o) computing and so)tware technolog$ in a negati+e manner,
7>

I) the e?uation is originall$ presented as g/+0 O h/+0! we set f/+0 O g/+0 - h/+0 to trans)orm the e?uation into the standard )orm,
9'

9(

The tangent o) a )unction f at ri is the linear )unction

The )unction fC is the deri+ati+e o) f! and fC/r'0 is the slope o) f at r', Furthermore! the root o) a linear )unction is the intersection o) a straight line with the + a8is, In general! i) the lineCs e?uation is

then its root is - bKa, In our case! the root o) fCs tangent is

Section 2) +lgorithms that 5ac6trac6


Sol+ing problems does not alwa$s proceed on a direct route to the goal, Sometimes we ma.e progress b$ pursuing one approach onl$ to disco+er that we are stuc. because we too. a wrong turn, In those cases! we bac.trac. in our e8ploration and ta.e a di))erent turn at some branch! in the hope that it leads us to a solution, Algorithms can proceed li.e that, In the )irst subsection! we deal with an algorithm that can help us tra+erse a graph! which is o) course the situation we Fust discussed, The second subsection is an e8tended e8ercise that uses bac.trac.ing in the conte8t o) chess,

"4#$ Traversing 5raphs


@n occasion! we need to na+igate through a ma*e o) one2wa$ streets, @r! we ma$ wish to draw a graph o) whom we consider a )riend! whom the$ consider a )riend! and so on, @r! we need to plan a route through a networ. o) pipelines, @r! we as. the Internet to )ind some wa$ to send a message )rom one place to another, All these situations share a common element: a directed graph, Speci)icall$! there is alwa$s some collection o) nodes and a collection o) edges, The edges represent one2wa$ connections between the nodes, Consider )igure ;9, The blac. bullets are the nodesE the arrows between them are the one2wa$ connections, The sample graph consists o) se+en nodes and nine edges, -ow suppose we wish to plan routes in the graph o) )igure ;9, For e8ample! i) we plan to go )rom C to D! the route is simple: it consists o) the origination node C and the destination node D, In contrast! i) we wish to tra+el )rom # to D! we ha+e two choices: (, 1e either tra+el )rom # to F and then to D, &, @r! we tra+el )rom # to C and then to D, For some nodes! howe+er! it is impossible to connect them, In particular! it is impossible in our sample graph to mo+e )rom C to = b$ )ollowing the arrows,

Figure (&' A directed graph In the real world! graphs ha+e more than Fust se+en nodes and man$ more edges, Hence it is natural to de+elop )unctions that plan routes in graphs, Following the general design recipe! we start with a data anal$sis, Here is a compact representation o) the graph in )igure ;9 using lists:
!define"Graph" ""'!!'"!("5## """"!("!5">## """"!7"!D## """"!D"!## """"!5"!7">## """"!>"!D"G## """"!G"!####

The list contains one list per node, #ach o) these lists starts with the name o) a node )ollowed b$ the list o) its neighbors, For e8ample! the second list represents node B with its two outgoing edges to # and F, E ercise 2)<1<1< Translate the abo+e de)inition into proper list )orm using +ist and proper s$mbols, The data de)inition )or node is straight)orward: A node is a s$mbol, Formulate a data de)inition )or graphs with arbitraril$ man$ nodes and edges, The data de)inition must speci)$ a class o) data that contains Graph, Solution Based on the data de)initions )or node and graph! we can now produce the )irst dra)t o) a contract )or find-ro.te! the )unction that searches a route in a graph:
66"find-ro.te":"node"node"graph""-/""!listof"node# 66"to"create"a"path"from"origination"to"destination"in"G !define"!find-ro.te"origination"destination"G#"...#

1hat this header lea+es open is the e8act shape o) the result, It implies that the result is a list o) nodes! but it does not sa$ e8actl$ which nodes the list contains, To understand this aspect! we must stud$ some e8amples,

Consider the )irst problem mentioned abo+e, Here is an e8pression that )ormulates the problem in Scheme:
!find-ro.te"'7"'D"Graph#

A route )rom '7 to 'D consists o) Fust two nodes: the origination and the destination node, Hence! we should e8pect the answer !+ist"'7"'D#, @) course! one might argue that since both the origination node and the destination node are .nown! the result should be empt2, Here we choose the )irst alternati+e since it is more natural! but it re?uires onl$ a minor change o) the )inal )unction de)inition to produce the latter, -ow consider our second problem! going )rom '5 to 'D! which is more representati+e o) the .inds o) problems we might encounter, @ne natural idea is to inspect all o) the neighbors o) '5 and to )ind a route )rom one o) them to 'D, In our sample graph! '5 has two neighbors: '7 and '>, Suppose )or a moment that we didnCt .now the route $et, In that case! we could again inspect all o) the neighbors o) '7 and )ind a route )rom those to our goal, @) course! '7 has a single neighbor and it is 'D, Putting together the results o) all stages shows that the )inal result is !+ist"'5"'7"'D#, @ur )inal e8ample poses a new problem, Suppose find-ro.te is gi+en the arguments '7! 'G! and Graph, In this case! we .now )rom inspecting )igure ;9 that there is no connecting route, To signal the lac. o) a route! find-ro.te should produce a +alue that cannot be mista.en )or a route, @ne good choice is fa+se! a +alue that isnCt a list and naturall$ denotes the )ailure o) a )unction to compute a proper result, This new agreement re?uires another change in our contract:
66"find-ro.te":"node"node"graph""-/""!listof"node#"or"fa+se 66"to"create"a"path"from"origination"to"destination"in"G 66"if"there"is"no"path<"the"f.nction"prod.ces"fa+se !define"!find-ro.te"origination"destination"G#"...#

@ur ne8t step is to understand the )our essential pieces o) the )unction: the DDtri+ial problemCC condition! a matching solution! the generation o) a new problem! and the combination step, The discussion o) the three e8amples suggests answers, First! i) the origination argument o) find-ro.te is e?ual to its destination! the problem is tri+ialE the matching answer is !+ist"destination#, Second! i) the arguments are di))erent! we must inspect all neighbors o) origination in graph and determine whether there is a route )rom one o) those to destination, Since a node can ha+e an arbitrar$ number o) neighbors! this tas. is too comple8 )or a single primiti+e, 1e need an au8iliar$ )unction, The tas. o) the au8iliar$ )unction is to consume a list o) nodes and to determine )or each one o) them whether there is a route to the destination node in the gi+en graph, Put di))erentl$! the )unction is a list2oriented +ersion o) find-ro.te, "et us call this )unction find-ro.te/+ist, Here is a translation o) this in)ormal description into a contract! header! and purpose statement:

66"find-ro.te/+ist":"!listof"node#"node"graph""-/""!listof"node# or"fa+se 66"to"create"a"path"from"some"node"on"+o-originations"to destination 66"if"there"is"no"path<"the"f.nction"prod.ces"fa+se !define"!find-ro.te/+ist"+o-originations"destination"G#"...#

-ow we can write a )irst dra)t o) find-ro.te as )ollows:


!define"!find-ro.te"origination"destination"G# ""!cond """"9!s2m8o+&A"origination"destination#"!+ist"destination#: """"9else"..."!find-ro.te/+ist"!neigh8ors"origination"G# destination"G#"...:##

The )unction neigh8ors generates a whole list o) problems: the problems o) )inding routes )rom the neighbors o) origination to destination, Its de)inition is a straight)orward e8ercise in structural processing, E ercise 2)<1<2< De+elop the )unction neigh8ors, It consumes a node n and a graph g /see e8ercise &<,(,(0 and produces the list o) neighbors o) n in g, Solution -e8t we need to consider what find-ro.te/+ist produces, I) it )inds a route )rom an$ o) the neighbors! it produces a route )rom that neighbor to the )inal destination, But! i) none o) the neighbors is connected to the destination! the )unction produces fa+se, Clearl$! find-ro.teCs answer depends on what find-ro.te/+ist produces, Hence we should distinguish the answers with a cond2e8pression:
!define"!find-ro.te"origination"destination"G# ""!cond """"9!s2m8o+&A"origination"destination#"!+ist"destination#: """"9else"!local"!!define"possi8+e-ro.te" """"!find-ro.te/+ist"!neigh8ors"origination"G#" """""""""""""""""""""""""""""""""""""destination"G### """"!cond """"""9!8oo+eanA"ro.te#"...: """"""9else"6"!consA"ro.te#" ...:##:##

The two cases re)lect the two .inds o) answers we might recei+e: a boolean or a list, I) find-ro.te/+ist produces fa+se! it )ailed to )ind a route )rom originationCs neighbors! and it is there)ore impossible to reach destination at all, The answer in this case must there)ore be fa+se, In contrast! i) find-ro.te/+ist produces a list! the answer must be route )rom origination to destination, Since possi8+e-ro.te starts with one o) originationCs neighbors! it su))ices to add origination to the )ront o) possi8+e-ro.te,

66"find-ro.te":"node"node"graph""-/""!listof"node#"or"fa+se 66"to"create"a"path"from"origination"to"destination"in"G 66"if"there"is"no"path<"the"f.nction"prod.ces"fa+se !define"!find-ro.te"origination"destination"G# ""!cond """"9!s2m8o+&A"origination"destination#"!+ist"destination#: """"9else"!local"!!define"possi8+e-ro.te" """"!find-ro.te/+ist"!neigh8ors"origination"G# destination"G### """"!cond """"""9!8oo+eanA"possi8+e-ro.te#"fa+se: """"""9else"!cons"origination"possi8+e-ro.te#:##:## 66"find-ro.te/+ist":"!listof"node#"node"graph""-/""!listof"node# or"fa+se 66"to"create"a"path"from"some"node"on"+o-Ns"to"D 66"if"there"is"no"path<"the"f.nction"prod.ces"fa+se !define"!find-ro.te/+ist"+o-Ns"D"G# ""!cond """"9!empt2A"+o-Ns#"fa+se: """"9else"!local"!!define"possi8+e-ro.te"!find-ro.te"!first"+o-Ns# D"G### """"!cond """"""9!8oo+eanA"possi8+e-ro.te#"!find-ro.te/+ist"!rest"+o-Ns# D"G#:

Velse possible2routeW00W00 Figure ((' Finding a route in a graph Figure ;; contains the complete de)inition o) find-ro.te, It also contains a de)inition o) find-ro.te/+ist! which processes its )irst argument +ia structural recursion, For each node in the list! find-ro.te/+ist uses find-ro.te to chec. )or a route, I) findro.te indeed produces a route! that route is the answer, @therwise! i) find-ro.te )ails and produces fa+se! the )unction recurs, In other words! it bac.trac.s its current choice o) a starting position! !first"+o-Ns#! and instead tries the ne8t one in the list, For that reason! find-ro.te is o)ten called a BAC TRAC I-= A"=@RITHM, 5ac6trac6ing in the Structural @orld: Interme**o 5 discusses bac.trac.ing in the structural world, A particularl$ good e8ample is e8ercise (<,(,(5! which concerns a bac.trac.ing )unction )or )amil$ trees, The )unction )irst searches one branch o) a )amil$ tree )or a blue2e$ed ancestor and! i) this search produces fa+se! it searches the other hal) o) the tree, Since graphs generali*e trees! comparing the two )unctions is an instructi+e e8ercise, "ast! but not least! we need to understand whether the )unction produces an answer in all situations, The second one! find-ro.te/+ist! is structurall$ recursi+e and there)ore alwa$s produces some +alue! assuming find-ro.te alwa$s does, For find-ro.te the answer is )ar )rom ob+ious, For e8ample! when gi+en the graph in )igure ;9 and two nodes in the graph! find-ro.te alwa$s produces some answer, For other graphs! howe+er! it does not alwa$s terminate,

E ercise 2)<1<!< Test find-ro.te, Ase it to )ind a route )rom A to = in the graph o) )igure ;9, #nsure that it produces fa+se when as.ed to )ind a route )rom C to =, Solution E ercise 2)<1<#< De+elop the )unction test-on-a++-nodes! which consumes a graph g and tests find-ro.te on all pairs o) nodes in g, Test the )unction on Graph, Solution

Figure ()' A directed graph with c$cle Consider the graph in )igure ;<, It di))ers radicall$ )rom the graph in )igure ;9 in that it is possible to start a route in a node and to return to the same node, Speci)icall$! it is possible to mo+e )rom B to # to C and bac. to B, And indeed! i) applied find-ro.te to '(! 'D! and a representation o) the graph! it )ails to stop, Here is the hand2e+aluation:
""!find-ro.te"'("'D"72c+ic-graph# &"..."!find-ro.te"'("'D"72c+ic-graph#"... &"..."!find-ro.te/+ist"!+ist"'5"'>#"'D"72c+ic-graph#"... &"..."!find-ro.te"'5"'D"72c+ic-graph#"... &"..."!find-ro.te/+ist"!+ist"'7"'>#"'D"72c+ic-graph#"... &"..."!find-ro.te"'7"'D"72c+ic-graph#"... &"..."!find-ro.te/+ist"!+ist"'("'D#"'D"72c+ic-graph#"... &"..."!find-ro.te"'("'D"72c+ic-graph#"... &"..."

where 72c+ic-Graph stands )or a Scheme representation o) the graph in )igure ;<, The hand2e+aluation shows that a)ter se+en applications o) find-ro.te and findro.te/+ist the computer must e+aluate the e8act same e8pression )rom which we started, Since the same input produces the same output and the same beha+ior )or )unctions! we .now that the )unction loops )ore+er and does not produce a +alue, In summar$! i) some gi+en graph is c$cle2)ree! find-ro.te produces some output )or an$ gi+en inputs, A)ter all! e+er$ route can onl$ contain a )inite number o) nodes! and the number o) routes is )inite! too, The )unction there)ore either e8hausti+el$ inspects all solutions starting )rom some gi+en node or )inds a route )rom the origination to the destination node, I)! howe+er! a graph contains a c$cle! that is! a route )rom some node bac. to itsel)! find-ro.te ma$ not produce a result )or some inputs, In the ne8t part! we will stud$ a programming techni?ue that helps us )inds routes e+en in the presence o) c$cles in a graph,

E ercise 2)<1<$< Test find-ro.te on '(! '7! and the graph in )igure ;<, Ase the ideas o) section (;,< to )ormulate the tests as boolean2+alued e8pression, Solution E ercise 2)<1<&< @rgani*e the find-ro.te program as a single )unction de)inition, Remo+e parameters )rom the locall$ de)ined )unctions, Solution

"4#" E,tended E,ercise. Checking ?on@ =ueens


A )amous problem in the game o) chess concerns the placement o) ?ueens on a board, For our purposes! a chessboard is a DDs?uareCC o)! sa$! eight2b$2eight or three2b$2three tiles, The ?ueen is a game piece that can mo+e in a hori*ontal! +ertical! or diagonal direction arbitraril$ )ar, 1e sa$ that a ?ueen threatens a tile i) it is on the tile or can mo+e to it, Figure ;> shows an e8ample, The solid dis. represents a ?ueen in the second column and si8th row, The solid lines radiating )rom the dis. go through all those tiles that are threatened b$ the ?ueen,

Figure (-' A chessboard with a single ?ueen The ?ueen2placement problem is to place eight ?ueens on a chessboard o) eight2b$2eight tiles such that the ?ueens on the board donCt threaten each other, In computing! we generali*e the problem o) course and as. whether we can place n ?ueens on some board o) arbitrar$ si*e m b$ m, #+en a cursor$ glance at the problem suggests that we need a data representation o) boards and some basic )unctions on boards be)ore we can e+en thin. o) designing a program that sol+es the problem, "etCs start with some basic data and )unction de)initions, E ercise 2)<2<1< De+elop a data de)inition )or chessboards,

>int' Ase lists, Represent tiles with tr.e and fa+se, A +alue o) tr.e should indicate that a position is a+ailable )or the placement o) a ?ueenE fa+se should indicate that a position is occupied b$! or threatened b$! a ?ueen, Solution -e8t we need a )unction )or creating a board and another one )or chec.ing on a speci)ic tile, Following the e8amples o) lists! letCs de)ine 8.i+d-8oard and 8oard-ref, E ercise 2)<2<2< De+elop the )ollowing two )unctions on chessboards:
66"8.i+d-8oard":"N"!N"N""-/""8oo+ean#""-/""8oard 66"to"create"a"8oard"of"si@e"n"*"n<" 66"fi++"each"position"with"indices"i"and"S"with"!f"i"S# !define"!8.i+d-8oard"n"f#"...# 66"8oard-ref":"8oard"N"N""-/""8oo+ean 66"to"access"a"position"with"indices"i<"S"on"a-8oard !define"!8oard-ref"a-8oard"i"S#"...#

Test them rigorousl$L Ase the ideas o) section (;,< to )ormulate the tests as boolean2 +alued e8pressions, Solution In addition to these generic )unctions on a chessboard representation! we also need at least one )unction that captures the concept o) a DDthreatCC as mentioned in the problem statement, E ercise 2)<2<!< De+elop the )unction threatenedA! which computes whether a ?ueen can reach a position on the board )rom some gi+en position, That is! the )unction consumes two positions! gi+en as posn structures! and produces tr.e i) a ?ueen on the )irst position can threaten the second position, >int' The e8ercise translate the chess problem o) DDthreatening ?ueensCC into the mathematical problem o) determining whether in some gi+en grid! two positions are on the same +ertical! hori*ontal! or diagonal line, eep in mind that each position belongs to two diagonals and that the slope o) a diagonal is either +1 or -1, Solution @nce we ha+e data de)initions and )unctions )or the DDlanguage o) chessboards!CC we can turn our attention to the main tas.: the algorithm )or placing a number o) ?ueens on some gi+en board, E ercise 2)<2<#< De+elop p+acement, The )unction consumes a natural number and a board and tries to place that man$ ?ueens on the board, I) the ?ueens can be placed! the )unction produces an appropriate board, I) not! it produces fa+se, Solution

Section 2Interme**o $' The Cost of Computing and "ectors


In section &9,5 we discussed the di))erences between a structurall$ recursi+e program and an e?ui+alent! generati+e +ersion, The comparison re+ealed that the generati+e one is much )aster than the structural +ersion, 1e used both in)ormal arguments! using the number o) recursi+e calls! and measurements! using time e8pressions /e8ercises &9,5,( and &9,5,50! to support our conclusion, 1hile timing the application o) a program to speci)ic arguments can help us understand a programCs beha+ior in one situation! it is not a )ull$ con+incing argument, A)ter all! appl$ing the same program to some other inputs ma$ re?uire a radicall$ di))erent amount o) time, In short! timing programs )or speci)ic inputs has the same status as testing programs )or speci)ic e8amples, Just as testing ma$ re+eal bugs! timing ma$ re+eal anomalies concerning the e8ecution beha+ior )or speci)ic inputs, It does not pro+ide a )irm )oundation )or general statements about the beha+ior o) a program, This interme**o introduces a tool )or ma.ing general statements about the time that programs ta.e to compute a result, The )irst subsection moti+ates the tool and illustrates it with se+eral e8amples! though on an in)ormal basis, The second one pro+ides a rigorous de)inition, The last one uses the tool to moti+ate an additional class o) Scheme data and some o) its basic operations,

"6#$ Concrete Time2

&stract Time

"etCs stud$ the beha+ior o) how-man2! a )unction that we understand well:


!define"!how-man2"a-+ist# ""!cond """"9!empt2A"a-+ist#"%: """"9else"!+"!how-man2"!rest"a-+ist##"1#:##

It consumes a list and computes how man$ items the list contains, Here is a sample e+aluation:
""!how-man2"!+ist"'a"'8"'c## &"!+"!how-man2"!+ist"'8"'c##"1# &"!+"!+"!how-man2"!+ist"'c##"1#"1# &"!+"!+"!+"!how-man2"empt2#"1#"1#"1#

&"3

It consists o) onl$ those steps that are natural recursions, The steps in between are alwa$s the same, For e8ample! to get )rom the original application to the )irst natural recursion! we go through the )ollowing steps:
""!how-man2"!+ist"'a"'8"'c## &"!cond """"9!empt2A"!+ist"'a"'8"'c##"%: """"9else"!+"!how-man2"!rest"!+ist"'a"'8"'c###"1#:# &"!cond """"9fa+se"%: """"9else"!+"!how-man2"!rest"!+ist"'a"'8"'c###"1#:# &"!cond """"9else"!+"!how-man2"!rest"!+ist"'a"'8"'c###"1#:# &"!+"!how-man2"!rest"!+ist"'a"'8"'c###"1#

The steps between the remaing natural recursions di))er onl$ as )ar as the substitution )or a-+ist is concerned, I) we appl$ how-man2 to a shorter list! we need )ewer natural recursion steps:
""!how-man2"!+ist"'e## &"!+"!how-man2"empt2#"1# &"1

I) we appl$ how-man2 to a longer list! we need more natural recursion steps, The number o) steps between natural recursions remains the same, The e8ample suggests that! not surprisingl$! the number o) e+aluation steps depends on the si*e o) the input, More importantl$! though! it also implies that the number o) natural recrusions is a good measure o) the si*e o) an e+aluation se?uence, A)ter all! we can reconstruct the actual number o) steps )rom this measure and the )unction de)inition, For this reason! programmers ha+e come to e8press the ABSTRACT RA--I-= TIM# o) a program as a relationship between the si*e o) the input and the number o) recursion steps in an e+aluation,9& In our )irst e8ample! the si*e o) the input is simpl$ the si*e o) the list, More speci)icall$! i) the list contains one item! the e+aluation re?uires one natural recursion, For two items! we recur twice, For a list with / items! the e+aluation re?uires / steps, -ot all )unctions ha+e such a uni)orm measure )or their abstract running time, Ta.e a loo. at our )irst recursi+e )unction:
!define"!contains-do++A"a-+ist-of-s2m8o+s# ""!cond """"9!empt2A"a-+ist-of-s2m8o+s#"fa+se: """"9else"!cond """"9!s2m8o+&A"!first"a-+ist-of-s2m8o+s#"'do++#"tr.e: """"9else"!contains-do++A"!rest"a-+ist-of-s2m8o+s##:#:##

I) we e+aluate
!contains-do++A"!+ist"'do++"'ro8ot"'8a++"'game-8o2"'po-emon##

the application re?uires no natural recursion step, In contrast! )or the e8pression
!contains-do++A"!+ist"'ro8ot"'8a++"'game-8o2"'po-emon"'do++##

the e+aluation re?uires as man$ natural recursion steps as there are items in the list, Put di))erentl$! in the best case! the )unction can )ind the answer immediatel$E in the worst case! the )unction must search the entire input list, Programmers cannot assume that inputs are alwa$s o) the best posisble shapeE and the$ must hope that the inputs are not o) the worst possible shape, Instead! the$ must anal$*e how much time their )unctions ta.e on the a+erage, For e8ample! contains-do++A ma$ 22 on the a+erage 22 )ind 'do++ somewhere in the middle o) the list, Thus! we could sa$ that i) the input contains / items! the abstract running time o) contains-do++A is /roughl$0

22 that is! it naturall$ recurs hal) as o)ten as the number o) items on the input, Because we alread$ measure the running time o) a )unction in an abstract manner! we can ignore the di+ision b$ &, More precisel$! we assume that each basic step ta.es = units o) time, I)! instead! we use =K& as the constant! we can calculate

which shows that we can ignore other constant )actors, To indicate that we are hiding such constants we sa$ that contains-do++A ta.es DDon the order o) / stepsCC to )ind 'do++ in a list o) / items, -ow consider our standard sorting )unction )rom )igure 55, Here is a hand2e+aluation )or a small input:
""!sort"!+ist"3"1"2## &"!insert"3"!sort"!+ist"1"2### &"!insert"3"!insert"1"!sort"!+ist"2#### &"!insert"3"!insert"1"!insert"2"!sort"empt2#### &"!insert"3"!insert"1"!insert"2"empt2### &"!insert"3"!insert"1"!+ist"2### &"!insert"3"!cons"2"!insert"1"empt2### &"!insert"3"!+ist"2"1## &"!insert"3"!+ist"2"1## &"!+ist"3"2"1#

The e+aluation is more complicated than those )or how-man2 or contains-do++A, It also consists o) two phases, During the )irst one! the natural recursions )or sort set up as man$ applications o) insert as there are items in the list, During the second phase!

each application o) insert tra+erses a list o) (! &! 5! ... up to the number o) items in the original list /minus one0, Inserting an item is similar to )inding an item! so it is not surprising that insert beha+es li.e contains-do++A, More speci)icall$! the applications o) insert to a list o) / items ma$ trigger / natural recursions or none, @n the a+erage! we assume it re?uires /K&! which means on the order o) /, Because there are / applications o) insert! we ha+e an a+erage o) on the order o) /& natural recursions o) insert, In summar$! i) + contains / items! e+aluating !sort"+# alwa$s re?uires / natural recursions o) sort and on the order o) /& natural recursions o) insert, Ta.en together! we get

steps! but we will see in e8ercise &>,&,( that this is e?ui+alent to sa$ing that insertion sort re?uires on the order o) /& steps, @ur )inal e8ample is the )unction ma*i:
66"ma*i":"ne-+ist-of-n.m8ers""-/""n.m8er 66"to"determine"the"ma*im.m"of"a"non-empt2"+ist"of"n.m8ers" !define"!ma*i"a+on# ""!cond """"9!empt2A"!rest"a+on##"!first"a+on#: """"9else"!cond """"9!/"!ma*i"!rest"a+on##"!first"a+on##"!ma*i"!rest"a+on##: """"9else"!first"a+on#:#:##

In e8ercise (<,(,(&! we in+estigated its beha+ior and the beha+ior o) an obser+ationall$ e?ui+alent )unction that uses local, Here we stud$ its abstract running time rather than Fust obser+e some concrete running time, "etCs start with a small e8ample: !ma*i"!+ist"%"1"2"3##, 1e .now that the result is 3, Here is the )irst important step o) a hand2e+aluation:
""!ma*i"!+ist"%"1"2"3## &"!cond """"9!/"! """ ma*i"! " ""+ist "" "" 1"" 2"" 3"""%#"! ## " """ ma*i"! " ""+ist "" "" 1"" 2"" 3"": ## " """"9else"%:#

From here! we must e+aluate the le)t o) the two underlined natural recursions, Because the result is 3 and the condition is thus tr.e! we must e+aluate the second underlined natural recursion as well, Focusing on Fust the natural recursion we see that its hand2e+aluation begins with similar steps:

""!ma*i"!+ist"1"2"3## &"!cond """"9!/"!ma*i"!+ist"2"3##"1#"!ma*i"!+ist"2"3##: """"9else"1:#

Again! !ma*i"!+ist"2"3## is e+aluated twice because it produces the ma8imum, Finall$! e+en determining the ma8imum o) !ma*i"!+ist"2"3## re?uires two natural recursions:
""!ma*i"!+ist"2"3## &"!cond """"9!/"!ma*i"!+ist"3##"2#"!ma*i"!+ist"3##: """"9else"2:#

To summari*e! ma*i re?uires two natural recursions )or each application, The )ollowing table counts the instances )or our e8ample: original e8pression
!ma*i"!+ist"1"2"3## !ma*i"!+ist"2"3##

re?uires & e+aluations o)


!ma*i"!+ist"2"3## !ma*i"!+ist"3##

!ma*i"!+ist"%"1"2"3## !ma*i"!+ist"1"2"3##

Altogether the hand2e+aluation re?uires eight natural recursions )or a list o) )our items, I) we add 4 /or a larger number0 at the end o) the list! we need to double the number o) natural recursions, Thus! in general we need on the order o) recursions )or a list o) / numbers when the last number is the ma8imum,95 1hile the scenario we considered is the worst possible case! the anal$sis o) ma*iCs abstract running time e8plains the phenomenon we studied in e8ercise (<,(,(&, It also e8plains wh$ a +ersion o) ma*i that uses a local2e8pression to name the result o) the natural recursion is )aster:
66"ma*i2":"ne-+ist-of-n.m8ers""-/""n.m8er 66"to"determine"the"ma*im.m"of"a"+ist"of"n.m8ers" !define"!ma*i2"a+on# ""!cond """"9!empt2A"!rest"a+on##"!first"a+on#: """"9else"!local"!!define"ma*-of-rest"!ma*i2"!rest"a+on#### """"!cond """"""9!/"ma*-of-rest"!first"a+on##"ma*-of-rest: """"""9else"!first"a+on#:#:###

Instead o) recomputing the ma8imum o) the rest o) the list! this +ersion Fust re)ers to the +ariable twice when the +ariable stands )or the ma8imum o) the rest o) the list, E ercise 2-<1<1< A number tree is either a number or a pair o) number trees, De+elop the )unction s.m-tree! which determines the sum o) the numbers in a tree, How should we measure the si*e o) a treeH 1hat is its abstract running timeH Solution

E ercise 2-<1<2< Hand2e+aluate !ma*i2"!+ist"%"1"2"3## in a manner similar to our e+aluation o) !ma*i"!+ist"%"1"2"3##, 1hat is the abstract running time o) ma*i2H Solution

"6#" The Definition of AAon the ;rder of>>


It is time to introduce a rigorous description o) the phrase DDon the order o)CC and to e8plain wh$ it is acceptable to ignore some constants, An$ serious programmer must be thoroughl$ )amiliar with this notion, It is the most )undamental method )or anal$*ing and comparing the beha+ior o) programs, This interme**o pro+ides a )irst glimpse at the ideaE a second course on computing usuall$ pro+ides some more in2depth considerations,

Figure ).' A comparison o) two running time e8pressions "etCs consider a sample DDorder o)CC claim with concrete e8amples be)ore we agree on a de)inition, Recall that a )unction > ma$ re?uire on the order o) / steps and a )unction G /& steps! e+en though both compute the same results )or the same inputs, -ow suppose the basic time constants are 1%%% )or > and ( )or G, @ne wa$ to compare the two claims is to tabulate the abstract running time: / ( (' 7' ('' 7'' (''' > /(''' P /0 (''' ('''' 7'''' (''''' 7''''' ('''''' G // P / 0 ( ('' &7'' ('''' &7'''' (''''''

At )irst glance the table seems to sa$ that GCs per)ormance is better than >Cs! because )or inputs o) the same si*e //0! GCs running time is alwa$s smaller than >Cs, But a closer loo. re+eals that as the inputs get larger! GCs ad+antage decreases, Indeed! )or an input o) si*e ('''! the two )unctions need the same number o) steps! and therea)ter G is alwa$s slower than >, Figure <' compares the graphs o) the two e8pressions, It shows that the linear graph )or (''' P / dominates the cur+e o) / P / )or some )inite number o) points but therea)ter it is below the cur+e, The concrete e8ample recalls two important )acts about our in)ormal discussion o) abstract running time, First! our abstract description is alwa$s a claim about the relationship between two ?uantities: the si*e o) the input and the number o) natural recursions e+aluated, More precisel$! the relationship is a /mathematical0 )unction that maps an abstract si*e measure o) the input to an abstract measure o) the running time, Second! when we compare DDon the order o)CC properties o) )unctions! such as

we reall$ mean to compare the corresponding )unctions that consume / and produce the abo+e results, In short! a statement concerning the order o) things compares two )unctions on natural numbers /N0, The comparison o) )unctions on N is di))icult because the$ are in)inite, I) a )unction f produces larger outputs than some other )unction g )or all natural numbers! then f is clearl$ larger than g, But what i) this comparison )ails )or Fust a )ew inputsH @r )or (!''' such as the one illustrated in )igure <'H Because we would still li.e to ma.e appro8imate Fudgments! programmers and scientists adapt the mathematical notion o) comparing )unctions up to some )actor and some )inite number o) e8ceptions, @RD#R2@F /BI=2@0: =i+en a )unction g on the natural numbers! 8/g0 /pronounced: DDbig2@ o) gCC0 is a class o) )unctions on natural numbers, A )unction f is in 8/g0 i) there e8ist numbers c and big)no gh such that )or all n S big)no gh! it is true that Recall the per)ormance o) 9 and > abo+e, For the )irst! we assumed that it consumed time according to the )ollowing )unction

the per)ormance o) second one obe$ed the )unction g:

Asing the de)inition o) big2@! we can sa$ that f is 8/g0! because )or all n S ('''!

which means big)no gh O (''' and c O (,

More important! the de)inition o) big2@ pro+ides us with a shorthand )or stating claims about a )unctionCs running time, For e8ample! )rom now on! we sa$ how-man2Cs running time is 8//0, eep in mind that / is the standard abbre+iation o) the /mathematical0 )unction g//0 O /, Similarl$! we can sa$ that! in the worst case! sortCs running time is 8//&0 and ma*iCs is 8/&/0, Finall$! the de)inition o) big2@ e8plains wh$ we donCt ha+e to pa$ attention to speci)ic constants in our comparsions o) abstract running time, Consider ma*i and ma*i2, 1e .now that ma*iCs worst2case running time is in 8/&/0! ma*i2Cs is in 8//0, Sa$! we need the ma8imum o) a list with (' numbers, Assuming ma*i and ma*i2 roughl$ consume the same amount o) time per basic step! ma*i will need &(' O ('&6 steps and ma*i2 will need (' steps! which means ma*i2 will be )aster, -ow e+en i) ma*i2Cs basic step re?uires twice as much time as ma*iCs basic step! ma*i2 is still around 7' times )aster, Futhermore! i) we double the si*e o) the input list! ma*iCs apparent disad+antage totall$ disappears, In general! the larger the input is! the less rele+ant are the speci)ic constants, E ercise 2-<2<1< In the )irst subsection! we stated that the )unction f/n0 O n& I n belongs to the class 8/n&0, Determine the pair o) numbers c and big)no gh that +eri)$ this claim, Solution E ercise 2-<2<2< Consider the )unctions f/n0 O &n and g/n0 O (''' P n, Show that g belongs to 8/f0! which means that f is abstractl$ spea.ing more /or at least e?uall$0 e8pensi+e than g, I) the input si*e is guaranteed to be between 5 and (&! which )unction is betterH Solution E ercise 2-<2<!< Compare f/n0 O n log n and g/n0 O n&, Does f belong to 8/g0 andKor g to 8/f0H Solution

"6#(

+irst Look at 'ectors

Antil now we ha+e paid little attention to how much time it ta.es to retrie+e data )rom structures or lists, -ow that we ha+e a tool )or stating general Fudgments! letCs ta.e a close loo. at this basic computation step, Recall the last problem o) the preceding part: )inding a route in a graph, The program find-ro.te re?uires two au8iliaries: findro.te/+ist and neigh8ors, 1e paid a lot o) attention to find-ro.te/+ist and none to neigh8ors, Indeed! de+eloping neigh8ors was Fust an e8ercise /see &<,(,&0! because loo.ing up a +alue in a list is b$ now a routine programming tas., Here is a possible de)inition )or neigh8ors:
66"neigh8ors":"node"graph""-/""!listof"node# 66"to"+oo-.p"the"node"in"graph !define"!neigh8ors"node"graph# ""!cond """"9!empt2A"graph#"!error"'neigh8ors"1canKt"happen1#:

""""9else"!cond """"9!s2m8o+&A"!first"!first"graph##"node#"!second"!first graph##: """"9else"!neigh8ors"node"!rest"graph##:#:##

The )unction is similar to contains-do++A and has roughl$ the same beha+ior, More concretel$! neigh8ors is 8//0 when we assume that graph is a list o) / nodes, Considering that neigh8ors is used at e+er$ stage o) the e+aluation o) find-ro.te! neigh8ors is possibl$ a bottlenec., As a matter o) )act! i) the route we are loo.ing )or in+ol+es J nodes /the ma8imum0! neigh8ors is applied / times! so the algorithm re?uires 8//&0 steps in neigh8ors, In contrast to lists! structures deal with +alue e8tractions as a constant time operation, At )irst glance this obser+ation seems to suggest that we use structures as representations o) graphs, A closer loo.! howe+er! shows that this idea doesnCt wor. easil$, The graph algorithm wor.s best i) we are able to wor. with the names o) nodes and access a nodeCs neighbors based on the name, A name could be a s$mbol or the nodeCs number in the graph, In general! what we reall$ wish to ha+e in a programming language is a class o) compound +alues si*e with constant loo.up time! based on DD.e$s,CC Because the problem is so common! Scheme and most other languages o))er at least one built2in solution, Here we stud$ the class o) vectors, A +ector is a well2de)ined mathematical class o) data with speci)ic basic operations, For our purposes! it su))ices to .now how to construct them! how to e8tract +alues! and how to recogni*e them: (, The operation 0ector is li.e +ist, It consumes an arbitrar$ number o) +alues and creates a compound +alue )rom them: a +ector, For e8ample! !0ector"W%"..."W-n# creates a +ector )rom W-% through W-n, &, DrScheme also pro+ides a +ector analogue to 8.i+d-+ist, It is called 8.i+d0ector, Here is how it wor.s:
3. !8.i+d-0ector"J"f#"&"!0ector"!f"%#"..."!f"!-"J"1###

That is! 8.i+d-0ector consumes a natural number J and a )unction f on natural numbers, It then builds a +ector o) J items b$ appl$ing f to %! ...! J-1, 6, The operation 0ector-ref e8tracts a +alue )rom a +ector in constant time! that is! )or i between % and n /inclusi+e0:
5. !0ector-ref"!0ector"W-%"..."W-n#"i#"&"W-i

In short! e8tracting +alues )rom a +ector is 8/(0,

I) 0ector-ref is applied to a +ector and a natural number that is smaller than % or larger than n! 0ector-ref signals an error, 9, The operation 0ector-+ength produces the number o) items in a +ector:
7. !0ector-+ength"!0ector"W-%"..."W-n##"&"!+"n"1#

<, The operation 0ectorA is the +ector2predicate:


,. !0ectorA"!0ector"W-%"..."W-n##"&"tr.e 1%.!0ectorA"P#"&"fa+se

i) P is a +alue that isnCt created with 0ector, 1e can thin. o) +ectors as )unctions on a small! )inite range o) natural numbers, Their range is the )ull class o) Scheme +alues, 1e can also thin. o) them as tables that associate a small! )inite range o) natural numbers with Scheme +alues, Asing +ectors we can represent graphs li.e those in )igures ;9 and ;< i) we use numbers as names, For e8ample: A BCD#F= ' ( & 5 6 7 9 Asing this translation! we can also produce a +ector2based representation o) the graph in )igure ;9:
!define"Graph-as-+ist ""'!!'"!("5## """"!("!5">## """"!7"!D## """"!D"!## """"!5"!7">## """"!>"!D"G## """"!G"!#### !define"Graph-as-0ector ""!0ector"!+ist"1"4# """"""""""!+ist"4"5# ""!+ist"3# ""empt2 ""!+ist"2"5# ""!+ist"3" # ""empt2##

The de)inition on the le)t is the original list2based representationE the one on the right is a +ector representation, The +ectorCs i2th )ield contains the list o) neighbors o) the i2th node, The data de)initions )or node and graph change in the e8pected manner, "etCs assume that / is the number o) nodes in the gi+en graph: A node is an natural number between ' and / - (, A graph is a +ector o) nodes: !vectorof"!listof"node##, The notation !vectorof"R# is similar to !listof"R#, It denotes a +ector that contains items )rom some undetermined class o) data R,

-ow we can rede)ine neigh8ors:


66"neigh8ors":"node"graph""-/""!listof"node# 66"to"+oo-.p"the"node"in"graph !define"!neigh8ors"node"graph# ""!0ector-ref"graph"node##

As a result! loo.ing up the neighbors o) a node becomes a constant2time operation! and we can trul$ ignore it when we stud$ the abstract running time o) find-ro.te, E ercise 2-<!<1< Test the new neigh8ors )unction, Ase the strateg$ o) section (;,< to )ormulate the tests as boolean e8pressions, Solution E ercise 2-<!<2< Adapt the rest o) the find-ro.te program to the new +ector representation, Adapt the tests )rom e8ercises &<,(,5 through &<,(,7 to chec. the new program, Measure how much time the two find-ro.te programs consume to compute a route )rom node A to node # in the graph o) )igure ;9, Recall that !time"e*pr# measures how long it ta.es to e+aluate e*pr, It is good practice to e+aluate e*pr! sa$! (''' times when we measure time, This produces more accurate measurements, Solution E ercise 2-<!<!< Translate the c$clic graph )rom )igure ;< into our +ector representation o) graphs, Solution Be)ore we can trul$ program with +ectors! we must understand the data de)inition, The situation is comparable to that when we )irst encountered lists, 1e .now that 0ector! li.e cons! is pro+ided b$ Scheme! but we donCt ha+e a data de)inition that directs our program de+elopment e))orts, So! let us ta.e a loo. at +ectors, Roughl$ spea.ing! 0ector is li.e cons, The cons primiti+e constructs lists! the 0ector primiti+e creates +ectors, Since programming with lists usuall$ means programming with the selectors first and rest! programming with +ectors must mean programming with 0ector-ref, Anli.e first and rest! howe+er! 0ector-ref re?uires manipulating the +ector and an inde8 into a +ector, This suggests that programming with +ectors reall$ means thin.ing about indices! which are natural numbers, "etCs loo. at some simple e8amples to con)irm this abstract Fudgment, Here is the )irst one:
66"0ector-s.m-for-3":"!0ector"n.m8er"n.m8er"n.m8er#""-/""n.m8er !define"!0ector-s.m-for-3"0# ""!+"!0ector-ref"0"%#

"""""!0ector-ref"0"1# """""!0ector-ref"0"2###

The )unction 0ector-s.m-for-3 consumes +ectors o) three numbers and produces their sum, It uses 0ector-ref to e8tract the three numbers and adds them up, 1hat +aries in the three selector e8pressions is the inde8E the +ector remains the same, Consider a second! more interesting e8ample: 0ector-s.m! a generali*ation o) 0ectors.m-for-3, It consumes an arbitraril$ large +ector o) numbers and produces the sum o) the numbers:
66"0ector-s.m":"!vectorof"n.m8er#""-/""n.m8er 66"to"s.m".p"the"n.m8ers"in"0 !define"!0ector-s.m"0#"...#

Here are some e8amples:


!&"!0ector-s.m"!0ector"-1"3/4"1/4## """%# !&"!0ector-s.m"!0ector".1".1".1".1".1".1".1".1".1".1## """1# !&"!0ector-s.m"!0ector## """%#

The last e8ample suggests that we want a reasonable answer e+en i) the +ector is empt$, As with empt2! we use % as the answer in this case, The problem is that the one natural number associated with 0! its length! is not an argument o) 0ector-s.m, The length o) 0 is o) course Fust an indication o) how man$ items in 0 are to be processed! which in turn re)ers to legal indices o) 0, This reasoning )orces us to de+elop an au8iliar$ )unction that consumes the +ector and a natural number:
66"0ector-s.m-a.*":"!vectorof"n.m8er#"N""-/""n.m8er 66"to"s.m".p"the"n.m8ers"in"0"re+ati0e"to"i" !define"!0ector-s.m-a.*"0"i#"...#

The natural choice )or the initial +alue o) i is the length o) 0! which suggests the )ollowing completion o) 0ector-s.m:
!define"!0ector-s.m"0#" ""!0ector-s.m-a.*"0"!0ector-+ength"0###

Based on this de)inition! we can also adapt the e8amples )or 0ector-s.m to 0ectors.m-a.*:
!&"!0ector-s.m-a.*"!0ector"-1"3/4"1/4#"3# """%# !&"!0ector-s.m-a.*"!0ector".1".1".1".1".1".1".1".1".1".1#"1%# """1#

!&"!0ector-s.m-a.*"!0ector#"%# """%#

An)ortunatel$! this doesnCt clari)$ the role o) the second argument, To do that! we need to proceed to the ne8t stage o) the design process: template de+elopment, 1hen we de+elop templates )or )unctions o) two arguments! we must )irst decide which o) the arguments must be processed! that is! which o) the two will +ar$ in the course o) a computation, The 0ector-s.m-for-3 e8ample suggests that it is the second argument in this case, Because this argument belongs to the class o) natural numbers! we )ollow the design recipe )or those:
!define"!0ector-s.m-a.*"0"i#" ""!cond """"9!@eroA"i#"...: """"9else"..."!0ector-s.m-a.*"0"!s.81"i##"...:##

Although we considered i to be the length o) the +ector initiall$! the template suggests that we should consider it the number o) items o) 0 that 0ector-s.m-a.* must consider and thus as an inde8 into 0, The elaboration o) iCs use naturall$ leads to a better purpose statement )or 0ector-s.ma.*:
66"0ector-s.m-a.*":"!vectorof"n.m8er#"N""-/""n.m8er 66"to"s.m".p"the"n.m8ers"in"0"with"inde*"in"9%<"i# !define"!0ector-s.m-a.*"0"i#" ""!cond """"9!@eroA"i#"...: """"9else"..."!0ector-s.m-a.*"0"!s.81"i##"...:##

#8cluding i is natural because it is initiall$ !0ector-+ength"0# and thus not an inde8,

66"0ector-s.m":"!vectorof"n.m8er#""-/""n.m8er 66"to"comp.te"the"s.m"of"the"n.m8ers"in"0 !define"!0ector-s.m"0#" ""!0ector-s.m-a.*"0"!0ector-+ength"0### 66"0ector-s.m-a.*":"!vectorof"n.m8er#"N""-/""n.m8er 66"to"s.m"the"n.m8ers"in"0"with"inde*"in"9%<"i# !define"!0ector-s.m-a.*"0"i#" ""!cond """"9!@eroA"i#"%: """"9else"!+"!0ector-ref"0"!s.81"i##"

/+ector2sum2au8 + /sub( i000W00 Figure )1' Summing up the numbers in a +ector /+ersion (0
66"+r-0ector-s.m":"!vectorof"n.m8er#""-/""n.m8er 66"to"s.m".p"the"n.m8ers"in"0 !define"!+r-0ector-s.m"0# ""!0ector-s.m-a.*"0"%## 66"0ector-s.m":"!vectorof"n.m8er#""-/""n.m8er 66"to"s.m".p"the"n.m8ers"in"0"with"inde*"in"9i<"!0ector-+ength"0## !define"!0ector-s.m-a.*"0"i# ""!cond """"9!&"i"!0ector-+ength"0##"%:

Velse /I /+ector2re) + i0 /+ector2sum2au8 + /add( i000W00 Figure )2' Summing up the numbers in a +ector /+ersion &0 To trans)orm the template into a complete )unction de)inition! we consider each clause o) the cond: (, I) i is %! there are no )urther items to be considered because there are no +ector )ields between % and i with i e8cluded, There)ore the result is %, &, @therwise! !0ector-s.m-a.*"0"!s.81"i## computes the sum o) the numbers in 0 between % and !s.81"i# Ve8clusi+eW, This lea+es out the +ector )ield with inde8 !s.81"i#! which according to the purpose statement must be included, B$ adding !0ector-ref"0"!s.81"i##! we get the desired result:
3. !+"!0ector-ref"0"!s.81"i##"!0ector-s.m-a.*"0"!s.81"i###

See )igure <( )or the complete program, I) we were to e+aluate one o) the e8amples )or 0ector-s.m-a.* b$ hand! we would see that it e8tracts the numbers )rom the +ector in a right to le)t order as i decreases to %, A natural ?uestion is whether we can in+ert this order, In other words: is there a )unction that e8tracts the numbers in a le)t to right orderH The answer is to de+elop a )unction that processes the class o) natural numbers below !0ector-+ength"0# and to start at the )irst )easible inde8: %, De+eloping this )unction is Fust another instance o) the design recipe )or +ariants o) natural numbers )rom

section ((,6, The new )unction de)inition is shown in )igure <&, The new au8iliar$ )unction now consumes % and counts up to !0ector-+ength"0#, A hand2e+aluation o)
!+r-0ector-s.m"!0ector"%"1"2"3##

shows that 0ector-s.m-a.* indeed e8tracts the items )rom 0 )rom le)t to right, The de)inition o) +r-0ector-s.m shows wh$ we need to stud$ alternati+e de)initions o) classes o) natural numbers, Sometimes it is necessar$ to count down to %, But at other times it is e?uall$ use)ul! and natural! to count )rom % up to some other number, The two )unctions also show how important it is to reason about inter+als, The au8iliar$ +ector2processing )unctions process inter+als o) the gi+en +ector, A good purpose statement speci)ies the e8act inter+al that the )unction wor.s on, Indeed! once we understand the e8act inter+al speci)ication! )ormulating the )ull )unction is relati+el$ straight)orward, 1e will see the importance o) this point when we return to the stud$ o) +ector2processing )unctions in the last section, E ercise 2-<!<#< #+aluate !0ector-s.m-a.*"!0ector"-1"3/4"1/4#"3# b$ hand, Show the maFor steps onl$, Chec. the e+aluation with DrSchemeCs stepper, In what order does the )unction add up the numbers o) the +ectorH Ase a local2e8pression to de)ine a single )unction 0ector-s.m, Then remo+e the +ector argument )rom the inner )unction de)inition, 1h$ can we do thatH Solution E ercise 2-<!<$< #+aluate !+r-0ector-s.m"!0ector"-1"3/4"1/4## b$ hand, Show the maFor steps onl$, Chec. the e+aluation with DrSchemeCs stepper, In what order does the )unction add up the numbers o) the +ectorH Ase a local2e8pression to de)ine a single )unction +r-0ector-s.m, Then remo+e those arguments )rom the inner )unction de)inition that remain the same during an e+aluation, Also introduce de)initions )or those e8pressions that alwa$s e+aluate to the same +alue during the e+aluation, 1h$ is this use)ulH Solution E ercise 2-<!<&< The list2based analogue o) 0ector-s.m is +ist-s.m:
66"+ist-s.m":"!listof"n.m8er#""-/""n.m8er" 66"to"comp.te"the"s.m"of"the"n.m8ers"on"a+on !define"!+ist-s.m"a+on# ""!+ist-s.m-a.*"a+on"!+ength"a+on### 66"+ist-s.m-a.*":"N"!listof"n.m8er#""-/""n.m8er" 66"to"comp.te"the"s.m"of"the"first"L"n.m8ers"on"a+on !define"!+ist-s.m-a.*"L"a+on# ""!cond

""""9!@eroA"L#"%: """"9else"!+"!+ist-ref"a+on"!s.81"L##"!+ist-s.m-a.*"!s.81"L# a+on##:##

Instead o) using the structural de)inition o) the list! the de+eloper o) this program used the si*e o) the list 22 a natural number 22 as the guiding element in the design process, The resulting de)inition uses SchemeCs +ist-ref )unction to access each item on the list, "oo.ing up an item in a list with +ist-ref is an 8//0 operation )or lists o) / items, Determine the abstract running time o) s.m /)rom section >,70! 0ector-s.m-a.* and +ist-s.m-a.*, 1hat does this suggest about program de+elopmentH Solution E ercise 2-<!<(< De+elop the )unction norm! which consumes a +ector o) numbers and produces the s?uare root o) the sum o) the s?uares o) its numbers, Another name )or norm is distance-to-%! because the result is the distance o) a +ector to the origin! when we interpret the +ector as a point, Solution E ercise 2-<!<)< De+elop the )unction 0ector-contains-do++A, It consumes a +ector o) s$mbols and determines whether the +ector contains the s$mbol 'do++, I) so! it produces the inde8 o) 'do++Cs )ieldE otherwise! it produces fa+se, Determine the abstract running time o) 0ector-contains-do++A and compare with that o) contains-do++A! which we discussed in the preceding subsection, -ow discuss the )ollowing problem, Suppose we are to represent a collection o) s$mbols, The onl$ interesting problem concerning the collection is to determine whether it contains some gi+en s$mbol, 1hich data representation is pre)erable )or the collection: lists or +ectorsH 1h$H Solution E ercise 2-<!<-< De+elop the )unction 8inar2-containsA, It consumes a sorted +ector o) numbers and a .e$! which is also a number, The goal is to determine the inde8 o) the .e$! i) it occurs in the +ector! or fa+se, Ase the binar$2search algorithm )rom section &;,5, Determine the abstract running time o) 8inar2-containsA and compare with that o) containsA! the )unction that searches )or a .e$ in a +ector in the linear )ashion o) 0ector-contains-do++A, Suppose we are to represent a collection o) numbers, The onl$ interesting problem concerning the collection is to determine whether it contains some gi+en number, 1hich data representation is pre)erable )or the collection: lists or +ectorsH 1h$H Solution

E ercise 2-<!<1.< De+elop the )unction 0ector-co.nt, It consumes a +ector 0 o) s$mbols and a s$mbol s, Its result is the number o) s that occur in 0, Determine the abstract running time o) 0ector-co.nt and compare with that o) co.nt! which counts how man$ times s occurs in a list o) s$mbols, Suppose we are to represent a collection o) s$mbols, The onl$ interesting problem concerning the collection is to determine how man$ times it contains some gi+en s$mbol, 1hich data representation is pre)erable )or the collection: lists or +ectorsH 1h$H 1hat do e8ercises &>,5,<! &>,5,>! and this e8ercise suggestH Solution 1hile accessing the items o) a +ector is one .ind o) programming problem! constructing +ectors is an entirel$ di))erent problem, 1hen we .now the number o) items in a +ector! we can construct it using 0ector, 1hen we we wish to write programs that wor. on a large class o) +ectors independent o) their si*e! howe+er! we need 8.i+d-0ector, Consider the )ollowing simple e8ample, Suppose we represent the +elocit$ o) an obFect with a +ector, For e8ample! !0ector"1"2# represents the +elocit$ o) an obFect on a plane that mo+es 1 unit to the right and 2 down in each time unit, For comparison! !0ector"-1"2"1# is the +eloicit$ o) an obFect in spaceE it mo+es - units in the + direction in 9 time units! 12 units in the y direction in 9 time units! and units in the ' direction in 9 time units, 1e call !0ector"- "12" # the disp!acement o) the obFect in 9 time units, "etCs de+elop a )unction that computes the displacement )or an obFect with some +elocit$ 0 in t time units:
66"disp+acement":"!vectorof"n.m8er#"n.m8er""-/""!vectorof"n.m8er# 66"to"comp.te"the"disp+acement"of"0"and"t !define"!disp+acement"0"t#"...#

Computing the displacement is straight)orward )or some e8amples:


!e).a+A"!disp+acement"!0ector"1"2#"3#" """"""""!0ector"3" ## !e).a+A"!disp+acement"!0ector"-1"2"1#" #" """"""""!0ector"- "12" ## !e).a+A"!disp+acement"!0ector"-1"-2#"2#" """"""""!0ector"-2"-4##

1e Fust multipl$ each component o) the obFect with the number! which $ields a new +ector, The e8amplesC meaning )or our programming problem is that disp+acement must construct a +ector o) the same length as 0 and must use the items in 0 to compute those

o) the new +ectors, Here is how we build a +ector o) the same how2man$ as some gi+en +ector 0:
!8.i+d-0ector"!0ector-+ength"0#"...#

-ow we need to replace ... with a )unction that computes the %2th! 12st! and so on items o) the new +ector:
66"new-item":""N""-/""n.m8er 66"to"comp.te"the"contents"of"the"new"0ector"at"the"i-th"position !define"!new-item"inde*#"...#

Following our discussion! we multipl$ !0ector-ref"0"i# with t and thatCs all, Ta.e a loo. at the complete de)inition:
66"disp+acement":"!vectorof"n.m8er#"n.m8er""-/""!vectorof"n.m8er# 66"to"comp.te"the"disp+acement"of"0"and"t !define"!disp+acement"0"t# ""!local"!!define"!new-item"i#"!*"!0ector-ref"0"i#"t### """"!8.i+d-0ector"!0ector-+ength"0#"new-item###

The locall$ de)ined )unction is not recursi+e, 1e can thus replace it with a plain lambda2e8pression:
66"disp+acement":"!vectorof"n.m8er#"n.m8er""-/""!vectorof"n.m8er# 66"to"comp.te"the"disp+acement"of"0"and"t !define"!disp+acement"0"t# ""!8.i+d-0ector"!0ector-+ength"0#"!lambda"!i#"!*"!0ector-ref"0"i# t####

Mathematicians call this )unction sca!ar prod ct, The$ ha+e also studied man$ other operations on +ectors! and in Scheme we can de+elop those in a natural manner, E ercise 2-<!<11< De+elop the )unction id-0ector! which consumes a natural number and produces a +ector o) that man$ 1Cs, Solution E ercise 2-<!<12< De+elop the )unctions 0ector+ and ,ector"-"! which compute the pointwise sum and di))erences o) two +ectors, That is! each consumes two +ectors and produces a +ector b$ manipulating corresponding programs, Assume the gi+en +ectors are o) the same length, Also de+elop the )unctions chec-ed-0ector+ and chec+ed! ,ector"-", Solution E ercise 2-<!<1!< De+elop the )unction distance! which consumes two +ectors and computes their distance, Thin. o) the distance o) two +ectors as the length o) the line between them, Solution

E ercise 2-<!<1#< De+elop a +ector representation )or chessboards o) si*e n Y n )or n in N, Then de+elop the )ollowing two )unctions on chessboards:
66"8.i+d-8oard":"N"!N"N""-/""8oo+ean#""-/""8oard 66"to"create"a"8oard"of"si@e"n"*"n<" 66"fi++"each"position"with"indices"i"and"S"with"!f"i"S# !define"!8.i+d-8oard"n"f#"...# 66"8oard-ref":"8oard"N"N""-/""8oo+ean 66"to"access"a"position"with"indices"i<"S"on"a-8oard !define"!8oard-ref"a-8oard"i"S#"...#

Can we now run the program o) section &<,& using +ectors instead o) listsH Inspect the solution o) e8ercises &<,&,5 and &<,&,6, Solution E ercise 2-<!<1$< A matri8 is a chessboard o) numbers, Ase the chessboard representation o) e8ercise &>,5,(6 to represent the matri8

Asing 8.i+d-8oard! de+elop the )unction transpose! which creates a mirror image o) the matri8 along its diagonal )rom the upper2le)t corner to the lower2right one, For e8ample! the gi+en matri8 turns into

More generall$! the item at /i!30 becomes the item at /3!i0,

Solution

1e spea. o) an abstract running time because the measure ignores the details o) how much time primiti+e steps ta.e and how much time the o+erall e+aluation ta.es,
9&

95

More precisel$! the e+aluation consists o) &/-( steps! but

which shows that we ignore a /small0 constant when we sa$ on the order o) &/,

Part "I +ccumulating 7no3ledge Section !. The ,oss of 7no3ledge


1hen we design recursi+e )unctions! we donCt thin. about the conte8t o) their use, 1hether the$ are applied )or the )irst time or whether the$ are called )or the hundredth time in a recursi+e manner doesnCt matter, The$ are to wor. according to their purpose statement! and thatCs all we need to .now as we design the bodies o) the )unctions, Altough this principle o) conte8t2independence greatl$ )acilitates the de+elopment o) )unctions! it also causes occasional problems, In this section! we illustrate the most important problem with two e8amples, Both concern the loss o) .nowledge that occurs during a recursi+e e+aluation, The )irst subsection shows how this loss ma.es a structurall$ recursi+e )unction more complicated and less e))icient than necessar$E the second one shows how the loss o) .nowledge causes a )atal )law in an algorithm,

(8#$

Pro&lem !ith Structural Processing

Suppose we are gi+en the relati+e distances between a series o) points! starting at the origin! and suppose we are to compute the absolute distances )rom the origin, For e8ample! we might be gi+en a line such as this:

#ach number speci)ies the distance between two dots, 1hat we need is the )ollowing picture! where each dot is annotated with the distance to the le)t2most dot:

66"re+ati0e-2-a8so+.te":"!listof"n.m8er#""-/""!listof"n.m8er# 66"to"con0ert"a"+ist"of"re+ati0e"distances"to"a"+ist"of"a8so+.te distances 66"the"first"item"on"the"+ist"represents"the"distance"to"the origin !define"!re+ati0e-2-a8so+.te"a+on# ""!cond """"9!empt2A"a+on#"empt2: """"9else"!cons"!first"a+on# """"""""!add-to-each"!first"a+on#"!re+ati0e-2-a8so+.te"!rest a+on####:## 66"add-to-each":"n.m8er"!listof"n.m8er#""-/""!listof"n.m8er# 66"to"add"n"to"each"n.m8er"on"a+on !define"!add-to-each"n"a+on# ""!cond """"9!empt2A"a+on#"empt2:

Velse /cons /I /)irst alon0 n0 /add2to2each n /rest alon000W00 Figure )!' Con+erting relati+e distances to absolute distances De+eloping a program that per)orms this calculation is at this point an e8ercise in structural )unction design, Figure <5 contains the complete Scheme program, 1hen the gi+en list is not empt2! the natural recursion computes the absolute distance o) the remainder o) the dots to the )irst item on !rest"a+on#, Because the )irst item is not the actual origin and has a distance o) !first"a+on# to the origin! we must add !first a+on# to each and e+er$ item on the result o) the recursi+e application, This second step! adding a number to each item on a list o) numbers! re?uires an au8iliar$ )unction, 1hile the de+elopment o) the program is straight)orward! using it on larger and larger lists re+eals a problem, Consider the e+aluation o) the )ollowing de)inition:96
!define"*"!re+ati0e-2-a8so+.te"!+ist"%"..."J###

As we increase J! the time needed grows e+en )aster:97 time o) e+aluation ('' &&' &'' <<' 5'' &'7' 6'' 7'>' 7'' ;6(' 9'' ('6&' ;'' (6';' <'' (<75' Instead o) doubling as we go )rom ('' to &'' items! the time ?uadruples, This is also the appro8imate relationship )or going )rom &'' to 6''! 5'' to 9''! and so on,
J

E ercise !.<1<1< Re)ormulate add-to-each using map and lambda,

Solution

E ercise !.<1<2< Determine the abstract running time o) re+ati0e-2-a8so+.te, >int' #+aluate the e8pression
!re+ati0e-2-a8so+.te"!+ist"%"..."J##

b$ hand, Start b$ replacing J with (! &! and 5, How man$ natural recursions o) re+ati0e-2-a8so+.te and add-to-each are re?uired each timeH Solution Considering the simplicit$ o) the problem! the amount o) DDwor.CC that the two )unctions per)orm is surprising, I) we were to con+ert the same list b$ hand! we would tall$ up the total distance and Fust add it to the relati+e distances as we ta.e another step along the line, "etCs attempt to design a second +ersion o) the )unction that is closer to our hand method, The new )unction is still a list2processing )unction! so we start )rom the appropriate template:
!define"!re+-2-a8s"a+on# ""!cond """"9!empt2A"a+on#"...: """"9else"..."!first"a+on#"..."!re+-2-a8s"!rest"a+on##"...:##

-ow imagine an DDe+aluationCC o) !re+-2-a8s"!+ist"3"2"7##:


""!re+-2-a8s"!+ist"3"2"7## &"!cons"..."3"... """"!con0ert"!+ist"2"7### &"!cons"..."3"... """"!cons"..."2"... """"""!con0ert"!+ist"7#### &"!cons"..."3"... """"!cons"..."2"... """"""!cons"..."7"... !con0ert"empt2####

The )irst item o) the result list should ob+iousl$ be 3! and it is eas$ to construct this list, But! the second one should be !+"3"2#! $et the second instance o) re+-2-a8s has no wa$ o) DD.nowingCC that the )irst item o) the original list is 3, The DD.nowledgeCC is lost, Put di))erentl$! the problem is that recursi+e )unctions are independent o) their conte8t, A )unction processes the list L in !cons"J"L# in the e8act same manner as L in !cons"\ L#, Indeed! it would also process L in that manner i) it were gi+en L b$ itsel), 1hile this propert$ ma.es structurall$ recursi+e )unctions eas$ to design! it also means that solutions are! on occasion! more complicated than necessar$! and this complication ma$ a))ect the per)ormance o) the )unction,

To ma.e up )or the loss o) DD.nowledge!CC we e?uip the )unction with an additional parameter: acc.-dist, The new parameter represents the accumulated distance! which is the tall$ that we .eep when we con+ert a list o) relati+e distances to a list o) absolute distances, Its initial +alue must be %, As the )unction processes the numbers on the list! it must add them to the tall$, Here is the re+ised de)inition:
!define"!re+-2-a8s"a+on"acc.-dist# ""!cond """"9!empt2A"a+on#"empt2: """"9else"!cons"!+"!first"a+on#"acc.-dist# """"""""!re+-2-a8s"!rest"a+on#"!+"!first"a+on#"acc.-dist###:##

The recursi+e application consumes the rest o) the list and the new absolute distance o) the current point to the origin, Although this means that two arguments are changing simultaneousl$! the change in the second one strictl$ depends on the )irst argument, The )unction is still a plain list2processing procedure, #+aluating our running e8ample with re+-2-a8s shows how much the use o) an accumulator simpli)ies the con+ersion process:
&"!re+-2-a8s"!+ist"3"2"7#"%# &"!cons"3"!re+-2-a8s"!+ist"2"7#"3## &"!cons"3"!cons"5"!re+-2-a8s"!+ist"7#"5### &"!cons"3"!cons"5"!cons"12"!re+-2-a8s"empt2"12#### &"!cons"3"!cons"5"!cons"12"empt2###

#ach item in the list is processed once, 1hen re+-2-a8s reaches the end o) the argument list! the result is completel$ determined and no )urther wor. is needed, In general! the )unction per)orms on the order o) / natural recursion steps )or a list with / items, @ne minor problem with the new de)inition is that the )unction consumes two arguments and is thus not e?ui+alent to re+ati0e-2-a8so+.te! a )unction o) one argument, 1orse! someone might accidentall$ misuse re+-2-a8s b$ appl$ing it to a list o) numbers and a number that isnCt %, 1e can sol+e both problems with a )unction de)inition that contains re+-2-a8s in a local de)inition: see )igure <6, -ow! re+ati0e-2-a8so+.te and re+ati0e-2-a8so+.te2 are indistinguishable,

/rel2&2abs alon '000 Figure )#' Con+erting relati+e distances with an accumulator

66"re+ati0e-2-a8so+.te2":"!listof"n.m8er#""-/""!listof"n.m8er# 66"to"con0ert"a"+ist"of"re+ati0e"distances"to"a"+ist"of"a8so+.te distances 66"the"first"item"on"the"+ist"represents"the"distance"to"the origin !define"!re+ati0e-2-a8so+.te2"a+on# ""!local"!!define"!re+-2-a8s"a+on"acc.-dist# """"!cond """"""9!empt2A"a+on#"empt2: """"""9else"!cons"!+"!first"a+on#"acc.-dist# """"""""""!re+-2-a8s"!rest"a+on#"!+"!first"a+on#"acc.dist###:###

(8#"

Pro&lem !ith 5enerative Recursion

"et us re+isit the problem o) )inding a path in a graph )rom section &<, Recall that we are gi+en a collection o) nodes and connections between nodes! and that we need to determine whether there is a route )rom a node labeled orig to one called dest, Here we stud$ the slightl$ simpler +ersion o) the problem o) simp!e graphs where each node has e8actl$ one /one2directional0 connection to another node, Consider the e8ample in )igure <7, There are si8 nodes: A through F! and si8 connections, To get )rom A to #! we go through B! C! and #, It is impossible! though! to reach F )rom A or )rom an$ other node /besides F itsel)0,

!define"Cimp+eG" ""'!!'"(# """"!("7# """"!7"5# """"!D"5# """"!5"(# """"!>">###""""

Figure )$' A simple graph The right part o) )igure <7 contains a Scheme de)inition that represents the graph, #ach node is represented b$ a list o) two s$mbols, The )irst s$mbol is the label o) the nodeE the second one is the reachable node, Here are the rele+ant data de)initions: A node is a s$mbol, A pair is a list o) two nodes:

!cons"C"!cons";"empt2##

where C! ; are s$mbols, A simp!e-graph is a list o) pairs:


!listof"pair#,

The$ are straight)orward translations o) our in)ormal descriptions, Finding a route in a graph is a problem o) generati+e recursion, 1e ha+e data de)initions! we ha+e /in)ormal0 e8amples! and the header material is standard:
66"ro.te-e*istsA":"node"node"simp+e-graph""-/""8oo+ean 66"to"determine"whether"there"is"a"ro.te"from"orig"to"dest"in"sg !define"!ro.te-e*istsA"orig"dest"sg#"...#

1hat we need are answers to the )our basic ?uestions o) the recipe )or generati+e recursion: @hat is a tri1iall% sol1able problemB The problem is tri+ial i) the nodes orig and dest are the same, @hat is a corresponding solutionB #as$: tr.e, >o3 do 3e generate ne3 problemsB I) orig is not the same as dest! there is onl$ one thing we can do! namel$! go to the node to which orig is connected and determine whether a route e8ists between it and dest, >o3 do 3e relate the solutionsB There is no need to do an$thing a)ter we )ind the solution to the new problem, I) origCs neighbor is connected to dest! then so is orig, From here we Fust need to e8press these answers in Scheme! and we get an algorithm, Figure <9 contains the complete )unction! including a )unction )or loo.ing up the neighbor o) a node in a simple graph,

66"ro.te-e*istsA":"node"node"simp+e-graph""-/""8oo+ean 66"to"determine"whether"there"is"a"ro.te"from"orig"to"dest"in"sg !define"!ro.te-e*istsA"orig"dest"sg# ""!cond """"9!s2m8o+&A"orig"dest#"tr.e: """"9else"!ro.te-e*istsA"!neigh8or"orig"sg#"dest"sg#:## 66"neigh8or":"node"simp+e-graph""-/""node 66"to"determine"the"node"that"is"connected"to"a-node"in"sg !define"!neigh8or"a-node"sg# ""!cond """"9!empt2A"sg#"!error"1neigh8or:"impossi8+e1#: """"9else"!cond """"9!s2m8o+&A"!first"!first"sg##"a-node# """""!second"!first"sg##:

Velse /neighbor a2node /rest sg00W0W00 Figure )&' Finding a route in a simple graph /+ersion (0 #+en a casual loo. at the )unction suggests that we ha+e a problem, Although the )unction is supposed to produce fa+se i) there is no route )rom orig to dest! the )unction de)inition doesnCt contain fa+se an$where, Con+ersel$! we need to as. what the )unction actuall$ does when there is no route between two nodes, Ta.e another loo. at )igure <7, In this simple graph there is no route )rom C to D, The connection that lea+es C passes right b$ D and instead goes to #, So letCs loo. at how ro.te-e*istsA deals with the inputs '7 and 'D )or Cimp+eG:
""!ro.te-e*istsA"'7"'D"'!!'"(#"!("7#"!7"5#"!D"5#"!5"(#"!>">### &"!ro.te-e*istsA"'5"'D"'!!'"(#"!("7#"!7"5#"!D"5#"!5"(#"!>">### &"!ro.te-e*istsA"'("'D"'!!'"(#"!("7#"!7"5#"!D"5#"!5"(#"!>">### &"!ro.te-e*istsA"'7"'D"'!!'"(#"!("7#"!7"5#"!D"5#"!5"(#"!>">###

The hand2e+aluation con)irms that as the )unction recurs! it calls itsel) with the e8act same arguments again and again, In other words! the e+aluation ne+er stops, @ur problem with ro.te-e*istsA is again a loss o) DD.nowledge!CC similar to that o) re+ati0e-2-a8so+.te in the preceding section, "i.e re+ati0e-2-a8so+.te! ro.tee*istsA was de+eloped according to the recipe and is independent o) its conte8t, That is! it doesnCt DD.nowCC whether some application is the )irst or the hundredth o) a recursi+e chain, In the case o) ro.te-e*istsA this means! in particular! that the )unction doesnCt DD.nowCC whether a pre+ious application in the current chain o) recursions recei+ed the e8act same arguments, The solution )ollows the pattern o) the preceding section, 1e add a parameter! which we call acc.-seen and which represents the accumulated list o) origination nodes that the )unction has encountered! starting with the original application, Its initial +alue must be empt2, As the )unction chec.s on a speci)ic orig and mo+es to its neighbors! orig is added to acc.-seen, Here is a )irst re+ision o) ro.te-e*istsA! dubbed ro.te-e*ists-acc.A:

66"ro.te-e*ists-acc.A":"node"node"simp+e-graph"!listof"node#""-/" 8oo+ean 66"to"determine"whether"there"is"a"ro.te"from"orig"to"dest"in"sg<" 66"ass.ming"the"nodes"in"acc.-seen"ha0e"a+read2"8een"inspected" 66"and"fai+ed"to"de+i0er"a"so+.tion" !define"!ro.te-e*ists-acc.A"orig"dest"sg"acc.-seen# ""!cond """"9!s2m8o+&A"orig"dest#"tr.e: """"9else"!ro.te-e*ists-acc.A"!neigh8or"orig"sg#"dest"sg """"""""""""""""""""""!cons"orig"acc.-seen##:##

The addition o) the new parameter alone does not sol+e our problem! but! as the )ollowing hand2e+aluation shows! pro+ides the )oundation )or one:
""!ro.te-e*ists-acc.A"'7"'D"'!!'"(#"!("7#"!7"5#"!D"5#"!5"(#"!>">## empt2# &"!ro.te-e*ists-acc.A"'5"'D"'!!'"(#"!("7#"!7"5#"!D"5#"!5"(#"!>">## '!7## &"!ro.te-e*ists-acc.A"'("'D"'!!'"(#"!("7#"!7"5#"!D"5#"!5"(#"!>">## '!5"7## &"!ro.te-e*ists-acc.A"'7"'D"'!!'"(#"!("7#"!7"5#"!D"5#"!5"(#"!>">## """"""""""""""""""""""'!("5"7##

In contrast to the original )unction! the re+ised )unction no longer calls itsel) with the e8act same arguments, 1hile the three arguments proper are again the same )or the third recursi+e application! the accumulator argument is di))erent )rom that o) the )irst application, Instead o) empt2! it is now '!("5"7#, The new +alue represents the )act that during the search o) a route )rom '7 to 'D! the )unction has inspected '(! '5! and '7 as starting points, All we need to do at this point is e8ploit the accumulated .nowledge in the )unction de)inition, Speci)icall$! we determine whether the gi+en orig is alread$ an item on acc.-seen, I) so! the problem is tri+iall$ sol+able with fa+se, Figure <; contains the de)inition o) ro.te-e*ists2A! which is the re+ision o) ro.te-e*istsA, The de)inition re)ers to contains! our )irst recursi+e )unction /see part II0! which determines whether a speci)ic s$mbol is on a list o) s$mbols,
66"ro.te-e*ists2A":"node"node"simp+e-graph""-/""8oo+ean 66"to"determine"whether"there"is"a"ro.te"from"orig"to"dest"in"sg !define"!ro.te-e*ists2A"orig"dest"sg# ""!local"!!define"!re-acc.A"orig"dest"sg"acc.-seen# """"""""""""!cond """"""""""""""9!s2m8o+&A"orig"dest#"tr.e: """"""""""""""9!contains"orig"acc.-seen#"fa+se: """"""""""""""9else"!re-acc.A"!neigh8or"orig"sg#"dest"sg"!cons orig"acc.-seen##:###"

/re2accuH orig dest sg empt$000 Figure )(' Finding a route in a simple graph /+ersion &0

The de)inition o) ro.te-e*ists2A also eliminates the two minor problems with the )irst re+ision, B$ locali*ing the de)inition o) the accumulating )unction! we can ensure that the )irst call to re-acc.A alwa$s uses empt2 as the initial +alue )or acc.-seen, And! ro.te-e*ists2A satis)ies the e8act same contract and purpose statement as ro.te-e*istsA,

Still! there is a signi)icant di))erence between ro.te-e*ists2A and re+ati0e-toa8so+.te2, 1hereas the latter was e?ui+alent to the original )unction! ro.te-e*ists2A is an impro+ement o+er the ro.te-e*istsA )unction, A)ter all! it corrects a )undamental )law in ro.te-e*istsA! which completel$ )ailed to )ind an answer )or some inputs, E ercise !.<2<1< Complete the de)inition in )igure <; and test it with the running e8ample, Ase the strateg$ o) section (;,< to )ormulate the tests as boolean2+alued e8pressions, Chec. with a hand2e+aluation that this )unction computes the proper result )or ''! '7! and Cimp+eG, Solution E ercise !.<2<2< #dit the )unction in )igure <; so that the locall$ de)ined )unction consumes onl$ those arguments that change during an e+aluation, Solution E ercise !.<2<!< De+elop a +ector2based representation o) simple graphs, Adapt the )unction in )igure <; so that it wor.s on a +ector2based representation o) simple graphs, Solution E ercise !.<2<#< Modi)$ the de)initions o) find-ro.te and find-ro.te/+ist in )igure ;; so that the$ produce fa+se! e+en i) the$ encounter the same starting point twice, Solution

The most con+enient wa$ to construct this list is to e+aluate !8.i+d-+ist"!add1"J# identit2#,
96

The time o) e+aluation will di))er )rom computer to computer, These measurements were conducted on a Pentium (99Mh* running "inu8, Measuring timings is also di))icult, At a minimum! each e+aluation should be repeated se+eral times! and the time reported should be the a+erage o) those measurements,
97

Section !1 Designing +ccumulator2St%le Functions


Section 5' illustrated with two e8amples the need )or accumulating e8tra .nowledge, In some cases! the accumulation ma.es it easier to understand a )unctionE in others it is necessar$ )or the )unction to wor. properl$, In both cases! howe+er! we )irst chose one o) the a+ailable design recipes! inspected the )unction! and then re+ised or )i8ed it, Put more generall$! adding an ACCAMA"AT@R! that is! a parameter that accumulates .nowledge! is something that we add to a )unction a)ter we ha+e designed a )unction! not be)ore, The .e$s to the de+elopment o) an accumulator2st$le )unction are: (, to recogni*e that the )unction bene)its )rom! or needs! an accumulatorE &, to understand what the accumulator represents, The )irst two subsections address these two ?uestions, Because the second one is a di))icult topic! the third subsection illustrates how to )ormulate precise claims about accumulators, More concretel$! in this section! we trans)orm se+eral standard recursi+e )unctions into )unctions that use au8iliar$ )unctions with accumulators,

($#$ Recogni9ing the %eed for an

ccumulator

Recogni*ing the need )or accumulators is not an eas$ tas., 1e ha+e seen two reasons! and the$ are the most pre+alent reasons )or adding accumulator parameters, In either case! it is critical that we )irst built a complete )unction based on a design recipe, Then we stud$ the )unction and loo. )or one o) the )ollowing characteristics: (, I) the )unction is structurall$ recursi+e and i) the result o) a recursi+e application is processed b$ an au8iliar$! recursi+e )unction! then we should consider the use o) an accumulator parameter, Ta.e the )unction in0ert as an e8ample:
66"in0ert":"!listof"R#""-/""!listof"R# 66"to"constr.ct"the"re0erse"of"a+o* 66"str.ct.ra+"rec.rsion"

!define"!in0ert"a+o*# ""!cond """"9!empt2A"a+o*#"empt2: """"9else"!ma-e-+ast-item"!first"a+o*#"!in0ert"!rest a+o*###:## 66"ma-e-+ast-item":"R"!listof"R#""-/""!listof"R# 66"to"add"an-*"to"the"end"of"a+o* 66"str.ct.ra+"rec.rsion" !define"!ma-e-+ast-item"an-*"a+o*# ""!cond """"9!empt2A"a+o*#"!+ist"an-*#: """"9else"!cons"!first"a+o*#"!ma-e-+ast-item"an-*"!rest a+o*###:##

The result o) the recursi+e application produces the re+erse o) the rest o) the list, It is processed b$ ma-e-+ast-item! which adds the )irst item to the re+erse o) the rest and thus creates the re+erse o) the entire list, This second! au8iliar$ )unction is also recursi+e, 1e ha+e thus identi)ied a potential candidate, It is now time to stud$ some hand2e+aluations! as we did in section 5',(! to see whether an accumulator helps, &, I) we are dealing with a )unction based on generati+e recursion! we are )aced with a much more di))icult tas., @ur goal must be to understand whether the algorithm can )ail to produce a result )or inputs )or which we e8pect a result, I) so! adding a parameter that accumulates .nowledge ma$ help, Because these situations are comple8! we postpone the discussion o) an e8ample until section 5&,&, These two situations are b$ no means the onl$ onesE the$ are Fust the most common ones, To sharpen our perception! we will discuss an additional arra$ o) possibilities in the )ollowing section,

($#"

ccumulator7Style +unctions

1hen we ha+e decided that an accumulator2st$le )unction is necessar$! we introduce it in two steps: Setting2up an accumulator' First! we must understand what .nowledge the accumulator needs to remember about the parameters proper and then how it is to remember it, For e8ample! )or the con+ersion o) relati+e distances to absolute distances! it su))ices to accumulate the total distance encountered so )ar, For the routing problem! we needed the accumulator to remember e+er$ node inspected so )ar, Thus the )irst accumulator was Fust a number! the second one a list o) nodes, The best wa$ to discuss the accumulation process is to introduce a template o) the accumulator2st$le )unction +ia a local de)inition and to name the parameters o) the )unction proper di))erentl$ )rom those o) the au8iliar$ )unction,

"etCs ta.e a loo. at the in0ert e8ample:


66"in0ert":"!listof"R#""-/""!listof"R# 66"to"constr.ct"the"re0erse"of"a+o* !define"!in0ert"a+o*%# ""!local"!66"acc.m.+ator"... ""!define"!re0"a+o*"acc.m.+ator# """"!cond """"""9!empt2A"a+o*#"...: """"""9else" ..."!re0"!rest"a+o*#"..."!"first"alo-#"... accumulator# ...":### """"!re0"a+o*%"...###

Here we ha+e a de)inition o) in0ert with an au8iliar$ )unction re0 in template )orm, This au8iliar$ template has one parameter in addition to those o) in0ert: the accumulating parameter, The bo8 in the recursi+e application indicates that we need an e8pression that maintains the accumulation process and that this process depends on the current +alue o) acc.m.+ator and !first"a+o*#! the +alue re0 is about to )orget, Clearl$! in0ert cannot )orget an$thing! because it onl$ re+erses the order o) items on the list, Hence we might Fust wish to accumulate all items that re0 encounters, This means (, that acc.m.+ator stands )or a list! and &, that it stands )or all those items in a+o*% that precede the a+o* argument o) re0, For the second part o) the anal$sis! it is critical that we can distinguish the original argument! a+o*%! )rom the current one! a+o*, -ow that we .now the rough purpose o) the accumulator! letCs consider what the )irst +alue should be and what we should do )or the recursion, 1hen we appl$ re0 in the bod$ o) the local2e8pression! it recei+es a+o*%! which means that it hasnCt encountered an$ o) its items, The initial +alue )or acc.m.+ator is empt2, 1hen re0 recurs! it has Fust encountered one e8tra item: !first"a+o*#, To remember it! we can cons it onto the current +alue o) accumulator, Here is the enhanced de)inition:
66"in0ert":"!listof"R#""-/""!listof"R# 66"to"constr.ct"the"re0erse"of"a+o* !define"!in0ert"a+o*%# ""!local"!66"acc.m.+ator"is"the"re0ersed"+ist"of"a++"those items

""66"on"a+o*%"that"precede"a+o* ""!define"!re0"a+o*"acc.m.+ator# """"!cond """"""9!empt2A"a+o*#"...: """"""9else ..."!re0"!rest"a+o*#"!cons"!first"a+o*# acc.m.+ator## ...:### """"!re0"a+o*%"empt2###

A close inspection re+eals that acc.m.+ator is not Fust the items on a+o*% that precede but a list o) these items in re+erse order, E ploiting an accumulator' @nce we ha+e decided what .nowledge the accumulator maintains and how it is maintained! we can mo+e to the ?uestion o) how to e8ploit this .nowledge )or our )unction, In the case o) in0ert! the answer is almost ob+ious, I) acc.m.+ator is the list o) all items on a+o*% that precede a+o* in re+erse order! then! i) a+o* is empt$! acc.m.+ator stands )or the re+erse o) a+o*%, Put di))erentl$: i) a+o* is empt2! re0Cs answer is acc.m.+ator! and that is the answer we want in both cases:
66"in0ert":"!listof"R#""-/""!listof"R# 66"to"constr.ct"the"re0erse"of"a+o* !define"!in0ert"a+o*%# ""!local"!66"acc.m.+ator"is"the"re0ersed"+ist"of"a++"those items ""66"on"a+o*%"that"precede"a+o* ""!define"!re0"a+o*"acc.m.+ator# """"!cond """"""9!empt2A"a+o*#"acc.m.+ator: """"""9else !re0"!rest"a+o*#"!cons"!first"a+o*# acc.m.+ator##:### """"!re0"a+o*%"empt2###

The .e$ step o) this de+elopment is the precise description o) the role o) acc.m.+ator, In general! an ACCAMA"AT@R I-4ARIA-T describes a relationship between the argument proper o) the )unction! the current argument o) the au8iliar$ )unction! and the accumulator that must alwa$s hold when an accumulator2st$le )unction is used,

($#( Transforming +unctions into

ccumulator7Style

The most comple8 part o) the design recipe is the re?uirement to )ormulate an accumulator in+ariant, 1ithout that we cannot produce )unctioning accumulator2st$le )unctions, Because )ormulating in+ariants is clearl$ an art that deser+es a lot o) practice! we practice it in this section with three small! well2understood structural )unctions that do not need an accumulator, The section concludes with a group o) e8ercises concerning this step, For the )irst e8ample! consider the )unction s.m:

66"s.m":"!listof"n.m8er#""-/""n.m8er 66"to"comp.te"the"s.m"of"the"n.m8ers"on"a+on 66"str.ct.ra+"rec.rsion" !define"!s.m"a+on# ""!cond """"9!empt2A"a+on#"%: """"9else"!+"!first"a+on#"!s.m"!rest"a+on###:##

Here is the )irst step toward an accumulator +ersion:


66"s.m":"!listof"n.m8er#""-/""n.m8er 66"to"comp.te"the"s.m"of"the"n.m8ers"on"a+on% !define"!s.m"a+on%# ""!local"!66"acc.m.+ator"..." ""!define"!s.m-a"a+on"acc.m.+ator# """"!cond """"""9!empt2A"a+on#"...: """"""9else ..."!s.m-a"!rest"a+on#"..."!"first"alon#"... accumulator# ...":### """"!s.m-a"a+on%"...###

As suggested b$ our )irst step! we ha+e put the template )or s.m-a into a local de)inition! added an accumulator parameter! and renamed s.mCs parameter, @ur goal is to de+elop an accumulator in+ariant )or s.m, To do so! we must consider how s.m proceeds and what the goal o) the process is, "i.e re0! s.m-a processes the numbers on the list one b$ one, The goal is to add up these numbers, This suggests that acc.m.+ator represents the sum o) the numbers seen so )ar:
... ""!local"!66"acc.m.+ator"is"the"s.m"of"the"n.m8ers"that"preceded ""66"those"in"a+on"on"a+on% ""!define"!s.m-a"a+on"acc.m.+ator# """"!cond """"""9!empt2A"a+on#"...: """"""9else ..."!s.m-a"!rest"a+on#"!+"!first"a+on#"acc.m.+ator## ...":### """"!s.m-a"a+on%"%###

1hen we appl$ s.m-a we must use % as the +alue o) acc.m.+ator! because it hasnCt processed an$ o) the numbers on a+on $et, For the second clause! we must add !first a+on# to acc.m.+ator so that the in+ariant holds again )or the )unction application, =i+en a precise in+ariant! the rest is straight)orward again, I) a+on is empt2! s.m-a returns acc.m.+ator because it represents the sum o) all numbers on a+on now, Figure << contains the )inal de)inition o) the accumulator2st$le +ersion o) s.m,

66"s.m":"!listof"n.m8er#""-/""n.m8er 66"to"comp.te"the"s.m"of"the"n.m8ers"on"a+on% !define"!s.m"a+on%# ""!local"!66"acc.m.+ator"is"the"s.m"of"the"n.m8ers"that"preceded ""66"those"in"a+on"on"a+on% ""!define"!s.m-a"a+on"acc.m.+ator# """"!cond """"""9!empt2A"a+on#"acc.m.+ator: """"""9else"!s.m-a"!rest"a+on#"!+"!first"a+on# acc.m.+ator##:### """"!s.m-a"a+on%"%### 66"D":"N""-/""N 66"to"comp.te"n""B""!n"-"1#""B""...""B""2""B""1 !define"!D"n%# ""!local"!66"acc.m.+ator"is"the"prod.ct"of"a++"nat.ra+"n.m8ers"in 9n%<"n# ""!define"!D-a"n"acc.m.+ator# """"!cond """"""9!@eroA"n#"acc.m.+ator: """"""9else"!D-a"!s.81"n#"!*"n"acc.m.+ator##:###

/L2a n' (000 Figure ))' Some simple accumulator2st$le )unctions "etCs compare how the original de)inition o) s.m and the accumulator2st$le de)inition produce an answer )or the same input:
""!s.m"!+ist"1%.23"4.5%"5.27## &"!+"1%.23"!s.m"!+ist"4.5% 5.27### &"!+"1%.23"!+"4.5%"!s.m"!+ist 5.27#### &"!+"1%.23"!+"4.5%"!+"5.27"!s.m empt2#### &"!+"1%.23"!+"4.5%"!+"5.27"%### &"!+"1%.23"!+"4.5%"5.27## &"!+"1%.23",.77# &"2%.% ""!s.m"!+ist"1%.23"4.5% 5.27## &"!s.m-a"!+ist"1%.23"4.5% 5.27#"%# &"!s.m-a"!+ist"4.5%"5.27# 1%.23# &"!s.m-a"!+ist"5.27# 14.73# &"!s.m-a"empt2"2%.%# &"2%.%

@n the le)t side! we see how the plain recursi+e )unction descends the list o) numbers all the wa$ to the end and sets up addition operations on the wa$, @n the right side! we see how the accumulator2st$le +ersion adds up the numbers as it goes, Furthermore! we see that )or each application o) s.m-a the in+ariant holds with respect to the application o) s.m, 1hen s.m-a is )inall$ applied to empt2! the accumulator is the )inal result! and s.m-a returns it, E ercise !1<!<1< A second di))erence between the two )unctions concerns the order o) addition, 1hile the original +ersion o) s.m adds up the numbers )rom right to le)t! the accumulator2st$le +ersion adds them up )rom le)t to right, For e8act numbers! this di))erence has no e))ect on the )inal result, For ine8act numbers! the di))erence is signi)icant, Consider the )ollowing de)inition:
!define"!g-series"n# ""!cond """"9!@eroA"n#"empt2:

""""9else"!cons"!e*pt"-%.,,"n#"!g-series"!s.81"n###:##

Appl$ing g-series to a natural number produces the beginning o) a decreasing geometric series /see section &5,(0, Depending on which )unction we use to sum up the items o) this list! we get +astl$ di))erent results, #+aluate the e8pression
!s.m"!g-series"#i1%%%##

with both the original +ersion o) s.m as well as its accumulator2st$le +ersion, Then e+aluate
!*"1%e15"!s.m"!g-series"#i1%%%###

which pro+es that! depending on the conte8t! the di))erence can be arbitraril$ large, Solution For the second e8ample! we return to the )actorial )unction )rom part II:
66"D":"N""-/""N 66"to"comp.te"n""B""!n"-"1#""B""...""B""2""B""1 66"str.ct.ra+"rec.rsion" !define"!D"n# ""!cond """"9!@eroA"n#"1: """"9else"!*"n"!D"!s.81"n###:##

1hile re+ati0e-2-a8so+.te and in0ert processed lists! the )actorial )unction wor.s on natural numbers, Its template is that )or N2processing )unctions, 1e proceed as be)ore b$ creating a local de)inition o) D:
66"D":"N""-/""N 66"to"comp.te"n""B""!n"-"1#""B""...""B""2""B""1 !define"!D"n%# ""!local"!66"acc.m.+ator"..." ""!define"!D-a"n"acc.m.+ator# """"!cond """"""9!@eroA"n#"...: """"""9else" ..."!D-a"!s.81"n#"..."n"..."accumulator#"...:### """"!D-a"n%"...###

This s.etch suggests that i) D is applied to the natural number n! D-a processes n! then n - (! n - &! and so on until it reaches %, Since the goal is to multipl$ these numbers! the accumulator should be the product o) all those numbers that D-a has encountered:
... ""!local"!66"acc.m.+ator"is"the"prod.ct"of"a++"nat.ra+"n.m8ers 8etween ""66"n%"!inc+.si0e#"and"n"!e*c+.si0e#

""!define"!D-a"n"acc.m.+ator# """"!cond """"""9!@eroA"n#"...: """"""9else" ..."!D-a"!s.81"n#"!*"n"acc.m.+ator##"...:### """"!D-a"n%"1###

To ma.e the in+ariant true at the beginning! we must use 1 )or the accumulator, 1hen D-a recurs! we must multipl$ the current +alue o) the accumulator with n to reestablish the in+ariant, From the purpose statement )or the accumulator o) D-a! we can see that i) n is %! the accumulator is the product o) n! ...! 1, That is! it is the desired result, So! li.e s.m! D-a returns acc.m.+ator in the )irst case and simpl$ recurs in the second one, Figure << contains the complete de)inition, It is instructi+e to compare hand2e+aluations )or the two +ersions o) D:
""!D"3# &"!*"3"!D"2## &"!*"3"!*"2"!D"1### &"!*"3"!*"2"!*"1"!D"%#### &"!*"3"!*"2"!*"1"1### &"!*"3"!*"2"1## &"!*"3"2# &" ""!D"3# &"!D-a"3"1# &"!D-a"2"3# &"!D-a"1" # &"!D-a"%" # &"

The le)t column shows how the original +ersion wor.s! the right one how the accumulator2st$le )unction proceeds, Both tra+erse the natural number until the$ reach %! but while the original +ersion onl$ schedules multiplications! the new one multiplies the numbers as the$ are processed, In addition! the right column illustrates how the new )actorial )unction maintains the accumulator in+ariant, For each application! the accumulator is the product o) 3 to n where n is the )irst argument to D-a, E ercise !1<!<2< "i.e s.m! D per)orms the primiti+e computation steps /multiplication0 in re+erse order, Surprisingl$! this a))ects the per)ormance o) the )unction in a negati+e manner, Ase DrSchemeCs time2)acilit$ to determine how long the two +ariants need to e+aluate !D"2%# (''' times, >int' /(0 De+elop the )unction
66"man2":"N"!N""-/""N#""-/""tr.e 66"to"e0a+.ate"!f"2%#"n"times" !define"!man2"n"f#"...#

/&0 #+aluating !time"an-e*pression# determines how much time the e+aluation o) an-e*pression ta.es, Solution

For the last e8ample! we stud$ a )unction on simpli)ied binar$ trees, The e8ample illustrates that accumulator2st$le programming is not Fust )or data de)initions with a single sel)2re)erence, Indeed! it is as common )or complicated data de)initions as it is )or lists and natural numbers, Here is the structure de)inition )or stripped2down binar$ trees:
!define-struct"node"!+eft"right##

and here is its companion data de)inition: A binary-tree /short: tree0 is either (, empt2 &, !ma-e-node"t+"tr# where t+! tr are trees, These trees contain no in)ormation! and all o) them end in empt2, Still! there are man$ di))erent trees as )igure <> shows, The table indicates how to thin. o) each tree as a graphical element! that is! o) empt2 as a plain dot and ma-e-node as a dot that combines two trees,
empt2 !ma-e-node"empt2"empt2# !ma-e-node" ""!ma-e-node" """"empt2" """"!ma-e-node"empt2"empt2## ""empt2#"

Figure )-' Some stripped2down binar$ trees Asing the graphical representation o) binar$ trees we can easil$ determine properties o) trees, For e8ample! we can count how man$ nodes it contains! how man$ empt2s there are! or how high it is, "etCs loo. at the )unction height! which consumes a tree and determines how high it is:
66"height":"tree""-/""n.m8er 66"to"meas.re"the"height"of"a8t% 66"str.ct.ra+"rec.rsion" !define"!height"a8t# ""!cond

""""9!empt2A"a8t#"%: """"9else"!+"!ma*"!height"!node-+eft"a8t##"!height"!node-right a8t###"1#:##

"i.e the data de)inition! this )unction de)inition has two sel)2re)erences, To trans)orm this )unction into an accumulator2st$le )unction! we )ollow the standard path, 1e begin with putting an appropriate template into a local de)inition:
66"height":"tree""-/""n.m8er 66"to"meas.re"the"height"of"a8t% !define"!height"a8t%# ""!local"!66"acc.m.+ator"..." ""!define"!height-a"a8t"acc.m.+ator# """"!cond """"""9!empt2A"a8t#"...: """"""9else ..."!height-a"!node-+eft"a8t#" """"""""""""""""""""""""""""""..."!"node-right"a*t#"... accumulator#"... ..."!height-a"!node-right"a8t#" """"""""""""""""""""""""""""""..."!"node-+eft"a*t#"... accumulator#"...":### """"!height"a8t%"...###

The problem! as alwa$s! is to determine what .nowledge the accumulator should represent, An ob+ious choice is that acc.m.+ator should be a number, More speci)icall$! acc.m.+ator should represent the number o) nodes that height-a has processed so )ar, Initiall$! it has seen % nodesE as it descends the tree! it must increase the accumulator as it processes a node:
... ""!local"!66"acc.m.+ator"represents"how"man2"nodes"height-a" """"""""""66"has"enco.ntered"on"its"wa2"to"a8t"from"a8t% ""!define"!height-a"a8t"acc.m.+ator# """"!cond """"""9!empt2A"a8t#"...: """"""""""""""9else ..."!height-a"!node-+eft"a8t#""!+"acc.m.+ator"1##"... ..."!height-a"!node-right"a8t#"!+"acc.m.+ator 1##"...:### """"!height"a8t%"%##

That is! the accumulator in+ariant is that acc.m.+ator counts how man$ steps heighta has ta.en on a particular path into the tree a8t, The result in the base case is acc.m.+ator againE a)ter all it represents the height or length o) the particular path, But! in contrast to the )irst two e8amples! it is not the )inal result, In the second cond2clause! the new )unction has two heights to deal with, =i+en that we are interested in the larger one! we use SchemeCs ma* operation to select it,

/height2a abt' '000 Figure -.' The accumulator2st$le +ersion o) height

66"height":"tree""-/""n.m8er 66"to"meas.re"the"height"of"a8t% !define"!height"a8t%# ""!local"!66"acc.m.+ator"represents"how"man2"nodes"height-a" """"""""""66"has"enco.ntered"on"its"wa2"to"a8t"from"a8t% """"""""""!define"!height-a"a8t"acc.m.+ator# """"""""""""!cond """"""""""""""9!empt2A"a8t#"acc.m.+ator: """"""""""""""9else"!ma*"!height-a"!node-+eft"a8t#""!+"acc.m.+ator 1## """""""""""""""""""""""""!height-a"!node-right"a8t#"!+"acc.m.+ator 1###:###

Figure >' contains the complete de)inition )or height, @ur )inal step is to chec. out a hand2e+aluation o) the new )unction, 1e use the most comple8 e8ample )rom the abo+e table:
""!height"!ma-e-node """"!ma-e-node"empt2" """""""""""""""!ma-e-node"empt2"empt2##" """"empt2## &"!height-a"!ma-e-node """"""!ma-e-node"empt2" """""""""!ma-e-node"empt2"empt2##" """"""empt2# """"""""""""%# &"!ma*"!height-a "!ma-e-node"empt2" """"!ma-e-node"empt2"empt2## "1# """""""!height-a"empt2"1## &"!ma*"!ma*" "!height-a"empt2"2# "!height-a"!ma-e-node"empt2"empt2#"2## """""""!height-a"empt2"1## &"!ma*"!ma*" "!height-a"empt2"2# "!ma*"!height-a"empt2"3#"!height-a"empt2"3### """""""!height-a"empt2"1## &"!ma*"!ma*" "2 "!ma*"3"3## """""""1# &"3

It shows how height-a increments the accumulator at each step and that the accumulator at the top o) a path represents the number o) lines tra+ersed, The hand2 e+aluation also shows that the results o) the +arious branches are combined at each branching point, E ercise !1<!<!< De+elop an accumulator2st$le +ersion o) prod.ct! the )unction that computes the product o) a list o) numbers, Show the stage that e8plains what the accumulator represents, Solution

E ercise !1<!<#< De+elop an accumulator2st$le +ersion o) how-man2! which is the )unction that determines the number o) items on a list, Show the stage that e8plains what the accumulator represents, Solution E ercise !1<!<$< De+elop an accumulator2st$le +ersion o) add-to-pi! the )unction that adds a natural number to pi without using + /see section ((,70, Show the stage that e8plains what the accumulator represents, =enerali*e the )unction so that it adds two numbers! the )irst one a natural number! without using +, Solution E ercise !1<!<&< De+elop the )unction ma-e-pa+indrome! which accepts a non2empt$ list and constructs a palindrome b$ mirroring the list around the last item, Thus! i) we were to represent the word DDabcCC and appl$ ma-e-pa+indrome! we would get bac. the representation o) DDabcbaCC, Solution E ercise !1<!<(< De+elop to1%, It consumes a list o) digits and produces the corresponding number, The )irst item on the list is the most signi)icant digit, #8amples:
!&"!to1%"!+ist"1"%"2##" """1%2# !&"!to1%"!+ist"2"1## """21#

-ow generali*e the )unction so that it consumes a base b and a list o) b2digits, The con+ersion produces the decimal /('2based0 +alue o) the list, The base is between 2 and 1%, A b2digit is a number between ' and b - (, #8amples:
!&"!to1%-genera+"1%"!+ist"1"%"2##" """1%2# !&"!to1%-genera+"%$"!+ist"1"%"2##" """ #

>int' In the )irst e8ample! the result is determined b$

the second one is

That is! the e8ponent represents the number o) digits that )ollow,

Solution

E ercise !1<!<)< De+elop the )unction is-primeA! which consumes a natural number and returns tr.e i) it is prime and fa+se otherwise, A number n is prime i) it is not di+isible b$ an$ number between & and n - (, >ints' /(0 The design recipe )or N9/&1: suggests the )ollowing template:
66"is-primeA":"N9/&1:""-/""8oo+ean 66"to"determine"whether"n"is"a"prime"n.m8er !define"!is-primeA"n# ""!cond """"9!&"n"1#"...: """"9else"..."!is-primeA"!s.81"n##"...:##

From this outline! we can immediatel$ conclude that the )unction )orgets n! its initial argument as it recurs, Since n is de)initel$ needed to determine whether n is di+isible b$ & ... n - (! this suggests that we design an accumulator2st$le local )unction that remembers n as it recurs, Solution Pitfalls: People who encounter accumulator2st$le programming )or the )irst time o)ten get the impression that the$ are alwa$s )aster or easier to understand /design0 than their recursi+e counterparts, Both parts are plain wrong, 1hile it is impossible to deal with the )ull scope o) the mista.e! let us ta.e a loo. at a small countere8ample, Consider the )ollowing table: plain )actorial accumulator2st$le )actorial 7,;9' 7,>;' 7,;<' 7,>6' 7,<'' 7,><' 7,<&' 7,>;' 7,<;' 9,9>' 7,<'9 9,((' It represents the results )or e8ercise 5(,5,&, Speci)icall$! the le)t column shows the number o) seconds )or (''' e+aluations o) !D"2%# with the plain )actorial )unctionE the right column shows what the same e8periment $ields when we use the )actorial )unction with an accumulator parameter, The last row shows the a+erages )or the two columns, The table shows that the per)ormance o) the accumulator2st$le +ersion o) )actorial is alwa$s worse than that o) the original )actorial )unction,

Section !2

/ore 8ses of +ccumulation


This section presents three e8tended e8ercises that re?uire the whole range o) s.ills: design b$ recipe! including generati+e recursion! and the addition o) accumulators )or +arious purposes,

("#$ E,tended E,ercise.

ccumulators on Trees

!define-struct"chi+d"!father"mother"name"date"e2es##

A node in a fami!y tree /short: ftn0 is either (, empt2! or &, !ma-e-chi+d"f"m"na"da"ec# where f and m are ftns! na and ec are s$mbols! and da is a number,
66"a++-8+.e-e2ed-ancestors":"ftn""-/""!listof"s2m8o+# 66"to"constr.ct"a"+ist"of"a++"8+.e-e2ed"ancestors"in"a-ftree !define"!a++-8+.e-e2ed-ancestors"a-ftree# ""!cond """"9!empt2A"a-ftree#"empt2: """"9else"!local"!!define"in-parents" """"""""""""""""""""!append"!a++-8+.e-e2ed-ancestors"!chi+d-father a-ftree## """"""""""""""""""""""""""""!a++-8+.e-e2ed-ancestors"!chi+d-mother a-ftree##### """"""""""""!cond """"""""""""""9!s2m8o+&A"!chi+d-e2es"a-ftree#"'8+.e#" """""""""""""""!cons"!chi+d-name"a-ftree#"in-parents#:

Velse in2parentsW00W00 Figure -1' Collecting )amil$ trees with b! e-eyed-ancestor( Figure >( recalls the structure and data de)initions o) )amil$ trees )rom section (6,( where we de+eloped the )unction 8+.e-e2ed-ancestorA! which determined whether an ancestor )amil$ tree contained a blue2e$ed )amil$ member, In contrast! a++-8+.ee2ed-ancestors! the )unction in )igure >(! collects the names o) all blue2e$ed )amil$ in a gi+en )amil$ tree, The )unctionCs structure is that o) a tree2processing )unction, It has two cases: one )or the empt$ tree and another one )or a chi+d node, The latter clause contains two sel)2 re)erences: one per parent, These recursi+e applications collect the names o) all blue2 e$ed ancestors )rom the )atherCs and the motherCs )amil$ treeE append combines the two lists into one,

The append )unction is a structurall$ recursi+e )unction, Here it processes the two lists that the natural recursions o) a++-8+.e-e2ed-ancestors produce, According to section (;,(! this obser+ation suggests that the )unction is a natural candidate )or a trans)ormation into accumulator2st$le, "etCs get started:
66"a++-8+.e-e2ed-ancestors":"ftn""-/""!listof"s2m8o+# 66"to"constr.ct"a"+ist"of"a++"8+.e-e2ed"ancestors"in"a-ftree !define"!a++-8+.e-e2ed-ancestors"a-ftree%#" ""!local"!66"acc.m.+ator"... """"""""""!define"!a++-a"a-ftree"acc.m.+ator# """"""""""""!cond """"""""""""""9!empt2A"a-ftree#"...: """"""""""""""9else" """""""""""""""!local"!!define"in-parents" """""""""""""""""""""""""!a++-a"..."!chi+d-father"a-ftree#"..." """"""""..."acc.m.+ator"...# """""""""""""""""""""""""!a++-a"..."!chi+d-mother"a-ftree#"... """"""""..."acc.m.+ator"...### """""""""""""""""!cond """""""""""""""""""9!s2m8o+&A"!chi+d-e2es"a-ftree#"'8+.e#" """"""""""""""""""""!cons"!chi+d-name"a-ftree#"in-parents#: """""""""""""""""""9else"in-parents:##:### """"!a++-a"a-ftree%"...###

@ur ne8t goal is the )ormulation o) an accumulator in+ariant, The general purpose o) the accumulator is to remember .nowledge about a-ftree% that a++-a loses as it tra+erses the tree, A loo. at the de)inition in )igure >( shows two recursi+e applications, The )irst one processes !chi+d-father"a-ftree#! which means this application o) a++-8+.ee2ed-ancestors loses .nowledge about the mother o) a-ftree, Con+ersel$! the second recursi+e application has no .nowledge o) the )ather o) a-ftree as it processes the motherCs )amil$ tree, At this point! we ha+e two choices: (, The accumulator could represent all blue2e$ed ancestors encountered so )ar! including those in the motherCs )amil$ tree! as it descends into the )atherCs tree, &, The alternati+e is to ha+e the accumulator stand )or the lost items in the tree, That is! as a++-a processes the )atherCs )amil$ tree! it remembers the motherCs tree in the accumulator /and e+er$thing else it hasnCt seen be)ore0, "etCs e8plore both possibilities! starting with the )irst, Initiall$! a++-a has not seen an$ o) the nodes in the )amil$ tree! so acc.m.+ator is empt2, As a++-a is about to tra+erse the )atherCs )amil$ tree! we must create a list that

represents all blue2e$ed ancestors in the tree that we are about to )orget! which is the motherCs tree, This suggests the )ollowing accumulator in+ariant )ormulation:
66"acc.m.+ator"is"the"+ist"of"8+.e-e2ed"ancestors 66"enco.ntered"on"the"mother-side"trees"of"the"path"in 66"a-ftree%"to"a-ftree

To maintain the in+ariant )or the natural recursion! we must collect the ancestors on the motherCs side o) the tree, Since the purpose o) a++-a is to collect those ancestors! we use the e8pression
!a++-a"!chi+d-mother"a-ftree#"acc.m.+ator#

to compute the new accumulator )or the application o) a++-a to !chi+d-father"aftree#, Putting e+er$thing together )or the second cond2clause $ields this:
!local"!!define"in-parents" ""!a++-a"!chi+d-father"a-ftree# """"!a++-a"!chi+d-mother"a-ftree# """"""acc.m.+ator#### ""!cond """"9!s2m8o+&A"!chi+d-e2es"a-ftree#"'8+.e#" """""!cons"!chi+d-name"a-ftree#"in-parents#: """"9else"in-parents:##

This lea+es us with the answer in the )irst cond2clause, Since acc.m.+ator represents all blue2e$ed ancestors encountered so )ar! it is the result, Figure >& contains the complete de)inition,
66"a++-8+.e-e2ed-ancestors":"ftn""-/""!listof"s2m8o+# 66"to"constr.ct"a"+ist"of"a++"8+.e-e2ed"ancestors"in"a-ftree !define"!a++-8+.e-e2ed-ancestors"a-ftree#" ""!local"!66"acc.m.+ator"is"the"+ist"of"8+.e-e2ed"ancestors ""66"enco.ntered"on"the"mother-side"trees"of"the"path"in ""66"a-ftree%"to"a-ftree """"""""""!define"!a++-a"a-ftree"acc.m.+ator# """"""""""""!cond """"""""""""""9!empt2A"a-ftree#"acc.m.+ator: """"""""""""""9else" """""""""""""""!local"!!define"in-parents" """""""""""""""""""""""""!a++-a"!chi+d-father"a-ftree#" """"""""""""""""""""""""""""""""!a++-a"!chi+d-mother"a-ftree# acc.m.+ator#### """""""""""""""""!cond """""""""""""""""""9!s2m8o+&A"!chi+d-e2es"a-ftree#"'8+.e#" """"""""""""""""""""!cons"!chi+d-name"a-ftree#"in-parents#: """""""""""""""""""9else"in-parents:##:###

/all2a a2)tree empt$000 Figure -2' Collecting blue2e$ed ancestors! accumulator2st$le /+ersion (0 For the second +ersion! we want the accumulator to represent a list o) all o) the )amil$ trees that ha+enCt been processed $et, Because o) the di))erent intention! let us call the accumulator parameter todo:
66"todo"is"the"+ist"of"fami+2"trees" 66"enco.ntered"8.t"not"processed"

"i.e the accumulator2st$le in0ert! a++-a initiali*es todo to empt2, It updates it b$ e8tending the list )or the natural recursion:
!local"!!define"in-parents" ""!a++-a"!chi+d-father"a-ftree#" """"!cons"!chi+d-mother"a-ftree#"todo#### ""!cond """"9!s2m8o+&A"!chi+d-e2es"a-ftree#"'8+.e#" """""!cons"!chi+d-name"a-ftree#"in-parents#: """"9else"in-parents:##

The problem now is that when a++-a is applied to the empt2 tree! todo does not represent the result but what is le)t to do )or a++-a, To +isit all those )amil$ trees! a++-a must be applied to them! one at a time, @) course! i) todo is empt2! there is nothing le)t to doE the result is empt2, I) todo is a list! we pic. the )irst tree on the list as the ne8t one to be processed:
!cond ""9!empt2A"todo#"empt2: ""9else"!a++-a"!first"todo#"!rest"todo##:#

The rest o) the list is what is now le)t to do,


66"a++-8+.e-e2ed-ancestors":"ftn""-/""!listof"s2m8o+# 66"to"constr.ct"a"+ist"of"a++"8+.e-e2ed"ancestors"in"a-ftree !define"!a++-8+.e-e2ed-ancestors"a-ftree%#" ""!local"!66"todo"is"the"+ist"of"fami+2"trees"enco.ntered"8.t"not processed" """"""""""!define"!a++-a"a-ftree"todo# """"""""""""!cond """"""""""""""9!empt2A"a-ftree#" """""""""""""""!cond """""""""""""""""9!empt2A"todo#"empt2: """""""""""""""""9else"!a++-a"!first"todo#"!rest"todo##:#: """"""""""""""9else" """""""""""""""!local"!!define"in-parents" """""""""""""""""""""""""!a++-a"!chi+d-father"a-ftree#" """"""""""""""""""""""""""""""""!cons"!chi+d-mother"a-ftree# todo#### """""""""""""""""!cond """""""""""""""""""9!s2m8o+&A"!chi+d-e2es"a-ftree#"'8+.e#" """"""""""""""""""""!cons"!chi+d-name"a-ftree#"in-parents#: """""""""""""""""""9else"in-parents:##:###

/all2a a2)tree' empt$000 Figure -!' Collecting blue2e$ed ancestors! accumulator2st$le /+ersion &0 Figure >5 contains the complete de)inition )or this second accumulator2st$le +ariant o) a++-8+.e-e2ed-ancestors, The au8iliar$ de)inition is the most unusual recursi+e )unction de)inition we ha+e seen, It contains a recursi+e application o) a++-a in both the )irst and the second cond2clause, That is! the )unction de)inition does not match the data de)inition )or )amil$ trees! the primar$ inputs, 1hile a )unction li.e that can be the result o) a care)ul chain o) de+elopment steps! starting )rom a wor.ing )unction de+eloped with a design recipe! it should ne+er be a starting point,

The use o) accumulators is also )airl$ common in programs that process representations o) programs, 1e encountered these )orms o) data in section (6,6! and li.e )amil$ trees! the$ ha+e complicated data de)initions, In interme**o 5! we also discussed some concepts concerning +ariables and their mutual association! though without processing these concepts, The )ollowing e8ercises introduce simple )unctions that wor. with the scope o) parameters! binding occurrences o) +ariables! and other notions, E ercise !2<1<1< De+elop a data representation )or the )ollowing tin$ subset o) Scheme e8pressions: O ?0ar/ X /lambda /?0ar/0 ?e*p/0 X /?e*p/ ?e*p/0 The subset contains onl$ three .inds o) e8pressions: +ariables! )unctions o) one argument! and )unction applications,
?e*p/

#8amples:
1."!lambda"!*#"2# """""" 2."!!lambda"!*#"*#" """"""!lambda"!*#"*## 3."!!!lambda"!2# "!lambda"!*# """2## """""""!lambda"!@#"@## """"""!lambda"!w#"w##

Represent +ariables as s$mbols, Call the class o) data Lam, Recall that lambda2e8pressions are )unctions without names, Thus the$ bind their parameter in the bod$, In other words! the scope o) a lambda2e8pressionCs parameter is the bod$, #8plain the scope o) each binding occurrence in the abo+e e8amples, Draw arrows )rom all bound occurrences to the binding occurrences, I) a +ariable occurs in an e8pression but has no corresponding binding occurrence! the occurrence is said to be )ree, Ma.e up an e8pression in which * occurs both )ree and bound, Solution E ercise !2<1<2< De+elop the )unction
66"free-or-8o.nd":"Lam""-/""Lam" 66"to"rep+ace"each"non-8inding"occ.rrence"of"a"0aria8+e"in"a-+am" 66"with"'free"or"'8o.nd<"depending"on"whether"the" 66"occ.rrence"is"8o.nd"or"not. !define"!free-or-8o.nd"a-+am#"...#

where Lam is the class o) e8pression representations )rom e8ercise 5&,(,(, Solution

E ercise !2<1<!< De+elop the )unction


66".ni).e-8inding":"Lam""-/""Lam" 66"to"rep+ace"0aria8+es"names"of"8inding"occ.rrences"and"their 8o.nd 66"co.nterparts"so"that"no"name"is".sed"twice"in"a"8inding occ.rrence !define"!.ni).e-8inding"a-+am#"...#

where Lam is the class o) e8pression representations )rom e8ercise 5&,(,(, >int' The )unction gens2m creates a new and uni?ue s$mbol )rom a gi+en s$mbol, The result is guaranteed to be distinct )rom all other s$mbols in the program! including those pre+iousl$ generated with gens2m, Ase the techni?ue o) this section to impro+e the )unction, >int' The accumulator relates old parameter names to new parameter names, Solution

("#" E,tended E,ercise. /issionaries and Canni&als


@n occasion! accumulators are a part o) a piece o) compound data because a )unction manages man$ pieces o) data /in the same class0 at the same time, The )ollowing stor$ poses Fust such a problem: @nce upon a time! three cannibals were guiding three missionaries through a Fungle, The$ were on their wa$ to the nearest mission station, A)ter some time! the$ arri+ed at a wide ri+er! )illed with deadl$ sna.es and )ish, There was no wa$ to cross the ri+er without a boat, Fortunatel$! the$ )ound a row boat with two oars a)ter a short search, An)ortunatel$! the boat was too small to carr$ all o) them, It could barel$ carr$ two people at a time, 1orse! because o) the ri+erCs width there was no wa$ to bring the boat bac. other than to row it bac., Since the missionaries could not trust the cannibals the$ had to )igure out a plan to get all si8 o) them sa)el$ across the ri+er, The problem was that these cannibals would .ill and eat missionaries as soon as there were more cannibals than missionaries at some place, Thus our missionar$2programmer had to de+ise a plan that guaranteed that there were ne+er an$ missionaries in the minorit$ at either side o) the ri+er, The cannibals! howe+er! can be trusted to cooperate otherwise, Speci)icall$! the$ wonCt abandon an$ potential )ood! Fust as the missionaries wonCt abandon an$ potential con+erts, "uc.il$ one o) the missionaries had ta.en a Scheme course and .new how to sol+e this problem, 1hile we can sol+e the problem b$ hand! sol+ing it with a Scheme )unction is more )un and more general, I) the same stor$ comes up again with di))erent numbers o) cannibals and missionaries or di))erent boat si*es! we can use the same )unction to sol+e the problem again,

As with e+er$ problem! we begin b$ la$ing out how to represent the problem in our data language and then stud$ how to represent certain actions in the real world in our programming language, Here are two basic constants concerning the data representation:
!define"H7"3# !define"(N';-7'3'7I;I"2#

Formulate the )unction in terms o) these constants, E ercise !2<2<1< Pro+ide a data representation )or the states o) a ri+er crossing, A state should record the number o) missionaries and cannibals on each side o) the ri+er and the location o) the boat, Here is a graphical representation o) the states:

The two lines represent the ri+er! the blac. and white dots the missionaries and cannibals! the blac. rectangle the boat, Determine the initial and )inal state o) the game, Solution E ercise !2<2<2< De+elop a data representation )or boat loads, De)ine (N';-LN'DC! the list o) all possible boat loads, De+elop the )unction ma-e-(N';-LN'DC! which consumes the boatCs ma8imal capacit$ and constructs the list o) possible boat loads, Solution @ne wa$ to deal with search problems in a s$stematic manner is to generate all possible successor states )or the states we ha+e reached so )ar! to )ilter out the interesting ones! and to start the search o+er )rom those, A successor state is reached b$ using a )easible transition! )or e8ample! an enabled mo+e in a game! a boat trip! etc, Here is a graphical illustration o) the situation )or our problem:

The initial state in the top row has )i+e possible successor states! one per )easible boat load, The$ are shown in the second row, Two o) these successor states are illegal! because one side contains more cannibals than missionaries, @ne o) the legal ones is the state in which one missionar$ and cannibal reached the right side o) the ri+erE it has

three successor states in turn, The )ollowing e8ercises deal with generating the successor states and )iltering out the interesting ones, Testing: Formulate all tests as boolean2+alued e8pressions that produce tr.e i) the e8pected +alue is the computed one! and fa+se i) not, E ercise !2<2<!< De+elop a )unction that consumes a state and returns a list o) all possible successor states! that is! all those states that are reachable with one boat trip )rom one side o) the ri+er to the other, De+elop a generali*ed +ersion that consumes a list o) states! and returns a list o) states reachable with one crossing, Solution E ercise !2<2<#< De+elop a )unction that determines whether a gi+en state is legal, A state is legal i) it contains the proper number o) missionaries and cannibals and i) the missionaries on each side o) the ri+er are sa)e, De+elop a generali*ed )unction that consumes a list o) states and returns the sublist o) legal states, Solution E ercise !2<2<$< De+elop a )unction that consumes a state and determines i) it is )inal, De+elop a generali*ed +ersion that consumes a list o) states and returns the sublist o) )inal states, Solution The )unctions we ha+e de+eloped can generate the successor states o) a list o) states and can detect whether an$ o) the states reached so )ar are legal, -ow we can de+elop a )unction that determines whether we can transport the missionaries and cannibals across the ri+er, E ercise !2<2<&< De+elop mc-so+0a8+eA! which consumes a list o) states and generates the list o) all successor states until it has )ound a )inal state, The )unction should simpl$ produce tr.e when it )inds a )inal state, Solution E ercise !2<2<(< De+elop mc-so+.tion, The )unction is an adaptation o) mcso+0a8+eA that not onl$ produces tr.e when it )inds a solution but a list o) ri+er crossings i) a gi+en missionar$2and2cannibal problem is sol+able,

>int' Modi)$ the state representations so that the$ accumulate the list o) crossings that got the group to this particular state, For the initial state! this is Fust the empt$ listE )or a )inal state! it is the desired solution, Solution E ercise !2<2<)< A series o) boat trips ma$ bring the group o) missionaries and cannibals bac. to the initial state /or some other pre+ious state0, The series ma$ include two! )our! or more boat trips, In short! the DDgameCC contains c$cles, Ma.e up an e8ample, The )unction mc-so+.tion generates all those states reachable with! sa$! se+en boat trips be)ore it generates all those states reachable with eight crossings, There)ore we do not ha+e to worr$ about c$cles in solution attempts, 1h$H Modi)$ the solution so that a state reached +ia a c$cle is also illegal, Note: This shows how the accumulator inside the state representation has two uses, Solution

("#( E,tended E,ercise. Board Solitaire


Peg Solitaire is a board game )or indi+iduals, The board comes in +arious shapes, Here is the simplest one:

The circle without a blac. dot represents an unoccupied holeE the other circles are holes containing little pegs, The goal o) the game is to eliminate the pegs one b$ one! until onl$ one peg is le)t, A pla$er can eliminate a peg i) one o) the neighboring holes is unoccupied and i) there is a peg in the hole in the opposite direction, In that case! the second peg can Fump o+er the )irst one and the )irst one is eliminated, Consider the )ollowing con)iguration:

Here the pegs labeled ( and & could Fump, I) the pla$er decides to mo+e the peg labeled &! the ne8t con)iguration is

Some con)igurations are dead2ends, For a simple e8ample! consider the )irst board con)iguration, Its hole is in the middle o) the board, Hence no peg can Fump! because there are no two pegs in a row! column! or diagonal such that one can Fump o+er the

other into the hole, A pla$er who disco+ers a dead2end con)iguration must stop or bac.trac. b$ undoing mo+es and tr$ing alternati+es, E ercise !2<!<1< De+elop a representation )or triangular Solitaire boards, De+elop a data representation )or peg mo+es, Pegs can mo+e along a row! a column! and a diagonal, >ints' /(0 There are at least )our rows! because it is impossible to pla$ the game with three or )ewer, Still! de+elop the data de)inition independentl$ o) such constraints, /&0 Translate our e8amples )rom abo+e into the chosen data representations, Solution E ercise !2<!<2< De+elop a )unction that! gi+en a board and the board position o) a peg! determines whether or not the peg can Fump, 1e call such a peg enab!ed, De+elop a )unction that! gi+en a board and the board position o) an enabled peg! creates a board that represents the ne8t con)iguration, Solution E ercise !2<!<!< De+elop the )unction so+itaire! which sol+es a Solitaire problem )or di))erent si*es o) the e?uilateral triangle, The )unction should consume a board, It produces fa+se! i) the gi+en problem is not sol+able, @therwise! it should produce a list o) mo+es that speci)ies in what order the pegs must be mo+ed to sol+e the gi+en Solitaire problem,

Formulate the tests )or all )unctions as boolean2+alued e8pressions,

Solution

Section !! Interme**o &' The Nature of Ine act Numbers


Computers represent and process in)ormation in chun.s o) a )i8ed si*e, Because computers were )irst used )or numerical calculations! earl$ computer engineers de+eloped a representation )or numbers in terms o) )i8ed2si*e chun.s, Programming languages must mediate the gap between these )i8ed2si*e representations and the true mathematics, Because using the hardware representation )or numbers ma.es a programCs calculations as e))icient as possible! most designers and implementors o) programming languages adopted the hardware2based choice, This interme**o e8plains the )i8ed2si*e representation )or numbers and its conse?uences in some detail, The )irst subsection introduces a concrete )i8ed2si*e representation )or numbers! discusses what it implies )or the representation o) numbers! and shows how to calculate with such numbers, The second and third section illustrate the two most )undamental problems o) )i8ed2si*e number arithmetic: o+er)low and under)low! respecti+el$,

((#$ +i,ed7si9e %um&er

rithmetic

Suppose we can use )our digits to represent numbers, I) we represent natural numbers! the representable range is ' ...>>>>, Alternati+el$ we could represent ('!''' )ractions between ' and ( with that man$ digits, In either case! this is a rather small range o) numbers and not use)ul )or most scienti)ic or business computations, 1e can represent a larger range o) numbers i) we use a di))erent notation )or numbers instead, In science! )or e8ample! we encounter so2called scienti)ic notation! which represents numbers as two parts: (, a MA-TISSA! which is a base number! and &, an #NP@-#-T! which is used to determine a ('2based )actor, For pure scienti)ic notation! the base is between ' and >, 1e rela8 this constraint and Fust write numbers as

where m is the mantissa and e the e8ponent, For e8ample! one representation o) (&'' with this scheme is

another one is

In general! a number has se+eral e?ui+alents in mantissa2e8ponent representation, 1e can also use negati+e e8ponents! which add )ractions at the cost o) one e8tra piece o) data: the sign o) the e8ponent, For e8ample!

stands )or

As be)ore! the )raction has se+eral representations in the new notation, To use a )orm o) mantissa2e8ponent notation )or our problem! we must decide how man$ digits we wish to use )or the representation o) the mantissa and how man$ )or the e8ponent, Here we use two )or each and a sign )or the e8ponentE other choices are possible, =i+en this decision! we can still represent ' as

The ma8imal number we can represent is

which is >> )ollowed b$ >> 'Cs, I) we use negati+e e8ponents in addition to positi+e ones! we can also represent

which is a small number close to ', Thus we can now represent a +astl$ larger range o) numbers with )our digits and a sign than be)ore, But this impro+ement comes with its own problems,

66"create-ine*":"N"N"N""-/""ine* 66"to"ma-e"an"instance"of"ine*"after"chec-ing"the"appropriateness 66"of"the"arg.ments !define"!create-ine*"m"s"e# ""!cond """"9!and"!?&"%"m",,#"!?&"%"e",,#"!or"!&"s"+1#"!&"s"-1### """""!ma-e-ine*"m"s"e#: """"9else """""!error"'ma-e-ine*"1!?&"%"m",,#<"+1"or"-1<"!?&"%"e",,# e*pected1#:## 66"ine--/num*er":"ine*""-/""n.m8er 66"to"con0ert"an"ine*"into"its"n.meric"e).i0a+ent" !define"!ine--/num*er"an-ine*# ""!*"!ine*-mantissa"an-ine*#"

/e8pt (' /T /ine82sign an2ine80 /ine82e8ponent an2ine800000 Figure -#' Functions )or ine8act representations To understand the problems! it is best to agree on a )i8ed representation schema and to e8periment with the number representations, "etCs represent a )i8ed2si*e number with a structure that has three )ields:
!define-struct"ine*"!mantissa"sign"e*ponent##

The )irst and last )ield contain the mantissa and e8ponent o) the number! the sign )ield is +1 or -1 and represents the sign o) the e8ponent, This sign )ield enables us to represent numbers between % and 1, Here is the data de)inition: An ine* is a structure:
!ma-e-ine*"m"s"e#

where m and e are natural numbers in V%!,,W and s is +1 or -1, Because the conditions on the )ields o) an ine* structure are so stringent! we use the )unction create-ine* to create these structures, Figure >6 contains the )unction de)inition )or create-ine*! which is a generali*ed constructor! that is! a chec.ed constructor /see section ;,70, The )igure also de)ines the )unction ine--/num*er! which turns ine*s into numbers according to the principles o) our new notation, "etCs translate the abo+e e8ample! 12%%! into our Scheme representation:
!create-ine*"12"+1"2#

The alternati+e representation! (&' P ('(! is illegal in our Scheme world! howe+er, I) we e+aluate
!create-ine*"12%"+1"1#

we get an error message because the arguments donCt satis)$ the stated data contract, For other numbers! though! we can )ind two ine* e?ui+alents, @ne e8ample is %.%%%%%%%%%%%%%%%%%%5! which we can e8press as
!create-ine*"5%"-1"2%# and !create-ine*"5"-1"1,#

Con)irm the e?ui+alence o) these two representations with ine--/num*er, The range o) ine* numbers is +ast:
!define"H'R-3NCI;IW5"!ma-e-ine*",,"+1",,## !define"HIJ-3NCI;IW5"!ma-e-ine*"1"-1",,##

That is! we can represent large numbers that consist o) up to ('( digits in the standard decimal notationE we can also represent small positi+e )ractions smaller than 1 down to the )raction ( o+er ('...' with >> *eros, The appearances! howe+er! are decei+ing, -ot all real numbers in the range between ' and H'R-3NCI;IW5 can be translated into an ine* structure, In particular! an$ positi+e number less than

has no e?ui+alent ine* structure, Similarl$! the ine* representation has gaps in the middle, For e8ample! the successor o)
!create-ine*"12"+1"2#

is
!create-ine*"13"+1"2#

The )irst ine* structure corresponds to 12%%! the second one to 13%%, -umbers in the middle! such as 124% or 12 %! can onl$ be represented as one or the other, The standard choice is to round the number to the closest representable e?ui+alent, In short! we must appro8imate such mathematical numbers as we translate into a chosen representation, Finall$! we must also consider arithmetic operations on ine* structures, Adding two ine* representations with the same e8ponent means adding the two mantissas:
""!ine*+"!create-ine*"1"+1"%# "!create-ine*"2"+1"%##" &"!create-ine*"3"+1"%#

Translated into mathematical notation! we ha+e

1hen the addition o) two mantissas $ields too man$ digits! we ma$ ha+e to )ind a suitable representation, Consider the e8ample o) adding

to itsel), Mathematicall$ we get

but we canCt Fust translate this number nai+el$ into our chosen representation because ((' S >>, The proper correcti+e action is to represent the result as

@r! translated into Scheme! we must ensure that ine*+ computes as )ollows:
""!ine*+"!create-ine*"55"+1"%# """""""""!create-ine*"55"+1"%##" &"!create-ine*"11"+1"1#

More generall$! i) the mantissa o) the result is too large! we must di+ide it b$ 1% and increase the e8ponent b$ one, Sometimes the result contains more mantissa digits than we can represent, In those cases! ine*+ must round to the closest e?ui+alent in the ine* world, For e8ample:
""!ine*+"!create-ine*"5 "+1"%# """""""""!create-ine*"5 "+1"%##" &"!create-ine*"11"+1"1#

This corresponds to the precise calculation:

Because the result has too man$ mantissa digits! the integer di+ision o) the result mantissa b$ 1% produces an appro8imate result:

This is an e8ample o) the man$ appro8imations that ma.e I-#NACT ARITHM#TIC ine8act, 1e can also multipl$ numbers represented as ine* structures, Recall that

Thus we get:

or! in Scheme notation:


""!ine**"!create-ine*"2"+1"4# "!create-ine*"$"+1"1%##" &"!ma-e-ine*"1 "+1"14#

As with addition! things are not alwa$s straight)orward, 1hen the result has too man$ signi)icant digits in the mantissa! ine** has to increase the e8ponent:
""!ine**"!create-ine*"2%"-1"1# "!create-ine*""5"+1"4##" &"!create-ine*"1%"+1"4#

In the process! ine** will introduce an appro8imation i) the true mantissa doesnCt ha+e an e8act e?ui+alent in the class o) ine* structures:
""!ine**"!create-ine*"27"-1"1# "!create-ine*""7"+1"4##" &"!create-ine*"1,"+1"4#

E ercise !!<1<1< De+elop the )unction ine*+! which adds ine* representations that ha+e the same e8ponent, The )unction must be able to deal with e8amples that increase the e8ponent, Furthermore! it must signal its own error i) the result is out o) range )or ine* representations, Challenge: #8tend ine*+ so that it can deal with inputs whose e8ponents di))er b$ 1:
!e).a+A"!ine*+"!create-ine*"1"+1"%#"!create-ine*"1"-1"1## """"""""!create-ine*"11"-1"1##

Do not attempt to deal with larger classes o) inputs than that without reading the )ollowing subsection, Solution E ercise !!<1<2< De+elop the )unction ine**! which multiplies ine* representations, The )unction must be able to deal with e8amples that increase the e8ponent, Furthermore! it must signal its own error i) the result is out o) range )or ine* representations, Solution E ercise !!<1<!< The section illustrated how an ine8act representation s$stem )or real numbers has gaps, For e8ample! (&6' was represented as !create-ine*"12"+1"2# b$ rounding o)) the last signi)icant digit o) the mantissa, The problem is! round2o)) errors can accumulate, De+elop the )unction add! which adds up n copies o) #i1/1$5, 1hat is the result )or !add"1$5#H 1hat should it beH 1hat happens i) we multipl$ the result o) the second e8pression with a large numberH

De+elop the )unction s.8! which counts how o)ten 1/1$5 can be subtracted )rom the argument until the argument is %, How o)ten should the e+aluation recur be)ore !s.8"1# and !s.8"#i1.# is e+aluatedH 1hat happens in the second caseH 1h$H Solution

((#" ;verflo!
1hile the use o) scienti)ic notation e8pands the range o) numbers we can represent with )i8ed2si*e chun.s o) data! it still doesnCt co+er arbitraril$ large numbers, Some numbers are Fust too big to )it into a )i8ed2si*e number representation, For e8ample!

canCt be represented! because the e8ponent 7'' wonCt )it into two digits! and the mantissa is as large as it can be, -umbers that are too large )or our representation schema can arise during a computation, For e8ample! two numbers that we can represent can add up to a number that we cannot represent:
""!ine*+"!create-ine*"5%"+1",,# """""""""!create-ine*"5%"+1",,## &"!create-ine*"1%%"+1",,#

which +iolates the data contract! or


""!ine*+"!create-ine*"5%"+1",,# """""""""!create-ine*"5%"+1",,## &"!create-ine*"1%"+1"1%%#

which also brea.s the contract )or ine* structures, 1hen the result o) ine* arithmetic produces numbers that are too large to be represented! we sa$ /arithmetic0 @4#RF"@1 occurred, 1hen o+er)low occurs! some language implementations signal an error and stop the computation, @thers designate some s$mbol! called in)init$! )or all numbers that are too large, Arithmetic operations are aware o) in)init$ and propagate it, Negati1e Numbers: I) our ine* structures had a sign )ield )or the mantissa! then two negati+e numbers can add up to one that is so negati+e that it canCt be represented either, This is also called o+er)low! though to emphasi*e the distinction people sometimes sa$ o+er)low in the negati+e direction, E ercise !!<2<1< DrSchemeCs ine8act number s$stem uses an in)init$ +alue to deal with o+er)low, Determine the integer n such that !e*pt"#i1%."n# is still an ine8act Scheme number and !e*pt"#i1%."!+"n"1## is appro8imated with in)init$, >int' Ase a )unction to compute n, Solution

((#( <nderflo!
At the opposite end o) the spectrum! we ha+e alread$ seen small numbers that cannot be represented with ine* structures, For e8ample! ('-7'' is not '! but itCs smaller than the smallest non2*ero number we can represent, An arithemtic A-D#RF"@1 arises when we multipl$ two small numbers and the result is too small to )it into our class o) ine* structures:
""!ine**"!create-ine*"1"-1"1%# """""""""!create-ine*"1"-1",,## &"!create-ine*"1"-1"1%,#

which causes an error, 1hen under)low occurs! some language implementations signal an errorE others use ' to appro8imate the result, An appro8imation with ' )or under)low is ?ualitati+el$ di))erent )rom our ealier .inds o) appro8imations, In appro8imating (&7' with !create-ine*"12 +1"2#! we appro8imated b$ dropping signi)icant digits )rom the mantissa! but we were le)t with a non2*ero mantissa, The result is within ('R o) the number we wanted to represent, Appromi8ating on under)low! howe+er! means dropping the entire mantissa, The result is not within a predictable precentage range o) the true result, E ercise !!<!<1< DrSchemeCs ine8act number s$stem uses #i% to appro8imate under)low, Determine the smallest integer n such that !e*pt"#i1%."n# is still an ine8act Scheme number and !e*pt"#i1%."!-"n"1## is appro8imated with %, >int' Ase a )unction to compute n, Solution

((#) DrScheme>s %um&ers


Most programming languages support onl$ ine8act number representations /and arithmetic0 )or both integers and reals, Scheme! in contrast! supports both e8act and ine8act numbers and arithmetic, @) course! the base o) the representation is &! not ('! because Scheme uses the underl$ing computerCs on2o)) machiner$, As the note on page 7 e8plained! DrSchemeCs teaching le+els interpret all numbers in our programs as e8act rationals! unless the$ are pre)i8ed with #i, Some numeric operations! though! produce ine8act numbers, Plain Scheme! which is called Full Scheme in DrScheme! interprets all numbers with a dot as ine8act numbersE99 it also prints ine8act reals with Fust a dot! impl$ing that all such numbers are ine8act and possibl$ distant )rom the actual result, Scheme programmers can thus choose to use e8act arithmetic or ine8act arithmetic as necessar$, For e8ample! numbers in )inancial statements should alwa$s be interpreted as e8act numbersE arithmetical operations on such numbers should be as precise as possible, For some problems! howe+er! we ma$ not wish to spend the e8tra time to

produce e8act results, Scienti)ic computations are a primar$ e8ample, In such cases! we ma$ wish switch to ine8act numbers and arithmetic, Numerical +nal%sis: 1hen we use ine8act numbers and arithmetic! it is natural to as. how much the programCs results di))ers )rom the true results, @+er the past )ew decades! the stud$ o) this comple8 ?uestion has e+ol+ed into an ad+anced topic! called numerical anal$sis, The discipline has become a subFect o) its own right in applied mathematics or in computer science departments, E ercise !!<#<1< #+aluate
!e*pt"1.%%1"1e-12#

in >.++ Scheme /an$ +ariant0 and in Intermediate"Ct.dent Scheme, #8plain the obser+ations, Solution E ercise !!<#<2< De+elop the )unction m2-e*pt! which raises one number to the power o) some integer, Asing this )unction! conduct the )ollowing e8periment, Add
!define"ine*"!+"1"#i1e-12## !define"e*ac"!+"1"1e-12##

to the Definitions window, 1hat is !m2-e*pt"ine*"3%#H How about !m2-e*pt e*ac"3%#H 1hich answer is more use)ulH Solution E ercise !!<#<!< 1hen we add two ine8act numbers o) +astl$ di))erent orders o) magnitude! we ma$ get the larger one bac. as the result, For e8ample! i) we are using onl$ (7 signi)icant digits! then we run into problems when adding numbers which +ar$ b$ more than a )actor o) ('(9:

but i) the number s$stem supports onl$ (7 digits! the closest answer is ('(9, At )irst glance! this doesnCt loo. too bad, A)ter all! being wrong b$ one part in ('(9 /ten million billion0 is close enough to the accurate result, An)ortunatel$! this .ind o) problem can add up to huge problems, Consider the )ollowing list o) ine8act numbers:
!define"T'JPC ""!+ist"#i31 """"""""#i2e+34 """"""""#i-1.2345 7$,%1235e+$% """"""""#i274, """"""""#i-2,3,234 """"""""#i-2e+33 """"""""#i3.2e+27% """"""""#i17

""""""""#i-2.4e+27% """"""""#i4.23442,473$44 e+17% """"""""#i1 """"""""#i-$e+2 , """"""""#i% """"""""#i,,##

Determine the +alues !s.m"T'JPC# and !s.m"!re0erse"T'JPC##, #8plain the di))erence, Can we trust computersH Solution

1e can )orce Full Scheme to interpret numbers with a dot as e8act b$ pre)i8ing the numbers with [e,
99

Part "II Changing the State of "ariables Section !# /emor% for Functions
Ad+anced Student -o matter how o)ten we use a )unction with one and the same argument! we alwa$s get the same result, #+en an accumulator2st$le )unction produces the same result e+er$ time we appl$ it to the same argument! as long as the accumulator argument is also the same, Functions simpl$ do not ha+e an$ memor$ about their past uses, Man$ programs! though! must remember something about their past uses, Recall that a program t$picall$ consists o) se+eral )unctions, In the past we ha+e alwa$s assumed that there is one main )unction and that all others are au8iliar$ and in+isible to the user, In some cases! howe+er! a user ma$ e8pect more than one ser+ice )rom a program! and each ser+ice is best implemented as a )unction, 1hen a program pro+ides more than one )unction as a ser+ice to the user! it is common that! )or sheer con+enince or possibl$ because we add a graphical user inter)ace! the )unctions must ha+e memor$, Because this point is di))icult to grasp in the abstract! we stud$ some e8amples, The )irst one concerns a program )or managing telephone numbers in an address boo., The standard address boo. so)tware pro+ides at least two ser+ices: (, a ser+ice )or loo.ing up the phone number o) some personE and &, a ser+ice )or adding a name and a phone number to the address boo.,

Based on our guidelines! the program pro+ides two )unctions to the user, The user can appl$ those )unctions in DrSchemeCs Interactions window to appropriate data, @r! we can de+elop a graphical user inter)ace with te8t )ields and buttons so that the user doesnCt need to .now an$thing about programming, Figure >7 displa$s such an inter)ace,

Figure -$' A phoneboo. =AI The two ser+ices roughl$ correspond to two )unctions:
66"+oo-.p":"+ist-of-s2m8o+-n.m8er-pairs"s2m8o+""-/"""n.m8er"or fa+se 66"to"+oo-.p"the"n.m8er"associated"with"name"in"p8 66"if"it"doesnKt"find"name<"the"f.nction"prod.ces"fa+se !define"!+oo-.p"p8"name#"...# 66"add-to-address-8oo-":"s2m8o+"n.m8er""-/""0oid 66"to"add"name"and"n.m8er"to"address-8oo!define"!add-to-address-8oo-"name"n.m8er#"...# !define"'DDQ5CC-(NN\" ""!+ist"!+ist"''dam"1# """"""""!+ist"'50e"2###

1e also introduce a +ariable de)inition )or maintaining a list o) name2number associations, The )irst )unction is a +ariant o) our +er$ )irst recursi+e )unction, A user applies it to a list o) name2number associations! such as 'DDQ5CC-(NN\! and a name, It produces a number! i) the name is on the list! or fa+se otherwise, The second )unction is radicall$ di))erent )rom what we ha+e seen, The user would appl$ it to a name and a numberE an$ )uture loo.up o) that name would then produce that number, "etCs imagine an interaction in DrScheme:
/"!+oo-.p"'DDQ5CC-(NN\"''dam# 1" /"!+oo-.p"'DDQ5CC-(NN\"'Dawn# fa+se /"!add-to-address-8oo-"'Dawn"4# /"!+oo-.p"'DDQ5CC-(NN\"'Dawn# 4

The )irst two con)irm that ''dam has the phone number 1 and that we donCt ha+e a phone number )or 'Dawn, The third one adds the phone number 4 )or 'Dawn to 'DDQ5CC-(NN\, And the last interaction shows that the +er$ same use o) +oo-.p as be)ore now produces the e8pected phone number,

In the past! the onl$ wa$ we could ha+e achie+ed this same e))ect is b$ editing the de)inition o) 'DDQ5CC-(NN\, But! we do not wish users to edit our programs, Indeed! the$ shouldnCt e+en ha+e access to our programs, 1e are there)ore )orced to pro+ide an inter)ace with a )unction that permits such changes, 1e could go e+en )urther and implement the graphical inter)ace o) )igure >7, A dialogue e?ui+alent to the abo+e interaction would proceed as )ollows: (, T$pe 'dam into the te8t )ield! clic. the Loo-.p button! and DD(CC appears in the lower te8t )ield, &, #nter Dawn into the te8t )ield! clic. the Loo-.p button! and some message concerning a missing number appears in the lower te8t )ield, 5, Replace the message with DD6CC and clic. the 'dd button, 6, #rase the DD6CC )rom the lower te8t )ield! clic. the Loo-.p and the DD6CC shows up again, In short! pro+iding a con+enient inter)ace to a user )orces us to de+elop a program whose )unctions .now about each otherCs usage histor$,

Figure -&' The three stages o) a tra))ic light can+as and its =AI The second e8ample! a tra))ic light simulation! illustrates how a single )unction ma$ need to ha+e some memor$, Recall the )unction ne*t )rom e8ercise 9,&,7, It consumes the current color o) a tra))ic light and! with the help o) c+ear-8.+8 and draw-8.+8! switches the state o) the tra))ic light on a can+as to the ne8t tra))ic color, The result is the ne8t color, A user who wishes to switch the tra))ic light )our times in a row must enter
!ne*t"!ne*t"!ne*t"!ne*t"'red####

into the Interactions window, An e+en more con+enient user inter)ace! howe+er! would pro+ide a button that the user can clic., Pro+iding a button means pro+iding a call2bac. )unction that somehow .nows about the current state o) the tra))ic light and changes it, "etCs call this )unction ne*t! too! but letCs assume that it consumes no arguments, Here is an imaginar$ interaction using this )unction:
/"!ne*t# /"!ne*t# /"!ne*t#

#+er$ time we appl$ ne*t to no arguments! it produces the in+isible +alue and simulates the switch o) state in the tra))ic light on the can+as, In other words! the can+as c$cles through the three states depicted in )igure >9, #?ui+alentl$! we can ha+e a user clic. the DD-#NTCC button three times! which would appl$ the ne8t )unction and ha+e the same +isual e))ect, To accomplish this e))ect! the use o) ne*t must a))ect its own )uture uses,

Figure -(' Three stages in the hangman game and its =AI The )inal e8ample concerns the hangman game! which is also the subFect o) section 9,;, The game program re?uires us to de+elop three )unctions: ma-e-word! re0ea+! and draw-ne*t-part, 1e start the game b$ e+aluating
!hangman"ma-e-word"re0ea+"draw-ne*t-part#

which pic.s a word! creates the graphical user inter)ace o) the lower hal) o) )igure >;! and draws the le)t2most picture in the se?uence o) the upper hal) o) the )igure, The pla$er can then choose a letter )rom the choice menu in the =AI and clic. on the DDChec.CC button to determine whether the letter occurs in the word, I) so! the hangman )unction re+eals where the letter occursE i) not! it uses our draw-ne*t-part )unction to draw the ne8t stage in the hangman picture, The more bad guesses the pla$er ma.es! the more o) the stic. )igure appears in the picture /see top2hal) o) )igure >;0, @ur description suggests that the hangman )unction in the teachpac. emplo$s a callbac. )unction )or the DDChec.CC button, "etCs call this )unction chec-, It consumes the letter and produces tr.e i) the chec. re+eals new .nowledge:
/"!chec-"'8# tr.e

I) not! because the letter has alread$ been guessed! the )unction produces fa+se to indicate that the pla$er didnCt gain new .nowledge:
/"!chec-"'8# fa+se

In this case! chec- also emplo$s draw-ne*t-part to draw another part o) the hangman )igure, @) course! to accomplish this! hangman and chec- must ha+e some memor$ about how o)ten the DDChec.CC button was used and how o)ten it was used with a negati+e result, 1ith our current .nowledge o) Scheme! we cannot )ormulate )unctions such as add-toaddress-8oo-! ne*t! or chec-, To )ill this gap in our .nowledge! the ne8t section introduces set!9; e8pressions, This new )orm o) e8pression permits )unctions to change the +alue that a defined +ariable represents, Asing this new construct! we can )ormulate Scheme )unctions that ha+e memor$, That is! we can de)ine )unctions that .now something about their histor$ and the histor$ o) other )unctions,

9;

This .e$word is pronounced set2bang,

Section !$ +ssignment to "ariables


A setD2e8pression! also .nown as an ASSI=-M#-T! has the )ollowing shape:
!set!"0ar"e*p#

It consists o) a +ariable! the "#FT2HA-D SID#! and an e8pression! called RI=HT2HA-D SID#, The le)t2hand side o) a setD2e8pression is a )i8ed +ariable, In this boo.! we onl$ use +ariables that are defined! either at the top2le+el or in a local2e8pression, A setD2 e8pression ma$ occur where+er an e8pression is legal, The +alue o) a setD2e8pression is alwa$s the same and is moreo+er in+isible, It is there)ore irrele+ant, 1hat matters about a setD2e8pression! instead! is the e))ect o) its e+aluation, Speci)icall$! )or the )irst step o) the e+aluation o) a setD2e8pression! we determine the +alue o) e*p, "etCs sa$ this +alue is W, For the second step! we change the de)inition o) 0ar to
!define"0ar"W#

The #FF#CT o) this second step is that )rom this point on! all re)erences to 0ar in an e+aluation replace 0ar b$ W,9< Its )ormer +alue is lost, Anderstanding the true nature o) assignments is di))icult, 1e there)ore )irst consider a simple though useless e8ample,

(*#$ Simple

ssignments at Work

Consider the )ollowing de)inition and e8pression:


!define"*"3# !local"!!define"@"!set!"*"!+"*"2#### ""*#

The de)inition sa$s that * stands )or 3, The local2e8pression introduces a de)inition )or @, Its bod$ is * so! in the past! the +alue o) this local2e8pression would ha+e been 3 /i) an$thing0, -ow! with set! in the language! this is no longer true, To understand what happens! we must rewrite the program step b$ step until we ha+e a )inal answer, The )irst step in the e+aluation li)ts the local de)inition:

!define"*"3# !define"@"!set!"*"!+"*"2### *

-e8t we must determine the +alue o) !set!"*"!+"*"2##, According to the general e8planation o) set!! this re?uires the e+aluation o) the right2hand side o) the assignment:
!define"*"3# !define"@"!set!"*"5## *

That +alue is 5 because the current +alue o) * is 3, Finall$! the general e8planation sa$s that the e))ect o) the set! e8pression is to change the +alue that the le)t2hand side +ariable represents, In our e8ample this means that )rom now on! * is no longer 3 but 5, The best wa$ to e8press this change is to modi)$ the de)inition o) * )or the ne8t step:
!define"*"5# !define"@"!0oid## *

The +alue o) set! is !0oid#! the in+isible +alue, B$ replacing the setD2e8pression with the in+isible +alue! we indicate that its e+aluation is )inished, At this point! it is eas$ to see that the result is 5, The )irst de)inition sa$s that * currentl$ represents 5! and the last e8pression is *, Hence the +alue o) the )unction e+aluation is 5, E ercise !$<1<1< Consider the )ollowing:
1. !set!"*"5#

&,
3. !define"*"3# 4. 5. !set!"!+"*"1#"5#

9,
7. !define"*"3# $. !define"2"7# ,. !define"@"fa+se# 1%. 11.!set!"!@"*"2#"5#

(&,

1hich ones are s$ntacticall$ legal programsH 1hich ones are illegalH E ercise !$<1<2< #+aluate the )ollowing program:
!define"*"1# !define"2"1# !local"!!define"."!set!"*"!+"*"1### !define"0"!set!"2"!-"2"1#### ""!*"*"2##

Solution

I) set! were not a part o) the language! what could we sa$ about the result o) the local2 e8pressionH That is! consider the s.eleton
!define"*"1# !define"2"1# !local"!!define"."...# !define"0"...## ""!*"*"2##

where the right2hand sides o) the de)initions ha+e been remo+ed, 1hat would this e8pression ha+e produced be)ore the introduction o) setD2e8pressionsH Solution

(*#" Se:uencing E,pression Evaluations


The hand2e+aluation shows that the local de)inition )or @ ser+es to e+aluate a setD2 e8pression and DDto throw awa$CC its +alue, A)ter all! a set!Cs true purpose is to change a de)inition and not to generate a +alue, Because this situation is ?uite common! Scheme also pro+ides the begin2e8pression:
!begin"e*p-1 """""""... """""""e*p-n """""""e*p#

A begin2e8pression consists o) the .e$word begin )ollowed b$ a se?uence o) n I ( e8pressions, The e+aluation determines the +alues o) all e8pressions! in order! and then throws awa$ the )irst n, The +alue o) the last e8pression is the +alue o) the entire begin2 e8pression, In general! the )irst n sube8pressions in a begin2e8pression change some de)initionsE onl$ the last one has an interesting +alue, 1e can now rewrite our )irst sample program with set! into a short e8pression:
!define"*"3# !begin"!set!"*"!+"*"2## """""""*#

The use o) begin not onl$ simpli)ies the program! it also suggests a straight2line ordering o) the e+aluation, The hand2e+aluation also shows that the e+aluation o) setD2e8pression introduces additional timing constraints, More concretel$! the abo+e e+aluation consists o) two parts: the one be)ore and the one a)ter the assignment e8erted its e))ect on the state o) the de)initions, Be)ore we introduced assignments! we could replace a +ariable b$ its +alue or a )unction application b$ the )unctionCs bod$ whene+er we wished, -ow! we must wait until we trul$ need the +alue o) a +ariable be)ore we per)orm the substitution, A)ter all! de)initions ma$ change, 1hile some partial ordering is alwa$s a part o) computation! the timing constraints o) set! are new, B$ altering a de)inition! an assignment DDdestro$sCC the current +alue, Anless the programmer care)ull$ plans the arrangement o) assignments! such an action ma$ be )atal, The e8ercises illustrate the problem in more detail, E ercise !$<2<1< #+aluate the )ollowing program b$ hand:
!define"*"1# !define"2"1# !begin"!set!"*"!+"*"1## """""""!set!"2"!-"2"1## """""""!*"*"2##"""""""

How man$ time periods can we distinguish in this hand2e+aluationH Compare this with the e+aluation o)
!define"a"5# !*"!+"a"1#"!-"a"1###"""""""

Does the nesting impl$ an ordering among our calculationsH Does the order o) addition and subtraction matterH Solution E ercise !$<2<2< #+aluate the )ollowing program b$ hand:
!define"*"3# !define"2"5# !begin"!set!"*"2# """""""!set!"2"*# """""""!+ist"*"2##"

How man$ time periods can we distinguish in this hand2e+aluationH

-ow e+aluate the )ollowing:


!define"*"3# !define"2"5# !local"!!define"@"*## ""!begin"!set!"*"2# """""""""!set!"2"@# """""""""!+ist"*"2###

Is it true that the de)inition o) * contains the initial +alue o) 2 and 2 contains the initial +alue o) * a)ter the two setD2e8pressions are e+aluated! no matter what the initial +alues areH Discuss what the two e8amples teach us about time and DDdestruction o) +aluesCC in de)initions, Solution E ercise !$<2<!< #+aluate the )ollowing program b$ hand:
!define"*"3# !define"2"5# !begin" ""!set!"*"2# ""!set!"2"!+"2"2## ""!set!"*"3# ""!+ist"*"2##

How man$ time inter+als must we distinguish in this hand2e+aluationH

Solution

(*#(

ssignments and +unctions

An assignment can also occur in a )unction bod$:


!define"*"3# !define"2"5# !define"!swap-*-2"*%"2%# ""!begin """"!set!"*"2%# """"!set!"2"*%### !swap-*-2"*"2#

Here the )unction swap-*-2 consumes two +alues and per)orms two set!s, "et us see how the e+aluation wor.s, Because !swap-*-2"*"2# is a )unction application! we need to e+aluate the arguments! which are plain +ariables here, So we replace the +ariables with their /current0 +alues:

!define"*"3# !define"2"5# !define"!swap-*-2"*%"2%# ""!begin """"!set!"*"2%# """"!set!"2"*%### !swap-*-2"3"5#

From here we proceed with the usual substitution rule )or application:
!define"*"3# !define"2"5# !define"!swap-*-2"*%"2%# ""!begin """"!set!"*"2%# """"!set!"2"*%### !begin ""!set!"*"5# ""!set!"2"3##

That is! the application is now replaced b$ an assignment o) * to the current +alue o) 2 and o) 2 to the current +alue o) *, The ne8t two steps are also the last ones and thus the$ accomplish what the name o) the )unction suggests:
!define"*"5# !define"2"3# !define"!swap-*-2"*%"2%# ""!begin """"!set!"*"2%# """"!set!"2"*%### !0oid#

The +alue o) the application is in+isible because the last e8pression e+aluated was a setD2e8pression, In summar$! )unctions with set! ha+e results and e))ects, The result ma$ be in+isible, E ercise !$<!<1< Consider the )ollowing )unction de)inition:
!define"!f"*"2# ""!begin" """"!set!"*"2# """"2##

Is it s$ntacticall$ legal or illegalH

Solution

E ercise !$<!<2< #+aluate the )ollowing program b$ hand:


!define"*"3# !define"!increase-*# ""!begin """"!set!"*"!+"*"1## """"*## !increase-*# !increase-*# !increase-*#

1hat is the resultH 1hat is increase-*Cs e))ectH

Solution

E ercise !$<!<!< #+aluate the )ollowing program b$ hand:


!define"*"%# !define"!switch-*# ""!begin """"!set!"*"!-"*"1## """"*## !switch-*# !switch-*# !switch-*#

1hat is the resultH 1hat is switch-*Cs e))ectH

Solution

E ercise !$<!<#< #+aluate the )ollowing program b$ hand:


!define"*"%# !define"2"1# !define"!change-to-3"@# ""!begin """"!set!"2"3# """"@## !change-to-3"*#

1hat is the e))ect o) change-to-3H 1hat is its resultH

Solution

(*#)

+irst <seful E,ample

"etCs ta.e a loo. at the de)initions in )igure ><, The )unction add-to-address-8ooconsumes a s$mbol and a number, The )ormer represents a name! the latter a phone number, Its bod$ contains a setD2e8pression )or address-8oo-! a +ariable defined at

top2le+el, The )unction +oo-.p consumes an address boo. and a nameE its result is the matching phone number or fa+se! i) the name is not in address-8oo-,
!define"address-8oo-"empt2# 66"add-to-address-8oo-":"s2m8o+"n.m8er""-/""0oid !define"!add-to-address-8oo-"name"phone# ""!set!"address-8oo-"!cons"!+ist"name"phone#"address-8oo-### 66"+oo-.p":"s2m8o+"!listof"!+ist"s2m8o+"n.m8er##""-/""n.m8er"or fa+se 66"to"+oo-.p"the"phone"n.m8er"for"name"in"a8 !define"!+oo-.p"name"a8# ""!cond """"9!empt2A"a8#"fa+se: """"9else"!cond """"9!s2m8o+&A"!first"!first"a8##"name# """""!second"!first"a8##:

Velse /loo.up name /rest ab00W0W00 Figure -)' The basic address2boo. program Asing +oo-.p! we can stud$ the e))ect o) the set! e8pression in add-to-address8oo-, Suppose we e+aluate !+oo-.p"''dam"address-8oo-# with the gi+en de)initions:
""!+oo-.p"''dam"address-8oo-# &"!+oo-.p"''dam"empt2# &"!cond """"9!empt2A"empt2#"fa+se: """"9else"...:# &"fa+se

Because address-8oo- is empt2! we get fa+se! and the calculation is straight)orward, -ow letCs e+aluate the )ollowing in the Interactions window:
!begin"!add-to-address-8oo-"''dam"1# """""""!add-to-address-8oo-"'50e"2# """""""!add-to-address-8oo-"'7hris" 1453$4##

The )irst sube8pression is a plain )unction application, So! the )irst step relies on the usual law o) substitution:9>
!define"address-8oo-"empt2# !begin"!set!"address-8oo-"!cons"!+ist"''dam"1#"address-8oo-## """""""!add-to-address-8oo-"'50e"2# """""""!add-to-address-8oo-"'7hris" 1453$4##

The ne8t e8pression to be e+aluated is the setD2e8pression that is nested in the begin2 e8pressions! in particular its right2hand side, The )irst argument to cons is a +alue! but the second one is still a +ariable whose current +alue is empt2, 1ith this! we can see what happens ne8t:
!define"address-8oo-"empt2#

!begin"!set!"address-8oo-"!cons"!+ist"''dam"1#"empt2## """""""!add-to-address-8oo-"'50e"2# """""""!add-to-address-8oo-"'7hris" 1453$4##

At this point we are read$ to e+aluate the setD2e8pression, Speci)icall$! we change the de)inition o) address-8oo- so that the +ariable now stands )or !cons"!+ist"''dam"1# empt2#:
!define"address-8oo""!cons"!+ist"''dam"1# """"empt2## !begin"!0oid# """""""!add-to-address-8oo-"'50e"2# """""""!add-to-address-8oo-"'7hris" 1453$4##

The begin2e8pression throws awa$ the in+isible +alue, #+aluating the remaining applications o) add-to-address-8oo- $ields
!define"address-8oo""!+ist"!+ist"'7hris" 1453$4# !+ist"'50e"2# !+ist"''dam"1### !0oid#

In short! the three applications turn address-8oo- into a list o) three pairs, I) we now e+aluate !+oo-.p"''dam"address-8oo-# in the Interactions window again! we get 1:
""!+oo-.p"''dam"address-8oo-# &"!+oo-.p"''dam"!+ist"!+ist"'7hris" 1453$4# """"""!+ist"'50e"2# """"""!+ist"''dam"1## &"... &"1

The comparison o) this e+aluation and the one at the beginning o) the section shows how set! changes the meaning o) address-8oo- o+er time and how the two )unctions! add-to-address-8oo- and +oo-.p! implement the ser+ices that we discussed in section 56, The e8ercises show how use)ul this collaboration o) two )unctions is in the conte8t o) a graphical user inter)ace, E ercise !$<#<1< The so)tware )or managing address boo.s permits users to remo+e entries, De+elop the )unction
66"remo0e":"s2m8o+""-/""0oid !define"!remo0e"name#"...#

which changes address-8oo- so that all )uture +oo-.ps )or name $ield fa+se, Solution E ercise !$<#<2< The teachpac. phone-boo .ss implements a graphical user inter)ace based on the model2+iew pattern discussed in section &&,5, Figure >7 shows what the graphical user inter)ace o))ers: (, a te8t2)ield )or entering a nameE &, a te8t2)ield )or displa$ing the search result and )or entering a phone numberE 5, a button )or loo.ing up the phone number )or a nameE 6, a button )or adding a name and a phone numberE and 7, a button )or remo+ing the phone number )or a name, Ase the teachpac.Cs connect )unction to create a =AI )or the )unctions in this section and in e8ercise 57,6,(, The )unction has the )ollowing contract! purpose! and header:
66"mode+-;"&"!8.ttonF"contro+-e0entF""-/""tr.e# 66"connect":"mode+-;"mode+-;"mode+-;""-/""tr.e !define"!connect"+oo-.p-c8"change-c8"remo0e-c8#"...#

That is! it consumes three model )unctions and wires them up with the =AI, The names o) the parameters speci)$ which call2bac. )unction goes with which button, A model )unction ma$ obtain the contents o) the name )ield with !name-contro+# and the contents o) the number )ield with !n.m8er-fie+d#, Solution 1e ha+e alread$ encountered se+eral .inds o) e))ects: drawing to a can+as! changing the te8t )ield in a =AI! the creating o) )iles b$ teachpac.s! and so on, These e))ects arenCt as comple8 as those o) setD because the$ donCt a))ect the program proper,
9<

Because the calculation does not a))ect the )unction de)initions! we do not include them in the calculation here, This con+ention sa+es space and time! but it should be used care)ull$,
9>

Section !& Designing Functions 3ith /emor%


Section 56 moti+ated the idea o) )unctions with memor$E section 57 e8plained how +ariable de)initions and set! together can achie+e the e))ect o) memor$, It is now time to discuss the design o) programs with memor$, Designing )unctions with memor$ re?uires three important steps: (, 1e must determine that a program re?uires memor$, &, 1e must identi)$ the data that goes into the memor$, 5, 1e must understand which o) the ser+ices are supposed to modi)$ the memor$ and which are to use the memor$, The need )or the )irst step is ob+ious, @nce we .now that a program re?uires memor$! we must conduct a data anal$sis )or the programCs memor$, That is! we must )igure out what .ind o) data the program puts into memor$ and retrie+es )rom there, Finall$! we must care)ull$ design those )unctions )or the program that change the memor$, The others are those that use the +ariables /without modi)ication0E the$ are t$picall$ designed with one o) the recipes we ha+e alread$ discussed,

(-#$ The %eed for /emory


Programs need memor$ because we want them to wor. with users who .now little or nothing about programming, #+en i) we wanted users to emplo$ DrSchemeCs Interactions window! we would organi*e our programs so that each ser+ice corresponds to a )unction and the )unctions collaborate through memor$, 1ith graphical user inter)aces! we are almost )orced to thin. o) programs as a collection o) collaborating )unctions attached to +arious widgets in a window, Finall$! e+en programs that wor. in ph$sical de+ices such as ele+ators or 4CRs are )orced to interact with the de+ice in some )i8ed wa$! and that o)ten includes .eeping around in)ormation about the histor$ o) de+ice2program interactions, In short! the inter)ace between the program and the rest o) the world dictates whether a program needs memor$ and what .ind o) memor$ it needs,

Fortunatel$ it is relati+el$ eas$ to recogni*e when programs need memor$, As discussed alread$! there are two situations, The )irst in+ol+es programs that pro+ide more than one ser+ice to users, #ach ser+ice corresponds to a )unction, A user ma$ appl$ these )unctions in DrSchemeCs Interactionswindow! or the$ ma$ be applied in response to some user action in a graphical user inter)ace, The second in+ol+es a program that pro+ides a single ser+ice and is implemented with a single user2le+el )unction, But the program ma$ ha+e to produce di))erent answers when it is applied to the same arguments, "et us ta.e a loo. at some concrete e8amples )or each situation, So)tware )or managing an address boo. is a classical e8ample o) the )irst .ind, In sections 56 and 57! we saw how one )unction adds entries to the address boo. and another loo.s them up, Clearl$! the use o) the DDaddition ser+iceCC a))ects )uture uses o) the DDloo.up ser+iceCC and there)ore re?uires memor$, Indeed! the memor$ in this case corresponds to a natural ph$sical obFect: the address boo. that people used to .eep be)ore there were electronic noteboo.s,

Figure --' @rgani*ational charts )or programs with memor$ -e8t! consider a warehouse with a cler. that registers the items that people deli+er and pic. up, #+er$ time someone deli+ers an item! the cler. enters it into a ledgerE an in?uir$ )or a speci)ic item triggers a search in the ledgerE when someone pic.s up an item! the cler. remo+es it )rom the ledger, I) we were to pro+ide a )unction )or managing the ledger! the program would ha+e to o))er three ser+ices: one )or entering items! one )or searching in the ledger! and one )or remo+ing entries )rom the ledger, @) course! we canCt remo+e something that isnCt in the warehouse! so the program must ensure that the two ser+ices interact properl$, The memor$ in this program will be similar to the ledgers that warehouse cler.s use /or used0! that is! a ph$sical obFect, The second class o) memor$ need also has classical e8amples, The tra))ic light simulation mentioned in section 56 is one o) them, Recall that the description o) the program ne*t sa$s that e+er$ time it is applied! it redraws the picture on a can+as according to the common tra))ic rules, Because two e+aluations o) !ne*t# in a row produce two di))erent e))ects! this program needs memor$, For another e8ample! ta.e a loo. at the Scheme )unction random, It consumes a natural number n S ( and produces a number between ' and n - (, I) we e+aluate !random"1%#

twice in a row! we ma$ or ma$ not obtain the same digit, Again! to achie+e this e))ect! the implementor o) random needed to e?uip the )unction with some memor$, In general! as we anal$*e a problem statement! we should draw organi*ation charts, Figure >> contains sample charts )or the phone2boo. and the tra))ic2light programs, The$ represent each ser+ice that the program is to support with a rectangular bo8, Arrows going into the bo8 indicate what .ind o) data a ser+ice consumesE outgoing arrows speci)$ the output, Memor$ is represented with circles, An arrow )rom a circle to a bo8 means that the ser+ice uses the memor$ as an inputE an arrow to a circle means that the ser+ice changes the memor$, The two charts show that ser+ices commonl$ use memor$ and change it,

(-#" /emory and State 'aria&les


Memor$ is implemented with +ariable de)initions, The memor$2using programs we ha+e seen use a single +ariable to represent the memor$ o) a )unction, In principle! a single +ariable is enough to implement all memor$ needs! but this is usuall$ incon+enient, T$picall$! the memor$ anal$sis suggests how man$ +ariables we need and which ser+ices need which +ariables, 1hen memor$ changes! the corresponding +ariables assume a new +alue or! put di))erentl$! the state o) the +ariable declaration changes and re)lects the memor$ change o+er time, 1e there)ore re)er to +ariables that implement memor$ as STAT# 4ARIAB"#S, #+er$ ser+ice in a program corresponds to a )unction that ma$ emplo$ au8iliar$ )unctions, A ser+ice that changes the memor$ o) a program is implemented with a )unction that uses set! on some o) the state +ariables, To understand how a )unction should change a state +ariable! we need to .now what .ind o) +alues the +ariable ma$ represent and what its purpose is, In other words! we must de+elop a contract and a purpose statement )or state +ariables in the same manner in which we de+elop contracts and purpose statements )or )unction de)initions, "et us ta.e a loo. at the address2boo. and the tra))ic2light e8amples, The )irst one has one state +ariable: address-8oo-, It is intended to represent a list o) entries! where each entr$ is a list o) two items: a name and a number, To document that address-8oo- ma$ represent onl$ such lists! we add a contract as )ollows:
66"address-8oo-":"!listof"!+ist"s2m8o+"n.m8er## 66"to"-eep"trac-"of"pairs"of"names"and"phone"n.m8ers !define"address-8oo-"empt2#

B$ the de)inition o) !listof"R#! it is permissible to use empt2 as the initial +alue o) address-8oo-, From the contract )or the state +ariable! we can conclude that the )ollowing assignment is nonsensical:

!set!"address-8oo-"5#

It sets address-8oo- to 5! which is not a list, The e8pression there)ore +iolates the state +ariableCs contract, But
!set!"address-8oo-"empt2#

is proper! because it sets address-8oo- bac. to its initial +alue, Here is a third assignment:
!set!"address-8oo-"!cons"!+ist"''dam"1#"address-8oo-##

It helps us gain some understanding o) how )unctions can change the +alue o) address8oo- in a use)ul manner, Because address-8oo- stands )or a list o) lists! !cons"!+ist ''dam"1#"address-8oo-# constructs a longer list o) the right .ind, Hence the set! e8pression Fust changes the state +ariable to stand )or a di))erent +alue in the class o) !listof"!+ist"s2m8o+"n.m8er##, A program that controls a tra))ic light should ha+e a state +ariable )or the current color o) the tra))ic light, This +ariable should assume one o) three +alues: 'red! 'green! or '2e++ow! which suggests a data de)inition: A TL-co!or is either 'green! '2e++ow! or 'red, Here is the +ariable de)inition with a contract and purpose statement:
66"c.rrent-co+or":";L-co+or 66"to"-eep"trac-"of"the"c.rrent"co+or"of"the"traffic"+ight !define"c.rrent-co+or"'red#

As be)ore! the e8pression


!set!"c.rrent-co+or"5#

is nonsensical because 5 is not one o) the three legitimate s$mbols mentioned in the contract, In contrast!
!set!"c.rrent-co+or"'green#

is per)ectl$ o.a$, The right2hand side o) an assignment does not ha+e to consist o) a +alue or an e8pression that almost instantaneousl$ produces a +alue, In man$ cases it ma.es sense to use a )unction to compute the new +alue, Here is a )unction that computes the ne8t color )or our tra))ic light:
66"ne*t-co+or":";L-co+or""-/"";L-co+or 66"to"comp.te"the"ne*t"co+or"for"a"traffic"+ight" !define"!ne*t-co+or"c# ""!cond """"9!s2m8o+&A"'red"c#"'green:

""""9!s2m8o+&A"'green"c#"'2e++ow: """"9!s2m8o+&A"'2e++ow"c#"'red:##

Asing this )unction! we can now write an assignment that switches the state o) c.rrent-co+or appropriatel$:
!set!"c.rrent-co+or"!ne*t-co+or"c.rrent-co+or##

Because c.rrent-co+or is one o) the three legitimate s$mbols! we can appl$ ne*tco+or to the +alue o) c.rrent-co+or, The )unction also produces one o) these three s$mbols! so that the ne8t state o) c.rrent-co+or is again proper,

(-#( +unctions that 3nitiali9e /emory


A)ter we ha+e de+eloped contracts and purpose statements )or the state +ariables o) a program! we immediatel$ de)ine a )unction that sets the state +ariables to proper +alues, 1e call this )unction an I-ITIA"IMATI@- FA-CTI@- or an I-ITIA"IM#R, A programCs initia+i@er is the )irst )unction that is used during an e8ecutionE a program ma$ also pro+ide other means to in+o.e the initiali*er, For our current e8amples! the initiali*ers are straight)orward, Here is one )or the address2boo. e8ample:
66"init-address-8oo-":""-/""0oid" !define"!init-address-8oo-# ""!set!"address-8oo-"empt2##

The one )or tra))ic2light is e?uall$ tri+ial:


66"init-traffic-+ight":""-/""0oid" !define"!init-traffic-+ight# ""!set!"c.rrent-co+or"'red##

In setting c.rrent-co+or to 'red! we )ollow a con+entional rule o) engineering to put de+ices into their least harm)ul state when starting it up,;' At )irst glance! these initiali*ers donCt seem to add much to our programs, Both set the respecti+e state +ariables to the +alues that are their de)ined +alues, For both cases! howe+er! it is eas$ to see that the initiali*er could do some additional use)ul wor., The )irst one! )or e8ample! could create and displa$ the graphical user inter)ace )or an address boo.E the second one could create and displa$ a can+as that displa$s the current state o) the tra))ic light,

(-#) +unctions that Change /emory


@nce we ha+e the state +ariables and their initiali*ers in place! we turn our attention to the design o) )unctions that modi)$ a programCs memor$, Anli.e the )unctions in the preceding parts o) the boo.! the memor$2changing )unctions not onl$ consume and

produce data! the$ also a))ect the de)initions o) the state +ariables, 1e there)ore spea. o) the #FF#CT that )unctions ha+e on the state +ariables,
66"Data"Def.:"'"&.!color"is"either"'green<"'2e++ow<"or"'red." 66"Ctate"Waria8+e:" 66"c.rrent-co+or":";L-co+or 66"to"-eep"trac-"of"the"c.rrent"co+or"of"the"traffic"+ight !define"c.rrent-co+or"'red# 66"7ontract:"ne*t":""-/""0oid 66"3.rpose:"the"f.nction"a+wa2s"prod.ces"!0oid# 66"5ffect:"to"change"c.rrent-co+or"from"'green"to"'2e++ow<" 66"'2e++ow"to"'red<"and"'red"to"'green 66"=eader:"omitted"for"this"partic.+ar"e*amp+e 66"5*amp+es:" 66"if"c.rrent-co+or"is"'green"and"we"e0a+.ate"!ne*t#<"then c.rrent-co+or"is"'2e++ow 66"if"c.rrent-co+or"is"'2e++ow"and"we"e0a+.ate"!ne*t#<"then c.rrent-co+or"is"'red 66"if"c.rrent-co+or"is"'red"and"we"e0a+.ate"!ne*t#<"then"c.rrentco+or"is"'green 66";emp+ate:"data-directed"on"state-0aria8+e"that"is"to"8e"m.tated 66"!define"!f# 66"""!cond 66"""""9!s2m8o+&A"'green"c.rrent-co+or#"!set!"c.rrent-co+or"...#: 66"""""9!s2m8o+&A"'2e++ow"c.rrent-co+or#"!set!"c.rrent-co+or"...#: 66"""""9!s2m8o+&A"'red"c.rrent-co+or#"!set!"c.rrent-co+or"...#:## 66"Definition: !define"!ne*t# ""!cond """"9!s2m8o+&A"'green"c.rrent-co+or#"!set!"c.rrent-co+or"'2e++ow#: """"9!s2m8o+&A"'2e++ow"c.rrent-co+or#"!set!"c.rrent-co+or"'red#: """"9!s2m8o+&A"'red"c.rrent-co+or#"!set!"c.rrent-co+or"'green#:## "" 66";ests: !begin"!set!"c.rrent-co+or"'green#"!ne*t#"!s2m8o+&A"c.rrent-co+or '2e++ow## !begin"!set!"c.rrent-co+or"'2e++ow#"!ne*t#"!s2m8o+&A"c.rrent-co+or 'red##

/begin /setD current2color =red0 /ne8t0 /s$mbolOH current2color =green00 Figure 1..' The design recipe )or state +ariables: A complete e8ample "et us now ta.e a loo. at the stages o) our most basic design recipe and how we can accommodate e))ects on state +ariables: Data +nal%sis' #+en )unctions that a))ect the state o) +ariables consume and /possibl$0 produce data, Thus we still need to anal$*e how to represent in)ormation and! i) necessar$! introduce structure and data de)initions,

For e8ample! the tra))ic2light e8ample bene)its )rom the data de)inition )or ;Lco+or /see abo+e0, Contract, Purpose, and Effect' The )irst maFor change concerns the second step, In addition to speci)$ing what a )unction consumes and produces! we must also write down which +ariables it a))ects and how it a))ects those state +ariables, The e))ect o) a )unction on state +ariables must be consistent with the purpose statement o) a +ariable, Consider the tra))ic2light e8ample again, It re?uires a )unction that switches the color o) the tra))ic light in accordance with the tra))ic laws, The )unction chec.s the +ariable c.rrent-co+or and a))ects its state, Here is how we should speci)$ this )unction:
66"ne*t":""-/""0oid 66"effect:"to"change"c.rrent-co+or"from"'green"to"'2e++ow<" 66"'2e++ow"to"'red<"and"'red"to"'green !define"!ne*t#"...#

The )unction consumes no data and alwa$s produces the in+isible +alueE in Scheme this +alue is called 0oid, Because the )unction has no purpose in the traditional sense! it is accompanied b$ an e))ect statement onl$, Here is the speci)ication )or add-to-address-8oo-:
66"add-to-address-8oo-":"s2m8o+"n.m8er""-/""0oid 66"effect:"to"add"!+ist"name"phone#"to"the"front"of"address8oo!define"!add-to-address-8oo-"name"phone#"...#

1e can tell )rom the e))ect statement that the de)inition o) address-8oo- is modi)ied in a )ashion thatCs coherent with its purpose statement and contract, Program E amples' #8amples are as important as e+er! but )ormulating them has become more di))icult, As be)ore! we must de+elop e8amples that illustrate the relationship between inputs and outputs! but! because )unctions now ha+e e))ects! we also need e8amples that illustrate those, "et us return to our )irst running e8ample! the ne*t )unction )or tra))ic lights, It a))ects one state2+ariable: c.rrent-co+or, Because this +ariable can stand )or one o) three s$mbols! we can actuall$ characteri*e all o) its possible e))ects with e8amples:
66"if"c.rrent-co+or"is"'green"and"we"e0a+.ate"!ne*t#<" 66"then"c.rrent-co+or"is"'2e++ow"afterwards 66"if"c.rrent-co+or"is"'2e++ow"and"we"e0a+.ate"!ne*t#<" 66"then"c.rrent-co+or"is"'red"afterwards 66"if"c.rrent-co+or"is"'red"and"we"e0a+.ate"!ne*t#<" 66"then"c.rrent-co+or"is"'green"afterwards

In contrast! the state +ariable address-8oo- can stand )or an in)inite number o) +alues! so it is impossible to ma.e up a comprehensi+e series o) e8amples, But it is still important to state a )ew! because e8amples ma.e it easier to de+elop the )unction bod$ later:
66"if"address-8oo-"is"empt2"and" 66"we"e0a+.ate"!add-to-address-8oo-"''dam"1#<" 66"then"address-8oo-"is"!+ist"!+ist"''dam"1##"afterwards." 66"if"address-8oo-"is"!+ist"!+ist"'50e"2##"and" 66"we"e0a+.ate"!add-to-address-8oo-"''dam"1#<" 66"then"address-8oo-"is"!+ist"!+ist"''dam"1#"!+ist"'50e"2## afterwards." 66"if"address-8oo-"is"!+ist"5-1"..."5-2#"and" 66"we"e0a+.ate"!add-to-address-8oo-"''dam"1#<" 66"then"address-8oo-"is"!+ist"!+ist"''dam"1#""5-1"..."5-2# afterwards."

-ot surprisingl$! the language o) e8amples in+ol+es words o) a temporal nature, A)ter all! assignments emphasi*e the notion o) time in programming, @arning: The state +ariable is ne+er a parameter o) a )unction, The Template' The template )or state2changing )unctions is li.e that o) an ordinar$ )unction! but the bod$ should also contain set! e8pressions to speci)$ the state +ariables that are to be modi)ied:
!define"!f.n-for-state-change"*"2"@# ""!set!"a-state-0aria8+e"...##

The computation o) the ne8t +alue )or a-state-0aria8+e can be le)t to an au8iliar$ )unction! which consumes *! 2! and @, @ur two e8amples )it this pattern, @n occasion! we should add selector and cond2e8pressions! based on the data de)initions )or the )unctionCs inputs, Consider ne*t again, The data de)inition )or its input suggests a cond2e8pression:
!define"!ne*t# ""!cond """"9!s2m8o+&A"'green"c.rrent-co+or#"!set!"c.rrentco+or"...#: """"9!s2m8o+&A"'2e++ow"c.rrent-co+or#"!set!"c.rrentco+or"...#: """"9!s2m8o+&A"'red"c.rrent-co+or#"!set!"c.rrentco+or"...#:##

In this simple case! we can indeed go with either alternati+e and design a proper program, The 5od%' As alwa$s! the de+elopment o) the )ull )unction re?uires a solid understanding o) the e8amples! o) how the$ are computed! and o) the template, For )unctions with e))ects! the completion o) the set! e8pression is the most demanding step, In

some cases! the right2hand side in+ol+es nothing but primiti+e operations! the )unctionCs parameters! and the state +ariable /or se+eral o) them0, In others! it is best to de+elop an au8iliar$ )unction /without e))ect0 that consumes the current +alue o) the state +ariable and the )unctionCs parameters and that produces the new +alue o) the state +ariable, The )unction add-to-address-8oo- is an e8ample o) the )irst .ind, The right2 hand side o) the setD2e8pression consists o) address-8oo-! cons! +ist! and nothing else, The tra))ic2light e8ample! in contrast! is an e8ample )or both choices, Here is a de)inition that is based on the template:
!define"!ne*t# ""!cond """"9!s2m8o+&A"'green"c.rrent-co+or#"!set!"c.rrent-co+or '2e++ow#: """"9!s2m8o+&A"'2e++ow"c.rrent-co+or#"!set!"c.rrent-co+or 'red#: """"9!s2m8o+&A"'red"c.rrent-co+or#"!set!"c.rrent-co+or 'green#:##

1riting one based on an au8iliar$ )unction is also straight)orward:


!define"!ne*t# ""!set!"c.rrent-co+or"!ne*t-co+or"c.rrent-co+or###

For the de)inition o) ne*t-co+or! see page 67, Testing' In the past! we ha+e tested )unctions b$ translating the e8amples into boolean2 +alued e8pressions and b$ adding them to the bottom o) the Definitions window, For )unctions with e))ects! we use a similar approach! but to +eri)$ that )unctions ha+e the desired e))ect on state +ariables is a comple8 tas., There are two wa$s to test )unctions with e))ects, First! we can set the state +ariable into a desired state! appl$ the )unction! and then chec. whether the )unction has the desired result and e))ect, The ne*t )unction is a particularl$ good one )or this approach, 1e characteri*ed its complete beha+ior with three e8amples, All three can be translated into begin2e8pressions that test as suggested, Here is one e8ample:
!begin"!set!"c.rrent-co+or"'green# """""""!ne*t# """""""!s2m8o+&A"c.rrent-co+or"'2e++ow##

#ach line sets the state +ariable c.rrent-co+or to the desired color! e+aluates !ne*t#! and then chec.s whether the e))ect is appropriate, 1e can also do this )or the add-to-address-8oo- )unction! though the tests are less comprehensi+e than those )or ne*t:
!begin"!set!"address-8oo-"empt2#

"""""""!add-to-address-8oo-"''dam"1# """""""!e).a+A"'!!'dam"1##"address-8oo-##

In this test! we chec. onl$ that 'dam and 1 are properl$ added to the initiall$ empt2 list, Second! we can capture the +alue o) a state +ariable be)ore it is tested! appl$ the memor$2changing )unction! and then conduct appropriate tests, Consider the )ollowing e8pression:
!local"!9define"c.rrent-0a+.e-of"address-8oo-:# ""!begin """"!add-to-address-8oo-"''dam"1# """"!e).a+A"!cons"!+ist"''dam"1#"c.rrent-0a+.e-of#"address8oo-###

It de)ines c.rrent-0a+.e-of to be the +alue o) address-8oo- at the beginning o) the e+aluation! and at the end chec.s that the appropriate entr$ was added at the )ront and that nothing changed )or the rest o) the +alue, To conduct tests )or )unctions with e))ects! especiall$ tests o) the second .ind! it is use)ul to abstract the test e8pression into a )unction:
66"test-for-address-8oo-":"s2m8o+"n.m8er""-/""8oo+ean 66"to"determine"whether"add-to-address-8oo-"has"the appropriate 66"effect"on"address-8oo-"and"no"more"than"that 66"effect:"same"as"!add-to-address-8oo-"name"n.m8er# !define"!test-for-address-8oo-"name"n.m8er# ""!local"!9define"c.rrent-0a+.e-of"address-8oo-:# """"!begin """"""!add-to-address-8oo-"name"n.m8er# """"""!e).a+A"!cons"!+ist"name"n.m8er#"c.rrent-0a+.e-of#" """"""""""""""address-8oo-####

Asing this )unction! we can now easil$ test add-to-address-8oo- se+eral times and ensure )or each test that its e))ects are appropriate:
!and"!test-for-address-8oo-"''dam"1# """""!test-for-address-8oo-"'50e"2# """""!test-for-address-8oo-"'7hris" 1453$4##

The and2e8pression guarantees that the test e8pressions are e+aluated in order and that all o) them produce tr.e, Future 0euse' @nce we ha+e a complete! tested program! we should remember its e8istence! -hat it computes! and what its effects are, 1e do not! howe+er! need to remember ho- it computes, I) we encounter a situation that calls )or the same computation and the same e))ects! we can reuse the program as i) it were a primiti+e operation, @arning: In the presence o) e))ects! it is much more di))icult to reuse a )unction than in the world o) algebraic programs,

Figures ('' and ('( summari*e our two running e8amplesE the header in the )irst one is omitted because it is useless )or the purpose and e))ect statements in this particular case,
66"Data"Def.:"+ists"of"ar8itrar2"+ength:"!listof"R#<"+ists"of"two items:"!+ist"I"]# 66"Ctate"Waria8+e:" 66"address-8oo-":"!listof"!+ist"s2m8o+"n.m8er## 66"to"-eep"trac-"of"pairs"of"names"and"phone"n.m8ers !define"address-8oo-"empt2# 66"7ontract:"add-to-address-8oo-":"s2m8o+"n.m8er""-/""0oid 66"3.rpose:"the"f.nction"a+wa2s"prod.ces"!0oid# 66"5ffect:"to"add"!+ist"name"phone#"to"the"front"of"address-8oo66"=eader:" 66"!define"!add-to-address-8oo-"name"phone#"...# 66"5*amp+es:" 66"if"address-8oo-"is"empt2"and"we"e0a+.ate 66"!add-to-address-8oo-"''dam"1#<"address-8oo-"is"!+ist"!+ist ''dam"1##. 66"if"address-8oo-"is"!+ist"!+ist"'50e"2##"and"we"e0a+.ate 66"!add-to-address-8oo-"''dam"1#<"address-8oo-"is"!+ist"!+ist ''dam"1#"!+ist"'50e"2##. 66"if"address-8oo-"is"!+ist"5-1"..."5-2#"and"we"e0a+.ate 66"!add-to-address-8oo-"''dam"1#<"address-8oo-"is"!+ist"!+ist ''dam"1#""5-1"..."5-2#. 66";emp+ate:"omitted 66"Definition: !define"!add-to-address-8oo-"name"phone# ""!set!"address-8oo-"!cons"!+ist"name"phone#"address-8oo-### "" 66";ests: !begin"!set!"address-8oo-"empt2# """""""!add-to-address-8oo-"''dam"1#

/e?ualH =//Adam (00 address2boo.00 Figure 1.1' The design recipe )or state +ariables: A second e8ample E ercise !&<#<1< Modi)$ the tra))ic light program in )igure ('' to draw the current state o) the tra))ic light onto a can+as, Start b$ adding the initiali*er, Ase the solutions )or section 9,&, Solution E ercise !&<#<2< Modi)$ the phone boo. program in )igure ('( so that it o))ers a graphical user inter)ace, Start b$ adding the initiali*er, Ase the solution o) e8ercise 57,6,&, Solution A de+ice should also go into the least harm)ul state when it detects an internal )ailure, An)ortunatel$! man$ so)tware engineers donCt )ollow this rule,
;'

Section !( E amples of /emor% 8sage


Designing programs with memor$ re?uires e8perience and practice! which! in turn! come )rom stud$ing e8amples, In this section we stud$ three more e8amples o) programs that use memor$, The )irst one illustrates the importance o) initiali*ersE the second one demonstrates how to design programs whose e))ects depend on conditionsE and the last one shows how e))ects can be use)ul in recursi+e )unctions, The last two subsections pro+ide opportunities )or practicing what weC+e learned,

(0#$ 3nitiali9ing State


Recall the color2guessing game )rom e8ercise 7,(,7, @ne pla$er pic.s two colors )or two s?uaresE we call those DDtargets,CC The other one tries to guess which color is assigned to which s?uareE the$ are guesses, The )irst pla$erCs response to a guess is to compare the colors and to produce one o) the )ollowing answers: (, 'perfectD! i) the )irst target is e?ual to the )irst guess and the second target is e?ual to the second guessE &, 'Nne7o+or't7orrect3osition! i) the )irst guess is e?ual to the )irst target or the second guess is e?ual to the second targetE 5, 'Nne7o+orNcc.rs! i) either o) the guesses is one o) the two targetsE 6, and 'Jothing7orrect! otherwise, These )our answers are the onl$ answers that the )irst pla$er gi+es, The second pla$er is to guess the two chosen target colors in as )ew guesses as possible, To simpli)$ the game! the choice o) colors is limited: see the top o) )igure ('&, @ur goal is to de+elop a program that pla$s the role o) the master pla$er, That is! we want a program that pic.s the colors and chec.s the guesses o) the second pla$er,

66"7onstants: 66"the"+egitimate"co+ors" !define"7NLNQC ""!+ist"'8+ac-"'white"'red"'8+.e"'green"'go+d"'pin-"'orange 'p.rp+e"'na02## 66"the"n.m8er"of"co+ors !define"7NL#"!+ength"7NLNQC##

EE A co!or is a s$mbol on C@"@RS, Figure 1.2' =uessing colors The game description suggests that the program must o))er two ser+ices: one )or setting up two target colors and another one )or chec.ing the guesses, -aturall$! each ser+ice corresponds to a )unction, "etCs call the )irst master and the second one master-chec-, Here is a possible dialogue! based on the two )unctions:
/"!master# /"!master-chec-"'red"'red# 'Jothing7orrect /"!master-chec-"'8+ac-"'pin-# 'Nne7o+orNcc.rs ..." /"!master# /"!master-chec-"'red"'red# 'perfectD

66"Data"Definition:

The master )unction consumes nothing and produces the in+isible +alueE its e))ect is to initiali*e the two targets, Depending on what the chosen colors are! chec.ing the same two guesses ma$ produce 'perfectD or 'Jothing7orrect, In other words! master sets up some memor$ that master-chec- uses, "et us now stud$ how the design recipe applies to the de+elopment o) the program, The )irst step is to de)ine the state +ariables and to speci)$ the purpose o) each +ariable, @ur anal$sis suggests that we need two state +ariables! one per target:
66"target1,"target2":"co+or 66"the"0aria8+es"represent"the"two"co+ors"that"the"first"p+a2er chooses !define"target1"!first"7NLNQC## !define"target2"!first"7NLNQC##

Both +ariables are set to the )irst item )rom 7NLNQC! so that the$ stand )or some color, The second step is to de+elop an initiali*er )or the two state +ariables, A single initiali*er is enough because the two +ariables go together, Indeed! the initiali*er is the desired master )unction:
66"master":""-/""0oid 66"effect:"set"target1"and"target2"to"random+2"chosen"items"in 7NLNQC

!define"!master# ""!begin """"!set!"target1"!+ist-ref"7NLNQC"!random"7NL#### """"!set!"target2"!+ist-ref"7NLNQC"!random"7NL######

The e))ect comment e8plains how master changes the two state +ariables b$ pic.ing an item )rom 7NLNQC based on a random number between ' and the length o) 7NLNQC, Finall$! we can turn to the )unctions that modi)$ and utili*e the programCs memor$, As it turns out! the memor$ isnCt modi)ied a)ter the two target +ariables are initiali*edE it is onl$ used to compare to the two guesses o) the pla$er, The onl$ other ser+ice we need is master-chec-, It uses chec--co+or! the solution o) e8ercise 7,(,7! to conduct the comparison, For a summar$! see )igure ('5! which contains the +ariable and )unction de)initions that we Fust discussed,
66"target1,"target2":"co+or" 66"the"two"0aria8+es"represent"the"two"co+ors"that"the"first p+a2er"chose !define"target1"!first"7NLNQC## !define"target2"!first"7NLNQC## 66"master":""-/""0oid 66"effect:"set"target1"and"target2"to"two"random+2"chosen"items from"7NLNQC !define"!master# ""!begin """"!set!"target1"!+ist-ref"7NLNQC"!random"7NL#### """"!set!"target2"!+ist-ref"7NLNQC"!random"7NL###### 66"master-chec-":"co+or"co+or""-/""s2m8o+ 66"to"determine"how"man2"co+ors"at"how"man2"positions"are"g.essed correct+2 66";he"f.nction"defers"to"chec--co+or<"the"so+.tion"of e*ercise"5.1.5. !define"!master-chec-"g.ess1"g.ess2#

/chec.2color guess( guess& target( target&00 Figure 1.!' =uessing colors /Part &0 E ercise !(<1<1< Draw a diagram that shows how master and master-chec- interact with memor$, Solution E ercise !(<1<2< Abstract the repeated e8pressions in master into the )unction random-pic-, It consumes a list and chooses a random item )rom that list, Then use the )unction to eliminate the repeated e8pressions in master, Solution E ercise !(<1<!< Modi)$ the color guessing program so that its )inal answer isnCt Fust 'perfectD but a list o) two items: the s$mbol perfectD and the number o) guesses that the second pla$er made, Start b$ modi)$ing the diagram o) e8ercise 5;,(,(, Solution

E ercise !(<1<#< Modi)$ the color guessing program so that it automaticall$ restarts the game when a pla$er has guessed the correct target colors, Solution E ercise !(<1<$< De+elop a graphical user inter)ace! similar to that o) the teachpac. master.ss, Instead o) colored buttons! use buttons labeled with the color, Show the current selection in message )ields, Solution

(0#" State Changes from <ser 3nteractions


Recall the hangman game )rom 9,;, The goal o) the game is to test a personCs acti+e +ocabular$, @ne pla$er thin.s o) a word and draws the noose o) a gallowsE the other pla$er tries to guess the word! one letter at a time, For e+er$ wrong guess! the )irst pla$er adds another part to the drawing /see )igure (70: )irst the head! then the bod$! the arms! and the legs, I)! howe+er! the pla$erCs guess re+eals new .nowledge about the chosen word! the )irst pla$er indicates where the the letter occurs in the word, The game is o+er when the second pla$er guesses the complete word or when the )irst pla$er has completed the stic. )igure,
66"Data"'na+2sis"and"Definitions: 66"'"letter"is"a"s2m8o+"in:"'a"..."'@"p+.s"'V 66"'"word"is"a"!+istof"+etter#. 66"'"*ody!part"is"one"of"the"fo++owing"s2m8o+s: !define"3'Q;C"'!head"8od2"right-arm"+eft-arm"right-+eg"+eft-+eg## 66"7onstants: 66"some"g.essing"words:" !define"ONQDC" ""'!!h"e"+"+"o# """"!w"o"r"+"d# """"!i"s# """"!a# """"!s"t"."p"i"d# """"!p"r"o"g"r"a"m# """"!a"n"d# """"!s"h"o"."+"d# """"!n"e"0"e"r# """"!8"e# """"!."s"e"d# """"!o"-"a"2# """"... """"## 66"the"n.m8er"of"words"we"can"choose"from"

/define 1@RDS[ /length 1@RDS00 Figure 1.#' Hangman Basics Figure ('6 contains the data de)initions )or letters! words! and bod$2parts, In particular! 3'Q;C not onl$ speci)ies the bod$ parts that are drawn! but also the order in which the$ are drawn, The )igure also de)ines an incomplete list o) words so that the hangman program can randoml$ pic. a word )or us to guess,

The random pic.ing o) words occurs at the beginning o) the game! which suggests a random initiali*ation )unction! similar to that o) the color2guessing program in the preceding section, In contrast to the latter! the hangman program must also remember the number o) guesses that a pla$er made! because there is onl$ a limited number o) them, A)ter '+eft-+eg is drawn! the game is o+er, Counting down the number o) bod$ parts also implies that as the program chec.s each guess! it must in)orm the pla$er not onl$ what the guess re+ealed but also which bod$ part! i) an$! was lost, "et us capture this thought in a data de)inition that speci)ies the legitimate class o) responses: A response is either (, 1Io."won1 &, !+ist"1;he"5nd1"word# 5, !+ist"1Good"g.essD1"word# 6, !+ist"1Corr21"8od2-part"word# Three o) the responses are lists so that the program can pro+ide se+eral pieces o) in)ormation at once, Speci)icall$! the )irst response sa$s that )illing in the guess turns the status word into the chosen word and that the pla$er sur+i+ed the game, The second response indicates the oppositeE the list o) a+ailable bod$ parts is e8hausted and the game is o+er because the pla$er did not guess all the letters in the word, In the third case! the pla$erCs guess was success)ul and the second item in the list shows how much the pla$er .nows about the word, Finall$! the )ourth response represents a bad guess! in which case the response is a list o) three items: a greeting! the lost bod$ part! and a reminder o) what the pla$er has )ound about the word, 1e can now imagine the role o) the two ser+ices in the hangman program, The )irst! called hangman! pic.s a new wordE the second! called hangman-g.ess! consumes a letter and produces one o) the )our possible responses, Here is a )easible dialogue:
/"!hangman# /"!hangman-g.ess"'a# !+ist"1Corr21"'head"!+ist"'V"'V"'V"'V"'V"'V## /"!hangman-g.ess"'i# !+ist"1Good"g.essD1"!+ist"'V"'V"'V"'V"'i"'V## /"!hangman-g.ess"'s# !+ist"1Good"g.essD1"!+ist"'s"'V"'V"'V"'i"'V## /"!hangman-g.ess"'i# !+ist"1Corr21"'8od2"!+ist"'s"'V"'V"'V"'i"'V##

... /"!hangman# /"!hangman-g.ess"'a# 1Io."won1

The dialogue consists o) two rounds o) hangman, The$ show that the results o) hangman-g.ess depend on the prior use o) hangman, Furthermore! the )irst round illustrates how hangman-g.ess applied to the same guess twice produces two di))erent answers, This again means that hangman-g.ess modi)ies and uses memor$! speci)icall$! it counts down the bod$ parts as the pla$er ma.es useless guesses,
66"chosen-word":"word 66"the"word"that"the"p+a2er"is"to"g.ess !define"chosen-word"!first"ONQDC## 66"stat.s-word":"word 66"represents"which"+etters"the"p+a2er"has"and"hasnKt"g.essed !define"stat.s-word"!first"ONQDC## 66"8od2-parts-+eft":"!listof"8od2-part# 66"represents"the"+ist"of"8od2"parts"that"are"sti++"1a0ai+a8+e1 !define"8od2-parts-+eft"3'Q;C# 66"hangman":""-/""0oid 66"effect:"initia+i@e"chosen-word<"stat.s-word<"and"8od2-parts+eft !define"!hangman# ""!begin """"!set!"chosen-word"!+ist-ref"ONQDC"!random"!+ength"ONQDC#### """"!set!"stat.s-word"...#

/setD bod$2parts2le)t PARTS000 Figure 1.$' Hangman Basics /Part &0 In addition! the dialogue shows that the pla$er loses a bod$ part whene+er a guess doesnCt contribute an$ new .nowledge, Consider the second guess: 'i, It occurs in the penultimate position o) the word and the response o) hangman-g.ess sa$s so, 1hen the pla$er enters 'i again as the )ourth guess! hangman-g.ess detects no progress because the positions o) 'i ha+e alread$ been re+ealed, In the in)ormal description o) the game! this aspect had been le)t open, B$ putting together an e8ample! we become aware o) this ambiguit$ and can ma.e a decision, Thus )ar! our reasoning has re+ealed the need )or two ser+ices and three state +ariables: (, &, 5,
chosen-word!

which is the word to be guessedE which records how much o) the word has been guessedE

stat.s-word!

and 8od2-parts-+eft! which remembers how man$ and which imaginar$ bod$ parts the pla$er can still lose,

The )irst two +ariables alwa$s stand )or words! as their name sa$s, A natural +alue )or the last one is a list o) bod$ partsE indeed! the list should alwa$s be a su))i8 o) 3'Q;C, Figure ('7 contains the de)initions o) the state +ariables and their purpose statements, The )irst two! chosen-word and stat.s-word! are set to the )irst items o) 1@RDS! so that the$ represent some word, The third one is set to 3'Q;C because this list represents the entire collection o) a+ailable bod$ parts, -e8t we must de+elop an initiali*er )or the state +ariables, As in the preceding section! a single initiali*er su))ices, It is the hangman )unction! and its purpose is to set up the programCs memor$, Speci)icall$! it pic.s a word )or chosen-word! and it sets stat.sword and 8od2-parts-+eft to +alues that re)lect that the game has Fust begun, The last one is eas$ because 3'Q;C is the appropriate list, The initial +alue )or stat.s-word re?uires a short anal$sis, First! the +alue must be a word, Second! it must consist o) as man$ letters as chosen-word, Finall$! each o) the letters is un.nown! because the pla$er hasnCt made an$ guesses $et, Thus! the matching action is to build a word as long as chosen-word )rom 'V, E ercise !(<2<1< De+elop the )unction ma-e-stat.s-word! which consumes a word and produces an e?uall$ long word consisting o) Fust 'V, Ase the )unction to complete the de)inition o) hangman in )igure ('7, Solution E ercise !(<2<2< Ase 8.i+d-+ist to create the status word in a single e8pression, Complete the de)inition o) hangman in )igure ('7, Solution -ow we are read$ to deal with the most di))icult part: the design o) hangman-g.ess! a )unction that uses and modi)ies the memor$, It consumes a letter and produces an answer! speci)icall$ a response! which depends on how the current +alue o) stat.sword! chosen-word! and g.ess compare, At the same time! the )unction must a))ect the state +ariable stat.s-word i) the pla$erCs guess added new .nowledge, I) not! the )unction must shorten 8od2-parts-+eft! the list o) a+ailable bod$ parts, The matching contract! purpose! and e))ect statements are as )ollows:
66"hangman-g.ess":"+etter""-/""response 66"to"determine"whether"the"p+a2er"has"won<"+ost<"or"ma2"contin.e to 66"p+a2"and<"if"no"progress"was"made<"which"8od2"part"was"+ost 66"effect: 66"!1#"if"the"g.ess"represents"progress<".pdate"stat.s-word 66"!2#"if"not<"shorten"the"8od2-parts-+eft"82"one"

1e ha+e alread$ considered a sample dialogue that illustrates the wor.ings o) hangmang.ess, B$ dissecting this dialogue! we can de+elop speci)ic e8amples )or hangmang.ess,

The sample dialogue and the purposeKe))ect statements impl$ that the result o) hangman-g.ess depends on whether or not the guess constitutes progress and! i) not! whether or not the guess was the last one, "etCs use these distinctions )or the de+elopment o) e8amples: (, I) stat.s-word is !+ist"'8"'V"'V"'V# and chosen-word is !+ist"'8"'a"'+ '+#! then e+aluating
2. "!hangman-g.ess"'+#

produces !+ist"1Good"g.essD1"!+ist"'8"'V"'+"'+## and stat.s-word becomes !+ist"'8"'V"'+"'+#, 5, I) stat.s-word is !+ist"'8"'V"'+"'+# and chosen-word is !+ist"'8"'a"'+ '+#! then e+aluating
4. "!hangman-g.ess"'a#

produces 1Io."won1, The e+aluation has no e))ect in this case, 7, I) stat.s-word is !+ist"'8"'V"'+"'+#! chosen-word is !+ist"'8"'a"'+ '+#! and 8od2-parts-+eft is !+ist"'right-+eg"'+eft-+eg#! then e+aluating
. "!hangman-g.ess"'+#

produces !+ist"1Corr21"'right-+eg"!+ist"'8"'V"'+"'+## and 8od2parts-+eft becomes !+ist"'+eft-+eg#, ;, Finall$! i) stat.s-word is !+ist"'8"'V"'+"'+#! chosen-word is !+ist"'8 'a"'+"'+#! and 8od2-parts-+eft is !+ist"'+eft-+eg#! then e+aluating
$. "!hangman-g.ess"'+#

produces !+ist"1;he"5nd1"!+ist"'8"'a"'+"'+## and 8od2-parts-+eft becomes empt2, The )irst two e8amples illustrate what happens when the pla$er enters a guess that re+eals new in)ormationE the last two )ocus on those cases where the guess contributes nothing, The case split naturall$ suggests a basic template based on a distinction between the possible situations:
!define"!hangman-g.ess"g.ess#

""!cond """"9..."66"g.ess"did"re0ea+"new"information:" """"""!cond 9..."66"g.ess"comp+eted"the"search"for"the"word "...: 9..."66"g.ess"did"not"comp+ete"the"search"for"the"word """"""""""!begin" """"""""""""!set!"stat.s-word"...# """"...#:#: """"9..."66"g.ess"did"not"re0ea+"an2"new"information:" """""!begin" """""""!set!"8od2-parts-+eft"...# """""""..."#:##

The location o) the setD2e8pressions in the templateCs nested conds speci)$ e8actl$ under which conditions e))ects happen, First! the outermost conditional distinguishes whether or not g.ess produces new .nowledge about the hidden wordE i) it doesnCt! the )unction must modi)$ 8od2-parts-+eft, Second! i) g.ess re+eals new .nowledge! the )unction updates the stat.s-word +ariable unless the pla$er has Fust )inished the entire word, Because we ha+enCt considered $et how to e8press these tests! we use comments to indicate what the conditions are, "et us turn to this problem )irst! so that we can start the )unction2de)inition step with a )ull2)ledged template, The )irst missing condition concerns the ?uestion whether g.ess re+eals new in)ormation, To this end! we must compare g.ess with the letters in chosen-word, This comparison should produce the new status word, Here is the speci)ication )or the au8iliar$ )unction that conducts this computation:
66"re0ea+-+ist":"word"word"+etter""-/""word 66"to"comp.te"the"new"stat.s"word"from"chosen-word< 66"stat.s-word<"and"g.ess !define"!re0ea+-+ist"chosen-word"stat.s-word"g.ess#"...#

Fortunatel$! we ha+e discussed this au8iliar$ )unction twice be)ore /see sections 9,; and e8ercise (;,9,&0 and .now how to de)ine itE )igure ('9 contains a suitable de)inition, Asing re0ea+-+ist! we can now )ormulate a condition that determines whether g.ess re+eals new .nowledge:
!e).a+A"stat.s-word"!re0ea+-+ist"stat.s-word"chosen-word"g.ess##

The condition uses e).a+A to compare the current +alue o) stat.s-word with its new +alue! as computed b$ re0ea+-+ist, I) the two lists are e?ual! g.ess doesnCt produce new .nowledgeE otherwise it does, The second missing condition concerns the ?uestion whether the gi+en g.ess completes the search )or the word, I) g.ess is e?ual to all missing letters in stat.s-word! then the pla$er has )ound the complete word, Here is the corresponding condition:
!e).a+A"chosen-word"!re0ea+-+ist"stat.s-word"chosen-word"g.ess##

That is! the game is o+er i) chosen-word is e?ual to the result o) re0ea+-+ist,

"etCs put e+er$thing together in a single template:


!define"!hangman-g.ess"g.ess# ""!local"!!define"new-stat.s"!re0ea+-+ist"stat.s-word"chosen-word g.ess### """"!cond """"""9!e).a+A"new-stat.s"stat.s-word# """""""!begin" "!set!"8od2-parts-+eft"...# "..."#: """"""9else """""""!cond "9!e).a+A"new-stat.s"chosen-word# ""...: "9else" ""!begin" """"!set!"stat.s-word"...# """"...#:#:###

The template uses a local2e8pression because the result o) re0ea+-+ist is used twice, Also! the two outer cond2clauses are swapped because it is more natural to write !e).a+A"new-stat.s"stat.s-word# than its negation, 1e can now turn to the )unction2design step, Because the template is conditional! we de+elop each clause separatel$: (, Assume that !e).a+A"new-stat.s"stat.s-word# e+aluates to tr.e! that is! the pla$er made no progress, This implies that the pla$er loses an imaginar$ bod$ part, To capture this e))ect! the setD2e8pression must change the +alue o) 8od2-parts-+eft, Speci)icall$! it must set the state +ariable to the rest o) its current +alue:
2. !set!"8od2-parts-+eft"!rest"8od2-parts-+eft##

The answer depends on the new +alue o) 8od2-parts-+eft, I) it is empt2! the game is o+erE the appropriate response is !+ist"1;he"5nd1"chosen-word# so that the pla$er )inds out what the chosen word was, I) 8od2-parts-+eft is not empt$! the response is !+ist"1Corr21"AAA"stat.s-word#, The response sa$s that g.ess is useless, Its last part is the current +alue o) stat.s-word so that the pla$er sees what he has disco+ered, The AAA indicates a problem, To understand the problem! ta.e a loo. at what we ha+e:
!begin" ""!set!"8od2-parts-+eft"!rest"8od2-parts-+eft## ""!cond """"9!empt2A"8od2-parts-+eft#"!+ist"1;he"5nd1"chosen-word#: """"9else"!+ist"1Corr21"AAA"stat.s-word#:##

In principle! the ?uestion mar.s should be the bod$ part that the pla$er Fust lost to the gallows, But! because set! modi)ies 8od2-parts-+eft! we can no longer Fust sa$ !first"8od2-parts-+eft#, As mentioned in section 57,&! when programming with set! timing matters, 1e can sol+e the problem with a local2

e8pression that names the )irst item on 8od2-parts-+eft be)ore the state +ariable is modi)ied, 5, The second case is much simpler than the )irst, 1e distinguish two subcases: a, I) new-stat.s is e?ual to chosen-word! the pla$er has won, The response is 1Io."won1E there is no e))ect, b, I) the two are not e?ual! the pla$er made some progress and must be told, Furthermore! the )unction must .eep trac. o) the progressE a !set! stat.s-word"new-stat.s# accomplishes this e))ect, The response consists o) an encouragement and the new status, Figure ('9 contains the complete de)inition o) hangman-g.ess,
66"hangman-g.ess":"+etter""-/""response 66"to"determine"whether"the"p+a2er"has"won<"+ost<"or"ma2"contin.e to"p+a2 66"and<"if"so<"which"8od2"part"was"+ost<"if"no"progress"was"made 66"effects:"!1#"if"the"g.ess"represents"progress<".pdate"stat.sword 66"!2#"if"not<"shorten"the"8od2-parts-+eft"82"one" !define"!hangman-g.ess"g.ess# ""!local"!!define"new-stat.s"!re0ea+-+ist"chosen-word"stat.s-word g.ess### """"!cond """"""9!e).a+A"new-stat.s"stat.s-word# """""""!local"!!define"ne*t-part"!first"8od2-parts-+eft### """""""""!begin" """""""""""!set!"8od2-parts-+eft"!rest"8od2-parts-+eft## """""""""""!cond """""""""""""9!empt2A"8od2-parts-+eft#"!+ist"1;he"5nd1"chosenword#: """""""""""""9else"!+ist"1Corr21"ne*t-part"stat.s-word#:###: """"""9else """""""!cond """""""""9!e).a+A"new-stat.s"chosen-word#"1Io."won1: """""""""9else" """"""""""!begin" """"""""""""!set!"stat.s-word"new-stat.s# """"""""""""!+ist"1Good"g.essD1"stat.s-word##:#:### 66"re0ea+-+ist":"word"word"+etter""-/""word 66"to"comp.te"the"new"stat.s"word !define"!re0ea+-+ist"chosen-word"stat.s-word"g.ess# ""!local"!!define"!re0ea+-one"chosen-+etter"stat.s-+etter# """"!cond """"""9!s2m8o+&A"chosen-+etter"g.ess#"g.ess: """"""9else"stat.s-+etter:###

/map re+eal2one chosen2word status2word000 Figure 1.&' Hangman Basics /Part 50

E ercise !(<2<!< Draw a diagram that shows how hangman and hangman-g.ess interact with the state +ariables, Solution E ercise !(<2<#< Formulate the )our e8amples )or hangman-g.ess as boolean2+alued e8pressions that produce tr.e i) hangman-g.ess is correct, De+elop an additional e8ample )or each caseE turn these new e8amples into additional tests, Solution E ercise !(<2<$< De+elop a graphical user inter)ace! similar to that o) the teachpac. hangman.ss, Connect the )unctions in this section as call2bac.s, Solution E ercise !(<2<&< Modi)$ the program so that it .eeps trac. o) all the guesses, Then! i) a pla$er enters the same guess twice )or the same round o) a hangman game! the response o) hangman-g.ess is 1Io."ha0e".sed"this"g.ess"8efore.1 Solution E ercise !(<2<(< Consider the )ollowing +ariant o) re0ea+-+istD:
66"re0ea+-+istD":"+etter""-/""0oid 66"effect:"to"modif2"stat.s-word"8ased"on"a"comparison"of"chosenword< 66"the"stat.s-word<"and"the"p+a2erKs"g.ess !define"!re0ea+-+istD"cw"sw"g.ess# ""!local"!!define"!re0ea+-one"chosen-+etter"stat.s-+etter# """"!cond """"""9!s2m8o+&A"chosen-+etter"g.ess#"g.ess: """"""9else"stat.s-+etter:### """"!set!"stat.s-word"!map"re0ea+-one"cw"sw####

It changes the state +ariable stat.s-word to a +alue that is computed )rom the old +alue o) stat.s-word! chosen-word! and the guess, Modi)$ hangman-g.ess so that it wor.s properl$ with the re0ea+-+istD )unction, Solution

(0#( State Changes from Recursion


Functions that a))ect the memor$ o) a program ma$ not onl$ process simple )orms o) data but also arbitraril$ large pieces o) data, To understand how this wor.s! let us ta.e a closer loo. at the purpose o) re0ea+-+ist )rom the hangman game program, As we ha+e Fust seen! the )unction compares g.ess with each letter in chosen-word, I) it is the same! g.ess ma$ unco+er new .nowledge and is included at the appropriate position in the wordE otherwise! the corresponding letter )rom stat.s-word represents what the pla$er .nows,

The hangman-g.ess )unction then compares the result o) re0ea+-+ist with the old +alue o) stat.s-word to )ind out whether the pla$er unco+ered new .nowledge, Furthermore! the result is compared with chosen-word again i) the pla$er )ound new .nowledge! because g.ess might ha+e matched all remaining un.nown letters, Clearl$! both o) these comparisons repeat the computations o) re0ea+-one, The problem is that the result o) re0ea+-one is use)ul to re0ea+-+ist and that the result o) its indi+idual comparisons are use)ul in the conditionals o) hangman-g.ess, 1e can sol+e the )irst part o) the problem with the use o) an additional piece o) memor$: a state +ariable that records whether re0ea+-one unco+ers a letter, The state +ariable! letCs call it new--now+edge! is modi)ied b$ re0ea+-one i) it determines that g.ess unco+ers a currentl$ hidden letter in chosen-word, The hangman-g.ess )unction can use new--now+edge to )ind out what re0ea+-one disco+ered, "et us now translate our idea into new program de)initions s$stematicall$, First! we need to speci)$ the state +ariable and its meaning:
66"new--now+edge":"8oo+ean 66"the"0aria8+e"represents"whether"the"most"recent"app+ication"of 66"re0ea+-+ist"has"pro0ided"the"p+a2er"with"new"-now+edge !define"new--now+edge"fa+se#

Second! we must consider what it means to initiali*e the new state +ariable, From what we .now! the state +ariable is used e+er$ time re0ea+-+ist is applied to g.ess, 1hen the application starts! the state +ariable should be fa+seE it should change to tr.e i) g.ess is use)ul, This suggests that new--now+edge is to be initiali*ed to fa+se e+er$ time re0ea+-+ist is applied, 1e can achie+e this reinitiali*ation b$ changing re0ea++ist so that it sets the state +ariable be)ore it computes an$thing else:
66"re0ea+-+ist":"word"word"+etter""-/""word 66"to"comp.te"the"new"stat.s"word 66"effect:"to"set"new--now+edge"to"fa+se"first !define"!re0ea+-+ist"chosen-word"stat.s-word"g.ess# ""!local"!!define"!re0ea+-one"chosen-+etter"stat.s-+etter#"...## """"!begin """"""! """ set!""" " new--now+edge""" " fa+se# " "" """"""!map"re0ea+-one"chosen-word"stat.s-word####

The underlined e8pression is the essential modi)ication, The local e8pression de)ines the au8iliar$ )unction re0ea+-one and then e+aluates the localCs bod$, The )irst step o) the bod$ is to initiali*e new--now+edge, Third! we must de+elop the program that modi)ies new--now+edge, Here the program alread$ e8ists: re0ea+-+ist! so our tas. is to modi)$ it in such a wa$ that it changes the state +ariable appropriatel$, "etCs describe the idea with a modi)ied e))ect statement:
66"re0ea+-+ist":"word"word"+etter""-/""word 66"to"comp.te"the"new"stat.s"word 66"effect:" 66"!1#"to"set"new--now+edge"to"fa+se"first 66"!2#"to"set"new--now+edge"to"tr.e"if"g.ess"re0ea+s"new"-now+edge

The )irst part o) the e))ect is necessar$ )or the second oneE an e8perienced programmer ma$ drop it, -e8t we should modi)$ the e8amples )or the )unction to illustrate what .ind o) e))ects happen, The purpose o) the )unction is to compute the new status word b$ chec.ing whether g.ess occurs in the chosen-word, There are two basic situations depending on whether g.ess re+eals new .nowledge or not: (, I) stat.s-word is !+ist"'8"'V"'+"'+# and chosen-word is !+ist"'8"'a"'+ '+#! then e+aluating
2. !re0ea+-one"chosen-word"stat.s-word"'a#

produces !+ist"'8"'a"'+"'+# and new--now+edge is tr.e, 5, I) stat.s-word is !+ist"'8"'V"'V"'V# and chosen-word is !+ist"'8"'a"'+ '+#! then e+aluating
4. !re0ea+-one"chosen-word"stat.s-word"'*#

produces !+ist"'8"'V"'V"'V# and new--now+edge is fa+se, 7, I) stat.s-word is !+ist"'8"'V"'V"'V# and chosen-word is !+ist"'8"'a"'+ '+#! then e+aluating
. !re0ea+-one"chosen-word"stat.s-word"'+#

produces !+ist"'8"'V"'+"'+# and new--now+edge is tr.e, ;, Finall$! i) stat.s-word is !+ist"'8"'V"'+"'+# and chosen-word is !+ist '8"'a"'+"'+#! then e+aluating
$. !re0ea+-one"chosen-word"stat.s-word"'+#

produces !+ist"'8"'V"'+"'+# and new--now+edge is fa+se, The )irst two e8amples co+er the basic situationsE the third one shows that i) g.ess re+eals se+eral new positions in the word! new--now+edge also becomes tr.eE and the last shows how guessing a letter that has been unco+ered be)ore means no new .nowledge has been added,

66"re0ea+-+ist":"word"word"+etter""-/""word 66"to"comp.te"the"new"stat.s"word 66"effect:"to"set"new--now+edge"to"tr.e"if"g.ess"re0ea+s"new -now+edge !define"!re0ea+-+ist"chosen-word"stat.s-word"g.ess# ""!local"!!define"!re0ea+-one"chosen-+etter"stat.s-+etter# """"!cond """"""9!and"!s2m8o+&A"chosen-+etter"g.ess# """"! """ " s2m8o+&A""" " stat.s-+etter"" '" V" #" # """""""!begin "! """ " set!""" " new--now+edge""" " tr.e" #" "g.ess#: """"""9else"stat.s-+etter:### """"!begin """"""!set!"new--now+edge"fa+se#

/map re+eal2one chosen2word status2word0000 Figure 1.(' The revea!-!ist )unction =i+en that we alread$ ha+e a )unction! we can s.ip the template step and instead )ocus on the ?uestion o) what we need to change in the e8isting )unction, The gi+en +ersion o) re0ea+-+ist maps re0ea+-one o+er the two words! which are lists o) letters, It is re0ea+-one that compares g.ess with the letters in chosen-word and that determines whether the pla$er has unco+ered new .nowledge, Hence we must modi)$ the au8iliar$ )unction so that it recogni*es when g.ess represents new .nowledge and to set new-now+edge to true in that case, As it is currentl$ de)ined! re0ea+-one merel$ compares g.ess with the letters in chosen-word, It does not chec. whether the pla$er disco+ers trul$ new .nowledge i) g.ess and chosen-+etter are the same, The letter g.ess! howe+er! represents new .nowledge onl$ i) the matching letter in the status word is still 'V, This suggests the two modi)ications shown in )igure (';, That is! re0ea+-one changes the +alue o) new-now+edge i)! and onl$ i)! both !s2m8o+&A"chosen-+etter"g.ess# and !s2m8o+&A stat.s-+etter"'V# are true, In summar$! we can use state +ariables i) we wish to communicate se+eral results )rom one computation to distant places, For such cases! the inter)ace o) a )unction is under our control but we choose to design it such that the )unction has both a result and an e))ect, The proper wa$ to achie+e these combinations is to de+elop the computations separatel$ and to merge them later! i) necessar$, E ercise !(<!<1< Draw a diagram that shows how hangman! hangman-g.ess! and re0ea+-+ist interact with the state +ariables, Solution E ercise !(<!<2< Turn the three e8amples into tests! that is! boolean2+alued e8pressions! and test the new +ersion o) re0ea+-+ist, How man$ times does re0ea+one modi)$ new--now+edge )or the third test caseH Solution

E ercise !(<!<!< Modi)$ hangman-g.ess in the hangman program to ta.e ad+antage o) the additional in)ormation that re0ea+-+ist pro+ides through new--now+edge, Solution E ercise !(<!<#< Modi)$ the hangman program a second time to eliminate the second e).a+A in hangman-g.ess, >int' Introduce a state +ariable that counts how man$ letters the pla$er doesnCt .now $et, Solution "et us stud$ a second e8ample o) a )unction that consumes an arbitraril$ large piece o) data and modi)ies the programCs memor$, The e8ample is a natural e8tension o) the tra))ic light simulator in section 59, 1e de+eloped two )unctions:
66"init-traffic-+ight":""-/""0oid" 66"effects:"!1#"to"initia+i@e"c.rrent-co+or6"!2#"to"draw"traffic +ight

and
66"ne*t":""-/""0oid 66"effects:"!1#"to"change"c.rrent-co+or"from"'green"to"'2e++ow<" 66"'2e++ow"to"'red<"and"'red"to"'green 66"!2#"to"redraw"the"traffic"+ight"appropriate+2"

The )irst one starts the processE with the second one! we can repeatedl$ switch the state o) the light b$ e+aluating !ne*t# in the Interactions window, T$ping in !ne*t# o+er and o+er again is tiring! so it is natural to wonder how to write a program that switches the state o) the tra))ic light ('' or (''' or ('''' times, In other words! we should de+elop a program 22 letCs call it switch 22 that consumes a natural number and that switches the light )rom one color to another that man$ times, The )unction consumes a natural number and produces !0oid#! a)ter it succeeds in switching the tra))ic light a su))icient number o) times, B$ now we can immediatel$ write down all the basics! including the template! )or a )unction that consumes a natural number:
66"switch":"N""-/""0oid 66"p.rpose:"it"comp.tes"nothing"of"interest 66"effect:"switch"the"traffic"+ight"n"times<" 66"ho+ding"each"co+or"for"three"seconds !define"!switch"n# ""!cond """"9!@eroA"n#"...: """"9else"..."!switch"!-"n"1##"...:##

The template is that o) a con+entional! structurall$ recursi+e )unction,

Ma.ing up an e8ample is also straight)orward, I) we e+aluate !switch"4#! we wish to see a change )rom 'red to '2e++ow! 'green! and 'red again! with each stage +isible )or three seconds, De)ining the )ull )unction based on the template is straight)orward, 1e proceed b$ cases, I) n is %! the answer is !0oid#, @therwise! we .now that
!switch"!-"n"1##

simulates all the necessar$ switching actions but one, To accomplish this one additional switch! the )unction must use !ne*t# to per)orm all the state changes and the change o) can+as and must wait three seconds, I) we put e+er$thing together in a begin2 e8pression! things happen in the right order:
!begin"!s+eep-for-a-whi+e"3# """""""!ne*t# """""""!switch"!-"n"1###

The top o) )igure ('< is the complete de)inition )or switch,


66"switch":"N""-/""0oid 66"effect:"switch"the"traffic"+ight"n"times<"ho+ding"each"co+or for"3"seconds 66"str.ct.ra+"rec.rsion" !define"!switch"n# ""!cond """"9!&"n"%#"!0oid#: """"9else"!begin"!s+eep-for-a-whi+e"3# """""""""""""""""!ne*t# """""""""""""""""!switch"!-"n"1###:## 66"switch-fore0er":""-/""0oid 66"effect:"switch"the"traffic"+ight"fore0er<"ho+ding"each"co+or for"3"seconds 66"generati0e"rec.rsion" !define"!switch-fore0er# ""!begin"!s+eep-for-a-whi+e"3# """""""""!ne*t#

/switch2)ore+er000 Figure 1.)' Two wa$s o) switching tra))ic lights

An alternati+e is to switch the tra))ic light )ore+er or at least until it brea.s because o) some e8ternal e+ent, In this case! the simulator does not consume an$ argument and! when applied! runs )ore+er, This is the simplest )orm o) generati+e recursion we can possibl$ encounter:
66"switch-fore0er":""-/""0oid 66"effect:"switch"the"traffic"+ight"fore0er<" 66"ho+ding"each"co+or"for"3"seconds !define"!switch-fore0er#" ""... ""!switch-fore0er##

Because the program does not terminate under an$ conditions! the template contains onl$ one recursi+e call, This su))ices to construct an eternall$ looping )unction,

Asing this template! we can de)ine the complete )unction as be)ore, Be)ore recurring! the )unction must sleep and switch the light with ne*t, 1e can accomplish this with a begin2e8pression! as shown in the bottom de)inition o) )igure ('<, In summar$! when we must de+elop recursi+e )unctions that modi)$ the programCs memor$! we choose the design recipe that best matches our situation and proceed accordingl$, In particular! i) the )unction has both an interesting purpose and an e))ect! as )or e8ample re0ea+-+ist! we should )irst de+elop the pure )unction and then add the e))ects later, E ercise !(<!<$< In section 5',&! we discussed how to search )or routes in simple graphs, The Scheme representation o) a simple graph is a list o) pairs /o) s$mbols0, The pairs speci)$ the direct connections between the nodes in the graph, #ach node is the beginning o) e8actl$ one connection! but ma$ be the end o) se+eral such connections or none, =i+en two nodes in a simple graph! the problem is to )ind out whether one can go )rom the )irst to the second, Recall our )irst attempt at a )unction that determines whether the route e8ists /see also )igure <90:
66"ro.te-e*istsA":"node"node"simp+e-graph""-/""8oo+ean 66"to"determine"whether"there"is"a"ro.te"from"orig"to"dest"in"sg 66"generati0e"rec.rsion" !define"!ro.te-e*istsA"orig"dest"sg# ""!cond """"9!s2m8o+&A"orig"dest#"tr.e: """"9else"!ro.te-e*istsA"!neigh8or"orig"sg#"dest"sg#:##

The )unction chec.s whether the origination and destination nodes are the same, I) not! it generates a new problem b$ loo.ing up the neighbor o) the origination node in the graph, @n occasion! ro.te-e*istsA )ails to produce an answer i) the graph contains a c$cle, In section 5',& we sol+ed the problem with an accumulator, It is also possible to sol+e it with a state +ariable that .eeps trac. o) the origination nodes that ro.te-e*istsA has +isited )or one particular attempt, Modi)$ the )unction appropriatel$, Solution E ercise !(<!<&< In section (9,&! we de+eloped se+eral simple models o) a computerCs )ile s$stem, De+elop the )unction dir-+isting! which consumes a director$ and produces a list o) all )ile names in the director$ and all o) its subdirectories, The )unction also sets the state +ariable how-man2-directories to the number o) subdirectories it encounters during the process, Solution

(0#) +inger E,ercises on State Changes


E ercise !(<#<1< Modi)$ chec--g.ess-for-+ist )rom e8ercise >,7,7 so that it also counts how man$ times the pla$er has clic.ed on the DDChec.CC button o) the inter)ace, >int' The call2bac. )unction )or the button uses chec--g.ess-for-+ist once per clic., Solution E ercise !(<#<2< De+elop a program that manages a tas. ?ueue, The program should support at least )our ser+ices: (, enter! which adds a tas. to end o) the ?ueueE &, ne*t! which determines the ne8t tas. in the ?ueue! i) an$E 5, remo0e! which remo+es the )irst tas. )rom the ?ueue! i) an$E 6, and co.nt! which computes the number o) items in the ?ueue, A user should start the tas. manager with start-tas--manager, A)ter the program is de+eloped and tested! use gui.ss to de+elop a graphical user inter)ace to the tas. manager, The inter)ace should start up with a )riendl$ message and should alwa$s displa$ the )irst tas. in the ?ueue and the number o) items in the ?ueue:

Anless the ?ueue is empt$! clic.ing the DD-e8tCC button should remo+e an item )rom the ?ueue and displa$ the )irst item in the remainder o) the ?ueue, I) the ?ueue is empt$! clic.ing the DD-e8tCC button should ha+e no e))ect,

>int' The greeting and the $ear are two separate message items,

Solution

E ercise !(<#<!< In section (',5! we de+eloped a program that mo+es pictures across a can+as, A picture is a list o) shapesE the program consists o) )unctions that draws! erases! and translates pictures, The main )unction is mo0e /e8ercise (',5,90, It consumes

a picture and a number n, It produces a new picture! mo+ed b$ n pi8elsE it also erases the original picture and draws the new one, De+elop the program dri0e, It draws a /)i8ed0 picture on a can+as and permits pla$ers to mo+e the picture le)t or right b$ a pla$er2speci)ied number o) pi8els, Modi)$ dri0e so that it also .eeps trac. o) some gi+en amount o) )uel, A mo+e b$ one pi8el should consume a )i8ed amount o) )uel, Solution E ercise !(<#<#< Modi)$ the two )unctions that control the state o) a single tra))ic light so that the$ control the state o) the two tra))ic lights at an ordinar$ intersection, #ach light can assume one o) three states: 'red! 'green! and '2e++ow, 1hen one is 'green or '2e++ow! the other one must be 'red, Recall the basics about the two )unctions )or a single tra))ic light:
66"init-traffic-+ight":""-/""0oid" 66"effects:"!1#"to"initia+i@e"c.rrent-co+or6"!2#"to"draw"traffic +ight

and
66"ne*t":""-/""0oid 66"effects:"!1#"to"change"c.rrent-co+or"from"'green"to"'2e++ow<" 66"'2e++ow"to"'red<"and"'red"to"'green 66"!2#"to"redraw"the"traffic"+ight"appropriate+2"

Modi)$ the basics )irst, 1hen the program is de+eloped and tested! de+elop a graphical displa$ li.e the )ollowing:

Ase the )unctions init-traffic-+ight and ne*t to dri+e the displa$! but .eep the )unctions that displa$ in)ormation separate )rom these two )unctions, Solution E ercise !(<#<$< In sections (6,6 and (;,; we de+eloped an e+aluator )or a portion o) Scheme, A t$pical Scheme implementation also pro+ides an I-T#RACTI4# user inter)ace, In DrScheme! the Interactions window pla$s this role, An interacti+e s$stem prompts the reader )or de)initions and e8pressions! e+aluates them appropriatel$! and possibl$ produces some result, De)initions are added to some repositor$E to con)irm the addition! the interacti+e s$stem ma$ produce a +alue li.e tr.e, #8pressions are e+aluated relati+e to the de)inition repositor$, The )unction interpret-with-defs )rom section (;,; per)orms this role, De+elop an interaction s$stem around interpret-with-defs, The s$stem should pro+ide at least two ser+ices: (, add-definition! which adds /the representation o)0 some )unction de)inition to the s$stemCs repositor$E &, e0a+.ate! which consumes /the representation o)0 some e8pression and e+aluates it relati+e to the current repositor$, I) a user adds two /or more0 de)initions )or some )unction f! the last addition is the one that matters, The pre+ious ones can be ignored, Solution

(0#* E,tended E,ercise. E,ploring Places

Figure 1.-' A tour o) a uni+ersit$

Figure 11.' Ta.e the tour

#arl$ computer games as.ed pla$ers to )ind their wa$ through dangerous ma*es and ca+es, The pla$er wanders )rom ca+e to ca+e! )inds treasures! encounters creatures o) all .inds! )ights! .isses! pic.s up energ$! and e+entuall$ reaches paradise, This section la$s out the basics o) such a game! using our iterati+e approach to program design, @ur tour ta.es place at one o) the scariest places o) all: campus, A campus consists o) buildings! some more dangerous than others, #ach building has a name and is connected to a group o) other buildings, The pla$er is alwa$s in a building, 1e re)er to this building as the c rrent !ocation, To )ind out more about the location! the pla$er can as. )or a picture o) the building and )or the list o) connections, The pla$er can also mo+e to one o) the connected buildings b$ issuing a go command, E ercise !(<$<1< Pro+ide structure and data de)initions )or buildings, Include a picture )ield in the structure, A campus is a list o) buildings, De)ine a sample campus, See )igure ('> )or a small e8ample, Solution E ercise !(<$<2< De+elop a program that permits a pla$er to mo+e through the sample campus o) e8ercise 5;,7,(, The program should support at least three ser+ices: (, show-me! which produces the picture o) the current location: see )igure (('E &, where-to-go! which produces the list o) connected buildingsE 5, go! which changes the current location o) the pla$er, I) the pla$er issues the command !go"s# and s is not connected to the current location! the )unction must report an error, De+elop other )unctions as necessar$ or as desired, Solution Pla$ers o) earl$ ma*e games could also gather obFects and trade obFects at the +arious sites, Speci)icall$! the pla$er had a bag )or carr$ing obFects! and each site contained obFects that the pla$er could trade )or things in the bag, E ercise !(<$<!< Modi)$ the tour program so that each building contains one obFect, Furthermore! the pla$er should ha+e a bag that contains /at most0 one obFect, At each

location! the pla$er can pic. up an obFect! i) the bag is empt$! or swap the obFect in the bag )or the obFect in the building otherwise, Modi)$ the program )urther so that the pla$er can carr$ an arbitrar$ number o) obFects in the bag, Solution The three e8ercises in this section illustrate how ma*e games wor., From here it is eas$ to e8periment with +arious )la+ors o) the game, Ta.ing a wal. )rom one building to another ma$ ta.e some energ$! and the pla$er ma$ ha+e onl$ a )inite amount o) energ$, Creatures ma$ )ight or .iss the pla$er! which consumes or replenishes the pla$erCs energ$ le+el, Ase $our imagination to e8tend the game and ha+e )riends ta.e the tour,

Section !) Interme**o (' The Final S%nta and Semantics


1ith the introduction o) setD2e8pressions and begin2e8pressions we ha+e co+ered most o) SchemeCs .ernel language, In DrScheme! this portion is called 'd0anced"Ct.dent Scheme, Considering the comple8it$ o) set!! this is a good place to summari*e our programming language in the spirit o) interme**o (, Following the organi*ation o) that interme**o! we discuss the +ocabular$! the grammar! and the meaning o) 'd0anced Ct.dent Scheme, The last subsection e8plains what .ind o) errors we ma$ encounter in 'd0anced"Ct.dent Scheme,

(4#$ The 'oca&ulary of

dvanced Scheme

The )oundation o) an$ language is its +ocabular$, In (eginning"Ct.dent Scheme! we distinguish )our categories o) words: +ariables! constants! primiti+e )unctions! and .e$words, The classi)ication ignores parentheses but we .now that e+er$ compound phrase is surrounded b$ a pair o) parentheses! and that e+er$ atomic phrase stands on its own, Scheme respects this basic classi)ication! though it contains )our important new .e$words: local! lambda! set!! and begin, The )irst two are important )or organi*ing and abstracting programsE the last two are important )or the computation o) e))ects, Still! .e$words per se ha+e no meaning, The$ are road signs that tell us what is ahead so that we can orient oursel+es, It is the grammar and the meaning o) a language that e8plains the role o) the .e$words,
'd0anced"Ct.dent

(4#" The 5rammar of

dvanced Scheme

#+en though Scheme is a )ull2)ledged language with as much power as an$ other programming language! its designers ha+e .ept its grammar simple, The grammar o) 'd0anced"Ct.dent Scheme! which is most o) Scheme! is onl$ a )ew lines longer than that o) (eginning"Ct.dent Scheme,

?def/

O /define /?0ar/ ?0ar/ ...?0ar/0 ?e*p/0 X /define ?0ar/ ?e*p/0 X /define2struct ?0ar%/ /?0ar-1/ ... ?0ar-n/00

?e*p/

O ?0ar/ X ?con/ X ?prm/ X /?e*p/ ?e*p/ ...?e*p/0 X /cond /?e*p/ ?e*p/0 .../?e*p/ ?e*p/00 X /cond /?e*p/ ?e*p/0 .../else ?e*p/00 X /local /?def/ ...?def/0 ?e*p/0 X /lambda /?0ar/ ...?0ar/0 ?e*p/0 X /setD ?0ar/ ?e*p/0 X /begin ?e*p/ ...?e*p/0 Figure 111' 'd0anced"Ct.dent Scheme: The core grammar

Figure ((( contains the essential grammar o) the 'd0anced"Ct.dent Scheme language,;( It e8tends Intermediate"Ct.dent Scheme with three new )orms o) e8pressions: lambda2e8pressions! setD2e8pressions! and begin2e8pressions, The speci)ication o) local2e8pressions re)ers to the categor$ o) de)initions! which re)ers bac. to the categor$ o) e8pressions, A lambda2e8pression consists o) a se?uence o) +ariables! enclosed in parentheses! and an e8pression, Similarl$! a setD2e8pression consists o) a +ariable and an e8pression, Finall$! a begin2e8pression is Fust a se?uence o) e8pressions pre)i8ed with the .e$word begin to distinguish it )rom an application, Since )unctions are +alues now! the grammar o) 'd0anced"Ct.dent Scheme is also simpler than that o) (eginning"Ct.dent Scheme in one regard, Speci)icall$! it merges the lines )or primiti+e and )unction application into a single line, The new line speci)ies applications! which are now se?uences o) e8pressions enclosed in parentheses, @wing to the inclusion o) primiti+e operations into the set o) e8pressions!
!+"1"2#

is still an e8pression, A)ter all! + is now an e8pression! and so are 1 and 2, The application o) defined )unctions wor.s similarl$:
!f"1"2#

The )irst e8pression is a +ariable! and the others are numbers, The application is thus a legal e8pression, An)ortunatel$! a language grammar can onl$ speci)$ the large contours o) what is a legal sentence construction, It cannot e8press restrictions that re?uire some .nowledge about the conte8t o) a phrase, 'd0anced"Ct.dent Scheme re?uires a )ew such restrictions:

(, In a lambda2e8pression no +ariable ma$ occur twice in the parameter se?uence, &, In a local2e8pression no de)inition ma$ introduce the same +ariable as an$ other de)inition in the same se?uence, 5, A setD2e8pression must occur in the le8ical scope o) a define that introduces the setD2e8pressionCs le)t2hand side, In addition! the old restriction applies that .e$words cannot be used as +ariables, Consider the )ollowing de)inition! which uses the new constructs:
!define"switch ""!local"!!define-struct"hide"!it## ""!define"state"!ma-e-hide"1### """"!lambda"!# """"""!begin !set!"state"!ma-e-hide"!-"1"!hide-it"state#### state####

The de)inition introduces the +ariable switch, The right2hand side o) the de)inition is a local2e8pression, It in turn de)ines the structure hide and the +ariable state! which stands )or an instance o) hide, The bod$ o) the local2e8pression is a lambda2 e8pression! whose parameter se?uence is empt$, The )unctionCs bod$ consists o) a begin2e8pression with two e8pressions: a setD2e8pression and an e8pression that consists o) Fust the +ariable state, All e8pressions in our program satis)$ the necessar$ restrictions, First! the local2 e8pression introduces )our names that are distinct: ma-e-hide! hideA! hide-it! and state, Second! the parameter list o) the lambda2e8pression is empt$! so there is no possible con)lict, Finall$! the setD2e8pressionCs +ariable is the locall$ de)ined +ariable state! so it is legal! too, E ercise !)<2<1< Determine whether the )ollowing phrases are s$ntacticall$ legal or illegal programs:
1."!define"!f"*#" """""""!begin "!set!"2"*# "*## 2."!define"!f"*#" """""""!begin "!set!"f"*# "*## 3."!local"!!define-struct"hide"!it## """""!define"ma-e-hide"1%##

"""""""!hideA"1%## 4."!local"!!define-struct"+oc"!con## """""!define"+oc"1%## """""""!+ocA"1%## 5."!define"f """""""!lambda"!*"2"*# "!*"*"2"@### """"" """""!define"@"3.14#

#8plain wh$ a phrase is legal or illegal,

Solution

(4#( The /eaning of

dvanced Scheme

1hen we )irst used 'd0anced"Ct.dent Scheme! we did so because we wanted to deal with )unctions as ordinar$ +alues, The e+aluation rules barel$ changed, 1e Fust agreed to allow e8pressions in the )irst position o) an application and to deal with the names o) )unctions as +alues, The e8tension o) the language with setD2e8pressions re?uired another change to our rules, -ow de)initions that associate +ariables and +alues can change o+er the course o) an e+aluation, The in)ormal rules weC+e used so )ar deal with changes to the de)inition o) state +ariables! because the$ matter the most, But the rules are in)ormal and imprecise! so a precise description o) how the addition o) set! changes the meaning o) the language must be our primar$ concern, "etCs recall how we determine the meaning o) a program, A program consists o) two parts: a collection o) de)initions and an e8pression, The goal is to e+aluate the e8pression! which means to determine the e8pressionCs +alue,;& In (eginning"Ct.dent Scheme! the collection o) +alues consists o) all the constants plus lists, @nl$ one list has a concise representation: the empt$ one, All other lists are written down as a series o) constructed lists, The e+aluation o) an e8pression consists o) a series o) steps, At each step we use the laws o) arithmetic and algebra to simpli)$ a sube8pression, This $ields another e8pression, 1e also sa$ that we R#1RIT# the )irst e8pression into the second, I) the second e8pression is a +alue! we are )inished, The introduction o) setD2e8pressions into our programming language re?uires a )ew small adFustments and e8tensions to this process: (, Instead o) rewriting Fust an e8pression! we must now rewrite de)initions and e8pressions, More precisel$! each step changes the e8pression and possibl$ the de)inition o) a state +ariable, To ma.e these e))ects as ob+ious as possible! each

stage in an e+aluation displa$s the de)initions o) state +ariables and the current e8pression, &, Furthermore! it is no longer possible to appl$ the laws o) arithmetic and algebra whene+er or where+er we want, Instead! we must determine the sube8pression that we must e+aluate i) we wish to ma.e progress, This rule still lea+es us with choices, For e8ample! when we rewrite an e8pression such as
3. !+"!*"3"3#"!*"4"4##

we ma$ choose to e+aluate !*"3"3# and then !*"4"4# or +ice +ersa, Fortunatel$! )or such simple e8pressions! the choice doesnCt a))ect the )inal outcome! so we donCt ha+e to suppl$ a complete unambigous rule, In general! though! we rewrite sube8pressions in a le)t2to2right and top2to2bottom order, At each stage in the e+aluation! we best start b$ underlining the sube8pression that must be e+aluated ne8t, 6, Suppose the underlined sube8pression is a setD2e8pression, B$ the restrictions on setD2e8pressions! we .now that there is a define )or the le)t2hand side o) the sube8pression, That is! we )ace the )ollowing situation:
5. ""!define"*"aWa+.e# . ""... 7. ""..."! """ set!"" " *""" anotherWa+.e# " ""..." $. &"!define"*"anotherWa+.e# ,. ""... 1%.""..."!0oid#"...

The e?uation indicates that the program changes in two wa$s, First! the +ariable de)inition is modi)ied, Second! the underlined setD2e8pression is replaced b$ !0oid#! the in+isible +alue, ((, The ne8t change concerns the replacement o) +ariables in e8pressions with the +alue in their de)inition, Antil now! we could replace a +ariable with its +alue where+er we thought it was con+enient or necessar$, Indeed! we Fust thought o) the +ariable as a shorthand )or the +alue, 1ith setD2e8pressions in the language! this is no longer possible, A)ter all! the e+aluation o) a setD2e8pression modi)ies the de)inition o) a state +ariable! and i) we replace a +ariable with its +alue at the wrong time! we get the wrong +alue, Suppoe that the underlined e8pression is a /state0 +ariable, Then we .now that we canCt ma.e an$ progress in our e+aluation until we ha+e replaced the +ariable with the current +alue in its de)inition, This suggests the )ollowing re+ised law )or +ariable e+aluation:
""!define"*"aWa+.e# ""... ""..."*"..." &"!define"*"aWa+.e#

""... ""..."aWa+.e"..."

In short! substitute the +alue in a state +ariable de)inition )or the state +ariable onl$ when the +alue is needed )or this particular occurrence o) the state +ariable, (&, "ast! but not least! we also need a rule )or begin2e8pressions, The simplest one sa$s to drop the )irst sube8pression i) it is a +alue:
13.""!begin"0"e*p-1"..."e*p-n# 14.&"!begin"e*p-1"..."e*p-n#

That means we also need a rule )or dropping begin completel$:


""!begin"e*p# &"e*p

In addition! we use a rule )or dropping se+eral +alues at once:


""!begin"0-1"..."0-m"e*p-1"..."e*p-n# &"!begin"e*p-1"..."e*p-n#

But this is onl$ a con+enience, Although the laws are more complicated than those o) (eginning"Ct.dent Scheme! the$ are still manageable, "etCs consider some e8amples, The )irst one demonstrates how the order o) e+aluation o) sube8pressions ma.es a di))erence:
""!define"*"5# ""!+"!begin"! """ set!"" " *"""# 11""*#"*# " &"!define"*"11# ""!+"!begin"!0oid#"*#"*# &"... &"!define"*"11# ""!+"11"*# &"!define"*"11# ""! "" +"""" 11"""# " 11"" "

The program consists o) one de)inition and one addition! which is to be e+aluated, @ne o) the additionCs arguments is a setD2e8pression that mutates *E the other is Fust *, B$ e+aluating the sube8pressions o) the addition )rom le)t to right! the mutation ta.es place be)ore we replace the second sube8pression with its +alue, As a result! the outcome is 22, I) we had e+aluated the addition )rom right to le)t! the result would ha+e been 1 , To a+oid such problems! we use the )i8ed ordering but gi+e oursel+es more )reedom when no state +ariables are in+ol+ed,

The second e8ample illustrates how a setD2e8pression that occurs in a local2e8pression actuall$ a))ects a top2le+el de)inition:
""!define"!ma-e-co.nter"*%# """"!local"!!define"co.nter"*%# """"!define"!increment# """"""!begin !set!"co.nter"!+"co.nter"1## co.nter### """"""increment## ""!! """ ma-e-co.nter"" " %" #" #

The program again consists o) a single de)inition and an e8pression that is to be e+aluated, The latter! howe+er! is an application nested in an application, The inner application is underlined! because we must e+aluate it to ma.e progress, Here are the )irst )ew steps:
&"!define"!ma-e-co.nter"*%# """"!local"!!define"co.nter"*%# """"!define"!increment# """"""!begin !set!"co.nter"!+"co.nter"1## co.nter### """"""increment## ""!!local"!!define"co.nter"%# """!define"!increment# """""!begin """""""!set!"co.nter"!+"co.nter"1## """""""co.nter### """""increment## &"!define"!ma-e-co.nter"*%# """"!local"!!define"co.nter"*%# """"!define"!increment# """"""!begin !set!"co.nter"!+"co.nter"1## co.nter### """"""increment## ""!define"co.nter1"%# ""!define"!increment1# """"!begin """"""!set!"co.nter1"!+"co.nter1"1## """"""co.nter1## ""!increment1#

The e+aluation o) the local2e8pression created additional top2le+el e8pressions, @ne o) them introduces a state +ariableE the others de)ine )unctions, The second part o) the e+aluation determines what !increment1# accomplishes:
""!define"co.nter1"%# ""! """ increment1# " "" &"!define"co.nter1"%# ""!begin """"!set!"co.nter1"!+"co.nter1"1## """"co.nter1# &"!define"co.nter1"%#

""!begin """"!set!"co.nter1"! "" +"" %"" 1" #" # """"co.nter1# &"!define"co.nter1"%# ""!begin """"! """ set!""" " co.nter1"" " 1" #" """"co.nter1# &"!define"co.nter1"1# ""!begin """"!0oid# """"co.nter1# &"!define"co.nter1"1# ""1

During the e+aluation! we replace co.nter1 with its +alue twice, First! the second step replaces co.nter1 with %! its +alue at that point, Second! we substitute 1 )or co.nter1 during the last step! which is its new +alue, E ercise !)<!<1< Anderline the sube8pression that must be e+aluated ne8t in the )ollowing e8pressions:
1."!define"*"11# """""!begin """""""!set!"*"!*"*"*## """""""*# 2."!define"*"11# """""!begin """""""!set!"*" "!cond """9!@eroA"%#"22: """9else"!/"1"*#:## """""""'done# 3."!define"!r.n"*# """""""!r.n"*## """""!r.n"1%# 4."!define"!f"*#"!*"pi"*"*## """""!define"a1"!f"1%## """""!begin """""""!set!"a1"!-"a1"!f"5### """""""'done# 5."!define"!f"*# """""""!set!"state"!-"1"state### """""!define"state"1# """""!f"!f"!f###

#8plain wh$ the e8pression must be e+aluated,

Solution

E ercise !)<!<2< Con)irm that the underlined e8pressions must be e+aluated ne8t:
1."!define"*"%# """""!define"2"1#

"""""!begin" """""""! """ set!"" " *"" 3" #" """""""!set!"2"4# """""""!+"!*"*"*#"!*"2"2### 2."!define"*"%# """""!set!"*" """""""!cond "9!@eroA"*#"1: "9else"%:## 3."!define"!f"*# """""""!cond "9!@eroA"*#"1: "9else"%:## """""!begin """""""! """ set!"" " f"""# 11"" " """""""f#

Rewrite the three programs to show the ne8t state, E ercise !)<!<!< #+aluate the )ollowing programs:
1."!define"*"%# """""!define"!8.mp"de+ta# """""""!begin "!set!"*"!+"*"de+ta## "*## """""!+"!8.mp"2#"!8.mp"3## 2."!define"*"1%# """""!set!"*"!cond """""""9!@eorA"*#"13: """""""9else"!/"1"*#:## 3."!define"!ma-e-8o*"*# """""""!local"!!define"contents"*# """""""!define"!new"2# "!set!"contents"2## """""""!define"!pee-# "contents## "!+ist"new"pee-### """"" """""!define"("!ma-e-8o*"55## """""!define"7"!ma-e-8o*"'a## """"" """""!begin """""""!!first"(#"33# """""""!!second"7###

Solution

Anderline )or each step the sube8pression that must be e+aluated ne8t, Show onl$ those steps that in+ol+e a local2e8pression or a setD2e8pression, Solution In principle! we could wor. with the rules we Fust discussed, The$ co+er the common cases! and the$ e8plain the beha+ior o) the programs we ha+e encountered, The$ do not e8plain! howe+er! how an assignment wor.s when the le)t2hand side re)ers to a defined )unction, Consider the )ollowing e8ample! )or which the rules still wor.:

""!define"!f"*#"*# "" ""!begin" """"! """ set!"" " f"""# 1%"" " """"f# &"!define"f"1%# "" ""!begin" """"!0oid# """"f#

Here f is a state +ariable, The setD2e8pression changes the de)inition so f stands )or a number, The ne8t step in an e+aluation substitutes 1% )or the occurrence o) f, Ander ordinar$ circumstances! an assignment would replace a )unction de)inition with a di))erent )unction de)inition, Ta.e a loo. at this program:
""!define"!f"*#"*# ""!define"g"f# ""!+"!begin"! """ set!"" " f"" "!lambda "" ""* "! """22 #"""## " """5#"!g"1##

The purpose o) the underlined setD2e8pression is to modi)$ the de)inition o) f so that it becomes a )unction that alwa$s produces 22, But g stands )or f initiall$, Since f is a the name o) a )unction! we can thin. o) !define"g"f# as a +alue de)inition, The problem is that our current rules change the de)inition o) f and! b$ implication! the de)inition o) g! because it stands )or f:
&"!define"f"!lambda"!*#"22## ""!define"g"f# ""!+"! """ begin"!0oid#" " "" "" 5 #"!g"1## &"!define"f"!lambda"!*#"22## ""!define"g"f# ""!+"5"! "" g"" 1" #" # &"!define"f"!lambda"!*#"22## ""!define"g"f# ""!+"5"22#

Scheme! howe+er! does not beha+e this wa$, A setD2e8pression can modi)$ onl$ one de)inition at a time, Here it modi)ies two: fCs! which is intended! and gCs! which happens through the indirection )rom g to f, In short! our rules do not e8plain the beha+ior o) all programs with setD2e8pressionsE we need better rules i) we wish to understand Scheme )ull$,

?0df/

O /define ?0ar/ ?0a+/0 X /define2struct ?0ar/ /?0ar/ ...?0ar/00 O ?con/ X ?+st/ X ?prm/ X ?f.n/ X ?0oid/ O empt$ X /cons ?0a+/ ?+st/0

?0a+/ ?+st/ ?f.n/

O /lambda /?0ar/ ...?0ar/0 ?e*p/0 Figure 112' 'd0anced"Ct.dent Scheme: The +alues

The problem concerns the de)initions o) )unctions! which suggests that we ta.e a second loo. at the representation o) )unctions and )unction de)initions, So )ar! we used the names o) )unctions as +alues, As we ha+e Fust seen! this choice ma$ cause trouble in case the state +ariable is a )unction, The solution is to use a concrete representation o) )unctions, Fortunatel$! we alread$ ha+e one in Scheme: lambda2e8pressions, Furthermore! we rewrite )unction de)initions so that the$ turn into +ariable de)initions with a lambda2e8pression on the right2hand side:
""!define"!f"*#"*# &"!define"f"!lambda"!*#"*##

#+en recursi+e de)initions are e+aluated in this manner:


""!define"!g"*#" """"!cond """"""9!@eroA"*#"1: """"""9else"!g"!s.81"*##:## &"!define"g """"!lambda"!*# """"""!cond 9!@eroA"*#"1: 9else"!g"!s.81"*##:###

All other rules! including the rule )or replacing +ariables with their +alues! remain the same, Figure ((& speci)ies the set o) +alues!;5 as a subset o) the set o) e8pressions! and the set o) +alue de)initions! as a subset o) the de)initions, Asing these de)initions and the modi)ied rules! we can ta.e a second loo. at at the abo+e e8ample:
""! """ define"! " ""f """ *""* #""" " #" ""!define"g"f# ""!+"!begin"!set!"f"!lambda"!*#"22##"5#"!g"1## &"!define"f"!lambda"!*#"*## ""!define"g"f# ""!+"!begin"!set!"f"!lambda"!*#"22##"5#"!g"1## &"!define"f"!lambda"!*#"*## ""!define"g"!lambda"!*#"*##

""!+"!begin"! """ set!"" " f"" "!lambda "" ""* "! """22 #"""## " """5#"!g"1## &"!define"f"!lambda"!*#"22## ""!define"g"!lambda"!*#"*## ""!+"! """ begin"!0oid#" " "" "" 5 #"!g"1## &"!define"f"!lambda"!*#"22## ""!define"g"!lambda"!*#"*## ""!+"5"! "" g"" 1" #" # &"!define"f"!lambda"!*#"22## ""!define"g"!lambda"!*#"*## ""!+"5"1#

The .e$ di))erence is that the de)inition o) g directl$ associates the +ariable with a )unction representation! not Fust a name )or a )unction, The )ollowing program shows the e))ects o) setD2e8pressions on )unctions with an e8treme e8ample:
!define"!f"*# ""!cond """"9!@eroA"*#"'done: """"9else"!f"!s.81"*##:## !define"g"f# !begin" ""!set!"f"!lambda"!*#"'o.ch## ""!s2m8o+&A"!g"1#"'o.ch##

The )unction f is recursi+e on natural numbers and alwa$s produces 'done, Initiall$! g is de)ined to be f, The )inal begin2e8pression )irst modi)ies f and then uses g, At )irst! we must rewrite the )unction de)initions according to our modi)ied rules:
&"!define"f """"!lambda"!*# """"""!cond 9!@eroA"*#"'done: 9else"!f"!s.81"*##:### ""!define"g"f# ""!begin" """"!set!"f"!lambda"!*#"'o.ch## """"!s2m8o+&A"!g"1#"'o.ch## &"!define"f """"!lambda"!*# """"""!cond 9!@eroA"*#"'done: 9else"!f"!s.81"*##:### ""!define"g" """"!lambda"!*# """"""!cond 9!@eroA"*#"'done: 9else"!f"!s.81"*##:### ""!begin"

""""! """ set!"" " f"" "!lambda "" ""* "! """ #"' " """ o.ch## " "" """"!set!"f"!lambda"!*#"'o.ch## """"!s2m8o+&A"!g"1#"'o.ch##

Rewriting the de)inition o) f is straight)orward, The maFor change concerns the de)inition o) g, Instead o) f it now contains a cop$ o) the +alue )or which f currentl$ stands, This +alue contains a re)erence to f! but that is not unusual, -e8t! the setD2e8pression modi)ies the de)inition o) f:
""... &"!define"f """"!lambda"!*#" """"""'o.ch## "" ""!define"g" """"!lambda"!*# """"""!cond 9!@eroA"*#"'done: 9else"!f"!s.81"*##:### "" ""!begin" """"!0oid# """"!s2m8o+&A"! "" g"" 1" #"'o.ch##

-o other de)inition! howe+er! is a))ected, In particular! the de)inition o) g remains the same! though the f inside o) gCs +alue now re)ers to a new +alue, But we ha+e seen this phenomenon be)ore, The ne8t two steps )ollow the basic rules o) interme**o (:
""... &"!define"f """"!lambda"!*#" """"""'o.ch## "" ""!define"g" """"!lambda"!*# """"""!cond 9!@eroA"*#"'done: 9else"!f"!s.81"*##:### "" ""!begin" """"!0oid# """"!s2m8o+&A"!f"%#"'o.ch## &"!define"f """"!lambda"!*#" """"""'o.ch## "" ""!define"g" """"!lambda"!*# """"""!cond 9!@eroA"*#"'done: 9else"!f"!s.81"*##:### "" ""!begin" """"!0oid# """"!s2m8o+&A"'o.ch"'o.ch##

That is! the application o) g e+entuall$ applies f to %! which $ields 'o.ch, Hence the )inal result is tr.e, E ercise !)<!<#< 4alidate that the )ollowing program e+aluates to tr.e:
!define"!ma-e-8o*"*# ""!local"!!define"contents"*# ""!define"!new"2#"!set!"contents"2## ""!define"!pee-#"contents## """"!+ist"new"pee-### !define"("!ma-e-8o*"55## !define"7"(# !and" ""!begin" """"!!first"(#"33# """"tr.e# ""!&"!second"7#"33# ""!begin """"!set!"("!ma-e-8o*"44## """"!&"!second"7#"33###"

Anderline )or each step the sube8pression that must be e+aluated ne8t, Show onl$ those steps that in+ol+e a local2e8pression or a setD2e8pression, Solution 1hile we decided to rewrite )unction de)initions so that their right2hand side are alwa$s lambda2e8pressions! we stuc. with a )unction application rule that assumes )unction de)initions in the st$le o) (eginning"Ct.dent Scheme, More concretel$! i) the de)inition conte8t contains a de)inition such as
!define"f"!lambda"!*"2#"!+"*"2###

and the e8pression is


!*"!f"1"2#"5#

then the ne8t step in the e+aluation is


!*"!+"1"2#"5#

For other occasions! howe+er! we Fust replace +ariables with the +alues in the respecti+e de)initions, I) we )ollowed that rule! we would rewrite
!*"!f"1"2#"5#

to
!*"!!lambda"!*"2#"!+"*"2## """"1"2# """5#

At )irst glance! this e8ploration route ends here! because there are no laws )or this application, 1e can reconcile the two ideas with a new law! suggested b$ the last e8pression:
""!!lambda"!*-1"..."*-n#"e*p# """0-1"..."0-n# &"e*p""with"a++""*-1"..."*-n""rep+aced"82""0-1"..."0-n

The law ser+es as a replacement o) the law o) application )rom algebra in the stud$ o) the )oundations o) computing, B$ con+ention! this law is called the ?v /pronounced DDbeta +alueCC0 a8iom, 5eta and the ,ambda Calculus: The orginal ? a8iom was )ormulated b$ Alon*o Church in the late (>&'s as )ollows:
""!!lambda"!*#"e*p# """e*p-1# &"e*p""with""*""rep+aced"82""e*p-1

It does not restrict the argument in a )unction application to be a +alue, The interest o) Church and other logicians;6 was to e8plore the principles o) computation! what computation could achie+e! and what it couldnCt, The$ con)irmed that the a8iom and a small sublanguage o) Scheme! namel$! O ?0ar/ X /lambda /?0ar/0 ?e*p/0 X /?e*p/ ?e*p/0 are enough to de)ine all computable )unctions on a /simulation o)0 the natural numbers, Functions that cannot be )ormulated in this language are not computable,
?e*p/

The language and the ? a8iom became .nown as the lambda /pronounced: DDlambdaCC0 calculus, =erald Sussman and =u$ ", Steele Jr, later based Scheme on the lambda calculus, In the mid2(>;'s! =ordon Plot.in suggested the ?v a8iom as a better method )or understanding )unction applications in programming languages such as Scheme,

(4#) Errors in

dvanced Scheme

The e8tension o) our language with )unctions as +alues introduces not onl$ new powers )or the programmer but also new possibilities )or errors, Recall that there are three .inds o) errors: s$nta8 errors! run2time /or semantics0 errors! and logical errors, 'd0anced Ct.dent Scheme turns a class o) s$ntactic errors o) (eginning"Ct.dent Scheme into run2time errors, It also introduces a new )orm o) logical error, Consider the )ollowing program:
66"how-man2-in-+ist":"!listof"R#""-/""N 66"to"co.nt"how"man2"items"a+ist"contains" !define"!how-man2-in-+ist"a+ist# ""!cond

""""9empt2A"!a+ist#: """"9else"!+"!how-man2-in-+ist"!rest"a+ist##"1#:##

In (eginning"Ct.dent Scheme or Intermediate"Ct.dent Scheme! DrScheme would ha+e signaled a s$nta8 error because a+ist is the parameter to a )unction but is also used as a )unction, Because )unctions are +alues in 'd0anced"Ct.dent Scheme! DrScheme must now accept this )unction de)inition as s$ntactiall$ correct, 1hen the )unction is applied to empt2 or an$ other list +alue! howe+er! DrScheme soon applies empt2 to no arguments! which is a run2time error, A)ter all! lists are not )unctions, DrScheme signals immediatel$ with an error message an$ attempt to appl$ a non2 )unction and stops the e+aluation, The second )orm o) error is logical, That is! a program that su))ers )rom this )orm o) error doesnCt produce a s$nta8 or a run2time error message, Instead! it produces wrong answers, Ta.e a loo. at the )ollowing two de)initions:
!define"f+ip1 ""!local"!!define"state 1## """"!lambda"!# """"""!begin !set!"state"!-"1 state## state#### !define"f+ip2 ""!lambda"!# """"!local"!!define"state 1## """"""!begin !set!"state"!-"1 state## state#### a local de)inition whose bod$

The$ di))er in the order o) two lines, @ne introduces e+aluates to a )unction, The other de)ines a )unction whose bod$ contains a local2 e8pression, According to our rules! the de)inition on the le)t rewrites to
!define"state1"1# !define"f+ip1 ""!lambda"!# """"!begin """"""!set!"state1"!-"1 state1## """"""state1###

!define"f+ip2 ""!lambda"!# """"!local"!!define"state 1## """"""!begin !set!"state"!-"1 state## state####

The one on the right alread$ associates a name with a )unction, "et us now see how the two )unctions ha+e radicall$ di))erent beha+iors, To do so! we e+aluate the e8pressions
!and"!&"!f+ip1#"%# """""!&"!f+ip1#"1# """""!&"!f+ip1#"%## !and"!&"!f+ip2#"%# """""!&"!f+ip2#"1# """""!&"!f+ip2#"%##

in the conte8t o) the respecti+e de)initions, Here are the )irst )our steps o) the e+aluation )or the e8pression on the le)t2hand side:
""!define"state1"1# ""!and"!&"!f+ip1#"%# """""""!&"!f+ip1#"1# """""""!&"!f+ip1#"%##

&"!define"state1"1# ""!and"!&"!begin """"!set!"state1"!-"1"state1## """"state1# ""%# """""""!&"!f+ip1#"1# """""""!&"!f+ip1#"%## &"!define"state1"1# ""!and"!&"!begin """"!set!"state1"%# """"state1# ""%# """""""!&"!f+ip1#"1# """""""!&"!f+ip1#"%## &"!define"state1"%# ""!and"!&"!begin """"!0oid# """"state1# ""%# """""""!&"!f+ip1#"1# """""""!&"!f+ip1#"%## &"!define"state1"%# ""!and"!&"%"%# """""""!&"!f+ip1#"1# """""""!&"!f+ip1#"%##

The rele+ant de)inition conte8t is the de)inition o) state1! which we see changing )rom 1 to % during the third step, From this point! it is not di))icult to +alidate that the e8pression produces tr.e and that state1 ends up being %, Compare this with the )irst three steps in the e+aluation o) the right2hand e8pression:
""!and"!&"!f+ip2#"%# """""""!&"!f+ip2#"1# """""""!&"!f+ip2#"%## &"!and"!&"!local"!!define"state"1## """"!begin """"""!set!"state"!-"1"state## """"""state## ""%# """""""!&"!f+ip2#"1# """""""!&"!f+ip2#"%## &"!define"state1"1# ""!and"!&"!begin """"!set!"state1"!-"1"state1## """"state1# ""%# """""""!&"!f+ip2#"1# """""""!&"!f+ip2#"%## &"!define"state1"%# ""!and"!&"%"%# """""""!&"!f+ip2#"1# """""""!&"!f+ip2#"%##

The onl$ de)inition that matters here is the one )or f+ip2, Super)iciall$! the two e+aluations are ali.e, But a closer loo. shows that the second one di))ers )rom the )irst in crucial wa$, It creates the de)inition )or state1 while the )irst e+aluation started with such a de)inition, Here is the continuation o) the second e+aluation:
""..." &"!define"state1"%# ""!and"tr.e """""""!&"!local"!!define"state"1## """"!begin """"""!set!"state"!-"1"state## """"""state## ""1# """""""!&"!f+ip2#"%## &"!define"state1"%# ""!define"state2"1# ""!and"tr.e """""""!&"!begin """"!set!"state2"!-"1"state2## """"state2# ""1# """""""!&"!f+ip2#"%## &"!define"state1"%# ""!define"state2"%# ""!and"tr.e """""""!&"!begin """"!0oid# """"state2# ""1# """""""!&"!f+ip2#"%## &"!define"state1"%# ""!define"state2"%# ""!and"tr.e """""""!&"%"1# """""""!&"!f+ip2#"%##

It shows that f+ip2 creates a new de)inition e+er$ time it is applied and that it alwa$s produces %, Contrar$ to its name! it does not )lip the +alue o) state upon e+er$ application, As a result! the e+aluation ends now with two new top2le+el de)initions and the +alue fa+se, The general moral is that a )unction de)ined in a local2e8pression is di))erent )rom a )unction whose bod$ contains a local2e8pression, The )irst ensures that some de)initions are accessible onl$ to a )unction, The de)inition e8ists once and onl$ once )or this )unction, In contrast! the second creates a new /top2le+el0 de)inition )or e+er$ e+aluation o) the )unction bod$, In the ne8t part o) the boo.! we e8ploit both ideas to create new .inds o) programs,

;(

The grammar misses and2e8pression and or2e8pression! and a )ew other short2cuts,

1e also e+aluate the right2hand side o) de)initions i) the$ are not +alues! but we can sa)el$ ignore this minor issue here,
;&

;5

It lac.s a speci)ication o) structural +alues! but the$ pla$ no role in this discussion, "ogic is to computing what mathematics is to ph$sics,

;6

Part "III Changing Compound "alues Section !Encapsulation


1hen we design a program to control a tra))ic light! we probabl$ donCt want to control Fust one tra))ic light! but se+eral, Similarl$! when we design a program to manage names and phone numbers! we might wish to manage se+eral address boo.s! not Fust one, @) course! we could cop$ the code )or a tra))ic light controller /or an address boo. manager0 and rename the state +ariables! but cop$ing code is bad, Furthermore! we might wish to create so man$ tra))ic lights that cop$ing code is plain impractical, The proper solution is to use the power o) abstraction, Here we abstract o+er se+eral instances o) the address boo. program and the tra))ic light program and so on, This di))ers )rom the notion o) abstraction in part I4 because it in+ol+es state +ariables! but the idea and e+en the techni?ue is the same, 1e encapsulate the state +ariables and the )unctions in a local2e8pression and thus gi+e oursel+es the power to create as man$ +ersions as necessar$, 1e learn how to encapsulate state +ariables in the )irst subsection! and practice it in the second one,

(6#$

&stracting !ith State 'aria&les

Suppose we wish to turn the program in )igure ('' /page 670 into a program )or managing /simulated0 tra))ic lights, An operator o) the simulation should be able to control each tra))ic light independentl$ o) the others, Indeed! the operator should be able to add or shut down tra))ic lights while the rest o) the s$stem remains unchanged and running, Based on our e8perience! we .now that each tra))ic light in the simulation re?uires two de)initions:

(, a state +ariable! c.rrent-co+or! which .eeps trac. o) the lightCs current colorE and &, a ser+ice )unction! ne*t! which switches the tra))ic light to the ne8t color according to the tra))ic laws, For a graphical simulation! the ser+ice )unction would also redraw the tra))ic light so that users can +iew the current color, Finall$! each tra))ic light has a uni?ue location on the can+as:

The sample program o) )igure ('' deals with a single tra))ic light and lac.s the drawing operation, The problem now is to turn this into a program that can create as man$ tra))ic lights as needed! each with its own state +ariables and switching )unctions and at its own location, I) we were to cop$ the de)initions in )igure ('' and add de)initions )or dealing with the can+as! the +arious instances would di))er in onl$ one aspect: the data concerning the location o) the tra))ic light, This thought e8periment suggests that we should de+elop an abstract )unction that creates and manages tra))ic lights at +arious locations, Because the original program consists o) se+eral top2le+el de)initions! we use the recipe o) section &&,&! which suggests wrapping the de)initions in a local2e8pression inside a )unction, 1hen local de)initions include state +ariables! as in this e8ample! we pre)er to sa$ that we #-CAPSA"AT# de)initions, This terminolog$ emphasi*es that the abstract )unction hides the state +ariables )rom other parts o) the program, In particular! it implies that b$ putting a state +ariable in a local2e8pression we guarantee that it can change onl$ according to the managed ser+ices! not b$ arbitrar$ assignments, Still! the de)inition encapsulates and abstracts at the same time! and a programmer must .eep this in mind,

66"Wiew: 66"draw-+ight":";L-co+or"n.m8er""-/""tr.e 66"to"!re#draw"the"traffic"+ight"on"the"can0as" !define"!draw-+ight"c.rrent-co+or"*-posn#"...## 66"Hode+: 66"ma-e-traffic-+ight":"s2m8o+"n.m8er""-/""!"-/""tr.e# 66"to"create"a"red"+ight"with"!ma-e-posn"*-posn"%#"as"the".pper+eft"corner 66"effect:"draw"the"traffic"+ight"on"the"can0as !define"!ma-e-traffic-+ight"street"*-posn# ""!local"!66"c.rrent-co+or":";L-co+or """"""""""66"to"-eep"trac-"of"the"c.rrent"co+or"of"the"traffic +ight """"""""""!define"c.rrent-co+or"'red# "" ""66"init-traffic-+ight":""-/""tr.e ""66"to"!re#set"c.rrent-co+or"to"red"and"to"!re#create"the 0iew" ""!define"!init-traffic-+ight# """"!begin """"""!set!"c.rrent-co+or"'red# """"""!draw-+ight"c.rrent-co+or"*-posn### "" """"""""""66"ne*t":""-/""tr.e """"""""""66"effect:"to"change"c.rrent-co+or"from"'green"to '2e++ow<" """"""""""66"'2e++ow"to"'red<"and"'red"to"'green """"""""""!define"!ne*t# """"""""""""!begin """"""""""""""!set!"c.rrent-co+or"!ne*t-co+or"c.rrent-co+or## """"""""""""""!draw-+ight"c.rrent-co+or"*-posn### "" """"""""""66"ne*t-co+or":";L-co+or""-/"";L-co+or """"""""""66"to"comp.te"the"s.ccessor"of"c.rrent-co+or"8ased"on the"traffic"+aws """"""""""!define"!ne*t-co+or"c.rrent-co+or# """"""""""""!cond """"""""""""""9!s2m8o+&A"'green"c.rrent-co+or#"'2e++ow: """"""""""""""9!s2m8o+&A"'2e++ow"c.rrent-co+or#"'red: """"""""""""""9!s2m8o+&A"'red"c.rrent-co+or#"'green:### """"!begin """"""66"Initia+i@e"and"prod.ce"ne*t """"""!init-traffic-+ight#

ne8t000

Figure 11!' Managing multiple tra))ic lights The ne8t step is to consider what this )unction should do! that is! what it should consume! what it should produce! and what e))ects it should ha+e! i) an$, "etCs start with the name, 1e call the new )unction ma-e-traffic-+ightE a)ter all! ma.ing a simulated tra))ic light is the purpose o) the abstracted program, Furthermore! according to our abstraction recipes! an abstraction must consume +alues that represent the uni?ue aspects o) an instance, The uni?ue aspect o) a tra))ic light is its position on the can+asE )or clarit$! letCs add a ph$sical address! too, #+er$ use o) ma-e-traffic-+ight should create a tra))ic light and enable the operator to switch it )rom one state to the ne8t, The )irst part suggests an e))ect, Speci)icall$! the )unction should initiali*e the state +ariable and draw the initial state o) the tra))ic light at

the designated position on the can+as, The second part o) the statement suggests a result: a )unction )or switching the state o) the tra))ic light, Figure ((5 contains the outline o) the tra))ic simulator! including the complete de)inition o) ma-e-traffic-+ight, The simulator consists o) a model and a +iew, The model is ma-e-traffic-+ight, The +iew is called draw-+ight and is onl$ s.etchedE the )ull de)inition o) the +iew is le)t as an e8ercise, The de)inition o) ma-e-traffic-+ight is an ordinar$ )unction de)inition, It uses a local de)inition to set up the single state +ariable! the initiali*er! and the state2changing )unction, The bod$ o) the local2e8pression uses the initiali*er and then produces ne*t as the )unctionCs +alue, Asing ma-e-traffic-+ight we can create se+eral indi+idual tra))ic lights or entire collections o) them, 1e could also add lights as time goes b$, First! we create a su))icientl$ large can+as:
66"create"the"can0as"first" !start"3%%"1 %#

Second! we appl$ ma-e-traffic-+ight as o)ten as needed:


66"+ights":"!listof"traffic-+ight# 66"to"manage"the"+ights"a+ong"C.nrise" !define"+ights ""!+ist"!ma-e-traffic-+ight"'s.nriseYrice"5%# """"""""!ma-e-traffic-+ight"'s.nriseYcm."15%###

Here we de)ine +ights to be a list o) two tra))ic lights, #ach tra))ic light is a )unction! so +ights stands )or a list o) two )unctions, A)ter creating the tra))ic lights! we can change their states as desired, To do so! we must .eep in mind that each tra))ic light is represented b$ a )unction that consumes nothing and produces tr.e, Its e))ect is to change the hidden state +ariable and the drawing on the can+as, In our running e8ample! we could use the Interactions window as )ollows:
/"!!second"+ights##" tr.e /"!andmap"!lambda"!a-+ight#"!a-+ight##"+ights# tr.e

The )irst interaction e8tracts the second item )rom +ights and applies it, This sets the light at 's.nriseYcm. to green, The second one switches the state o) all items on +ights, #ach application o) ma-e-traffic-+ight turns +ariants o) the local de)initions into top2le+el de)initions! a)ter renaming them, Because the abo+e define contains two

applications o) ma-e-traffic-+ight! it creates two copies o) each locall$ de)ined )unction and state +ariable during an e+aluation:
66"definitions"for"'s.nriseYrice !define"c.rrent-co+orYrice"'red# !define"!init-traffic-+ightYrice#" ""!begin """"!set!"c.rrent-co+orYrice"'red# """"!draw-+ight"c.rrent-co+orYrice"5%### !define"!ne*tYrice#"...# !define"!ne*t-co+orYrice"c.rrent-co+or#"...#

66"definitions"for"'s.nriseYcm. !define"c.rrent-co+orYcm."'red# !define"!init-traffic-+ightYcm.# ""!begin """"!set!"c.rrent-co+orYcm."'red# """"!draw-+ight"c.rrent-co+orYcm."15%### !define"!ne*tYcm.#"...# !define"!ne*t-co+orYcm."c.rrent-co+or#"...# !define"+ights ""!+ist"ne*tYrice """"""""ne*tYcm.##

The new top2le+el de)initions o) init-traffic-+ight show how the renaming ensures that one o) them ta.es care o) 's.nriseYrice and the other one o) 's.nriseYcm.,

E ercise !-<1<1< 1hat is the e))ect o) the second interaction abo+eH

Solution

E ercise !-<1<2< Fill in the bodies o) ne*tYrice and ne*tYcm. in the hand2e+aluated program, Then e+aluate !!second"+ights## in the conte8t o) these de)initions, Solution E ercise !-<1<!< De+elop the )unction draw-+ight, It reali*es the +iew part o) the tra))ic light simulation in )igure ((5, #ach tra))ic light should be as tall as the can+as! delineated b$ solid lines on the le)t and right, The suggested dimensions o) a single light are
!define"OID;="5%# !define"Q'DIPC"2%# !define"DIC;'J75-(5;O55J-(PL(C"1%# 66"the"minim.m"can0as"height !define"=5IG=;" ""!+"DIC;'J75-(5;O55J-(PL(C

"""""!*"2"Q'DIPC# """""DIC;'J75-(5;O55J-(PL(C """""!*"2"Q'DIPC# """""DIC;'J75-(5;O55J-(PL(C """""!*"2"Q'DIPC# """""DIC;'J75-(5;O55J-(PL(C##

De+elop the necessar$ de)initons separate )rom the rest o) the tra))ic light program! then create a single )unction de)inition using local, Solution -ow suppose we wish to pro+ide the additional ser+ice o) resetting an indi+idual tra))ic light, That is! in addition to switching )rom the current color to the ne8t! an operator should be able to set a tra))ic light to red, The )unction )or doing so alread$ e8ists: init-traffic-+ight, It sets c.rrent-co+or to 'red and redraws the image on the can+as, But! init-traffic-+ight is inaccessible because it is de)ined within the local2 e8pression o) ma-e-traffic-+ight, I) we wish the )unction to be +isible! it must be the result o) ma-e-traffic-+ight Fust li.e ne*t,
66"ma-e-traffic-+ight":"s2m8o+"n.m8er""-/""!s2m8o+""-/""tr.e# 66"to"create"a"red"+ight"with"!ma-e-posn"*-posn"%#"as"the".pper+eft"corner 66"effect:"draw"the"traffic"+ight"on"the"can0as !define"!ma-e-traffic-+ight"street"*-posn# ""!local"!66"Hode+: """"""""""66"c.rrent-co+or":";L-co+or """"""""""66"to"-eep"trac-"of"the"c.rrent"co+or"of"the"traffic +ight """"""""""!define"c.rrent-co+or"'red# "" ""66"init-traffic-+ight":""-/""tr.e ""66"to"!re#set"c.rrent-co+or"to"red"and"to"!re#create"the 0iew" ""!define"!init-traffic-+ight#"...# "" """"""""""66"ne*t":""-/""tr.e """"""""""66"effect:"to"change"c.rrent-co+or"from"'green"to '2e++ow<" """"""""""66"'2e++ow"to"'red<"and"'red"to"'green """"""""""!define"!ne*t#"...# "" """"""""""66"ne*t-co+or":";L-co+or""-/"";L-co+or """"""""""66"to"comp.te"the"s.ccessor"of"c.rrent-co+or"8ased"on the"traffic"+aws """"""""""!define"!ne*t-co+or"c.rrent-co+or#"...# ""66"ser0ice-manager":"!s2m8o+""-/""tr.e# ""66"to"app+2"either"ne*t"or"init-traffic-+ight ""!define"!ser0ice-manager"msg# """"!cond """"""9!s2m8o+&A"msg"'ne*t#"!ne*t#: """"""9!s2m8o+&A"msg"'reset#"!init-traffic-+ight#: """"""9else"!error"'traffic-+ight"1message"not .nderstood1#:### """"!begin """"""66"Initia+i@e"and"prod.ce"ser0ice-manager """"""!init-traffic-+ight#

ser+ice2manager000 Figure 11#' Managing multiple tra))ic lights with a reset ser+ice

To ma.e both ne*t and init-traffic-+ight a result o) ma-e-traffic-+ight re?uires some wa$ o) combining the two )unctions into a single +alue, Since )unctions are +alues in Scheme! we could combine the two )unctions in a list! a structure! or e+en a +ector, Another possibilit$ is to combine the two )unctions in a third )unction, Here we discuss this third possibilit$ because it is an important techni?ue in the conte8t o) managing state +ariables and ser+ices, 1e call the new .ind o) )unction ser0ice-manager! because it hides and manages )unctions that implement ser+ices, The )unction accepts two s$mbols: (, 'ne*t! which indicates that !ne*t# should be e+aluated! and &, 'reset! which indicates that !reset# should be e+aluated, Furthermore! the )unction is the result o) the re+ised +ersion o) ma-e-traffic-+ight, Figure ((6 contains the modi)ied de)inition o) ma-e-traffic-+ight, Since an operator ma$ mista.enl$ appl$ )unctions to inappropriate arguments! ser0ice-manager is a chec.ed )unction in the sense o) section ;,7, It signals an error i) the input is a s$mbol other than 'ne*t or 'reset, 1e use the new ma-e-traffic-+ight )unction e8actl$ li.e the old one:
66"create"the"can0as"first" !start"3%%"1 %# 66"+ights":"!listof"traffic-+ight# 66"to"manage"the"+ights"a+ong"C.nrise" !define"+ights ""!+ist"!ma-e-traffic-+ight"'s.nriseYrice"5%# """"""""!ma-e-traffic-+ight"'s.nriseYcm."15%###

The result! howe+er! is that now e+er$ tra))ic light is represented as a )unction on s$mbols:
/"!!second"+ights#"'ne*t#" tr.e /"!andmap"!lambda"!a-+ight#"!a-+ight"'reset##"+ights# tr.e

The )irst interaction switches the initiall$ red light labeled 's.nriseYcm. to 'green, The second one changes the state o) e+er$ light bac. to 'red s.ipping the '2e++ow stage )or the light at 's.nriseYcm.,

E ercise !-<1<#< Complete the de)inition o) the program in )igure ((6! using the )unction )rom e8ercise 5>,(,5, Then use DrSchemeCs Interactions window to switch and reset tra))ic lights, Solution E ercise !-<1<$< #+aluate the abo+e program b$ hand and con)irm that the light labeled 's.nriseYrice switches )rom 'green directl$ bac. to 'red, Solution For the address2boo. e8ample )rom part 4II! the need )or managing two ser+ices is e+en more apparent, A)ter all! the moti+ating idea behind the e8ample is that users can access one state +ariable with two di))erent ser+ices: add-to-address-8oo- )or adding new entries and +oo-.p )or loo.ing up the phone number )or a gi+en name, Following our encapsulation recipe! we must (, de)ine a )unction ma-e-address-8oo- whose bod$ is a local2e8pressionE &, place the de)initions in this local2e8pressionE and 5, introduce a )unction called ser0ice-manager to manage the two ser+ices, B$ now! we ha+e the )irst two steps )irml$ under controlE the last one! howe+er! is comple8 here! because unli.e in the pre+ious case! the two )unctions that implement the ser+ices consume di))erent numbers o) arguments and produce di))erent .inds o) results, "etCs )irst agree on the inputs )or ser0ice-manager, Two good mnemonic s$mbols are 'add )or adding phone numbers and 'search )or loo.ing up the number )or some gi+en name, This suggests the )ollowing template:
!define"!ser0ice-manager"msg# ""!cond """"9!s2m8o+&A"msg"'add#"..."'"...: """"9!s2m8o+&A"msg"'search#"..."("...: """"9else"!error"'address-8oo-"1message"not".nderstood1#:##

The problem is that it is not clear how to replace ' and ( with +alid Scheme e8pressions that compute the appropriate +alue and e))ect, For '! we need not onl$ msg but also a name and a phone number, For (! we need the name, @ne solution is to produce )unctions that consume the additional arguments and then per)orm the appropriate computation, In other words! ser0ice-manager is now a )unction that produces a )unction )or two s$mbols, Since we ha+e not encountered this .ind o) result be)ore! we introduce a new )orm o) data de)inition:

An address-boo$ is an inter)ace: (, 'add :: s2m8o+"n.m8er""-/""0oid &, 'search :: s2m8o+""-/""n.m8er The data de)inition re)ers to the concept o) I-T#RFAC#! which is a )unction that consumes a )inite number o) s$mbols and produces )unctions with di))erent t$pes in return, Because this .ind o) )unction is radicall$ di))erent )rom what we ha+e seen be)ore! we use a di))erent name, -ow it is possible to write a contract and a purpose statement:
66"ser0ice-manager":"address-8oo66"to"manage"addition"to<"and"searches"in<"the"address"8oo-" !define"!ser0ice-manager"msg#"...#

To de)ine the )unction! we distinguish the two cases, In the case o) 'add! it is ob+ious what we produce: add-to-address-8oo-, In the case o) 'search! we need a )unction that consumes a s$mbol and then applies +oo-.p to this s$mbol and the locall$ de)ined address-8oo-, Asing lambda! we can create such a )unction on the )l$:
!lambda"!name#" ""!+oo-.p"name"address-8oo-##

Since the )unction is a +alue! it is the natural answer to 'search,

ser+ice2manager00 Figure 11$' Managing multiple address boo.s

66"ma-e-address-8oo-":"string""-/""address-8oo66"to"create"a"f.nction"that"manages"a++"the"ser0ices"for"a"hidden address"8oo!define"!ma-e-address-8oo-"tit+e# ""!local"!!define-struct"entr2"!name"n.m8er## ""66"address-8oo-":"!listof"!+ist"name"n.m8er## ""66"to"maintain"a"+ist"of"name-phone"n.m8er"associations ""!define"address-8oo-"empt2# "" """"""""""66"add-to-address-8oo-":"s2m8o+"n.m8er"0oid ""66"effect:"to"add"a"name-phone"n.m8er"association"to address-8oo""""""""""!define"!add-to-address-8oo-"name"phone# """"""""""""!set!"address-8oo-"!cons"!ma-e-entr2"name"phone# address-8oo-### "" """"""""""66"+oo-.p":"s2m8o+"!listof"!+ist"s2m8o+"n.m8er##""-/" n.m8er"or"fa+se """"""""""66"to"+oo-.p"the"phone"n.m8er"for"name"in"address-8oo""""""""""!define"!+oo-.p"name"a8# """"""""""""!cond """"""""""""""9!empt2A"a8#"fa+se: """"""""""""""9else"!cond """"""""""""""""""""""9!s2m8o+&A"!entr2-name"!first"a8##"name# """""""!entr2-n.m8er"!first"a8##: """"""""""""""""""""""9else"!+oo-.p"name"!rest"a8##:#:## """""""""" """"""""""66"ser0ice-manager":"address-8oo-"o8Sect """"""""""66"to"manage"addition"to<"and"searches"in<"the"address 8oo-" """"""""""!define"!ser0ice-manager"msg# """"""""""""!cond """"""""""""""9!s2m8o+&A"msg"'add# """""""add-to-address-8oo-: """"""""""""""9!s2m8o+&A"msg"'search# """""""!lambda"!name# "!+oo-.p"name"address-8oo-##: """"""""""""""9else"!error"'address-8oo-"1message"not .nderstood1#:###

Figure ((7 shows the complete de)inition o) ma-e-address-8oo-, The de)inition is standard b$ now, It consists o) a local2e8pression! which in turn produces the locall$ de)ined ser0ice-manager as the result, There is no need )or an initiali*er because the onl$ state +ariable is immediatel$ initiali*ed and there is no graphical +iew, To use an address boo.! we )irst create it with ma-e-address-8oo-:
66"friends":"an"address"8oo66"to"maintain"an"address"8oo-"for"friends" !define"friends ""!ma-e-address-8oo-"1>riends"of"7har+es1## 66"8.siness":"an"address"8oo66"to"maintain"an"address"8oo-"for"8.siness"co++eag.es !define"8.siness ""!ma-e-address-8oo-"17o++eag.es"Y"Qice<"Inc.1##

The two de)initions create two distinct address boo.s! one )or a collection o) )riends and a second one )or business ac?uaintances, Second! we add names and phone numbers to the address boo.! or we retrie+e numbers as desired:
/"!!friends"'add#"'(i++"2# /"!!friends"'add#"'Ca++2"3# /"!!friends"'add#"'Da0e"4# /"!!8.siness"'add#"'5mi+"5# /"!!8.siness"'add#"'>a2e"1$#

In this case! we added three entries to the address boo. named friends and two to the one called 8.siness, An addition to! sa$! friends wor.s in two steps, The )irst step is to appl$ friends to 'add, This $ields the /hidden0 )unction add-to-address-8oo-, The second step is to appl$ this resulting )unction to a name and a number, In a similar +ein! loo.ing up a phone number also wor.s in two steps, The application o)! sa$! friends to 'search $ields a )unction that consumes a name, This )unction is then applied to a s$mbol:
/"!!friends"'search#"'(i++# 2 /"!!8.siness"'search#"'(i++# fa+se

The two applications show that the number )or '(i++ in friends is 2 and that there is no number )or '(i++ in colleagues, According to the abo+e additions! thatCs e8actl$ what we should e8pect, @) course! we could also co2mingle the two actions in the Interactions window! adding and searching )or phone numbers at will, E ercise !-<1<&< De+elop an inter)ace de)inition )or the results o) the re+ised +ersion o) ma-e-traffic-+ight /see )igure ((60, Solution E ercise !-<1<(< Show the top2le+el de)initions that the e+aluation o) friends and co++eag.es creates, 1hat is the state o) these de)initions a)ter the )i+e 'add e8pressions ha+e been e+aluatedH #+aluate !!friends"'search#"'(i++# in this conte8t, Solution E ercise !-<1<)< Design g.i-for-address-8oo-, The )unction consumes a list o) strings and creates a new address boo. )or each one o) them, It also creates and displa$s a graphical user inter)ace )or an address boo. with a choice menu that lets users choose to which address boo. the$ want to add an entr$ and in which address boo. the program should search )or a number, Solution

(6#" Practice !ith Encapsulation


E ercise !-<2<1< De+elop the program ma-e-cit2, It manages a collection o) tra))ic lights, The program should pro+ide )our ser+ices: (, adding a tra))ic light with a label /string0E &, remo+ing a tra))ic light b$ labelE 5, switching the state o) a tra))ic light with some gi+en labelE and 6, resetting a tra))ic light to red with some gi+en label, >int' The )irst two ser+ices are pro+ided directl$E the last two are implemented b$ the simulated tra))ic lights, A)ter the de+elopment o) the program is completed! de+elop a graphical user inter)ace, Solution E ercise !-<2<2< De+elop ma-e-master, The program consumes nothing! creates an instance o) the color2guessing game o) section 5;,(! and produces the master-chec)unction as the onl$ result, A)ter the pla$er has guessed the answer! the )unction should simpl$ respond with DDgame o+er,CC A t$pical dialog would proceed as )ollows:
/"!define"master1"!ma-e-master## /"!master-chec-"'red"'red# 'Jothing7orrect /"!master-chec-"'8+ac-"'pin-# 'Nne7o+orNcc.rs ..."

Compare this with the )irst dialogue in section 5;,(, Add a ser+ice to ma-e-master that re+eals the hidden colors, That wa$ a pla$er who is tired o) pla$ing the game can )ind out the answer, Solution E ercise !-<2<!< De+elop ma-e-hangman, The program consumes a list o) words! creates a hangman game using the list! and produces the hangman-g.ess )unction as a result, A pla$er would use the dialogue as )ollows:
/"!define"hangman-eas2"!ma-e-hangman"!+ist"'a"'an"'and"'a8+e 'ad+er###

/"!define"hangman-diffic.+t"!ma-e-hangman"!+ist"'ard0ar-"...### /"!hangman-eas2"'a# 1Io."won1 /"!hangman-diffic.+t"'a# !+ist"'head"!+ist"'V"'V"'V"'V"'V"'V## /"..."

Compare this with the )irst dialogue in section 5;,&, Add a ser+ice to ma-e-master that re+eals the chosen word, An optional e8tension is to e?uip the program with a graphical user inter)ace and a graphical +iew o) the stic. )igure, Reuse e8isting solutions as much as possible, Solution E ercise !-<2<#< De+elop ma-e-p+a2er, The program abstracts o+er the )unctions o) section 5;,7, Asing the program! we can create se+eral pla$ers that wander through the campus:
!define"p+a2er1"!ma-e-p+a2er"'(io5ngineering## !define"p+a2er2"!ma-e-p+a2er"'H.dd(.i+ding## ...

The argument to ma-e-p+a2er speci)ies the initial position o) the pla$er, #ach instance should be able to produce (, a picture o) the current surroundingsE &, a list o) the a+ailable building connectionsE and 5, a mo+e )rom one place to another through an a+ailable connection, E tension: Two pla$ers ma$ be in the same building at the same time! but the$ cannot interact, #8tend the game so that two pla$ers in the same building can interact in some )orm, Solution E ercise !-<2<$< De+elop the program mo0ing-pict.res, It consumes a position and a picture! that is! a list o) shapes as de)ined in sections 9,9! and ;,6! and (',5, /Also see &(,6 )or )unctions on mo+ing pictures,0 It supports two ser+ices, First! it can place the shape at a speci)ic position, Second! it can reset the picture to the initiall$ gi+en position, Solution

Section #. /utable Structures


#ncapsulating and managing state +ariables is similar to )orming and managing structures, 1hen we )irst appl$ a )unction that abstracts o+er state +ariables we pro+ide initial +alues )or some o) the +ariables, The ser+ice manager ser+es the /current0 +alue o) these +ariables! which is similar to e8tracting the +alues o) )ields in structures, -ot surprisingl$ then! the techni?ue can simulate the constructors and selectors o) a definestruct de)inition, This simulation naturall$ suggests the introduction o) )unctions that modi)$ the +alue in a structureCs )ield, The )ollowing subsections spell out the details behind this ideaE the last subsection generali*es it to +ectors,

)8#$ Structures from +unctions


!define-struct"posn"!* 2## !define"!f-ma-e-posn"*%"2%# ""!local"!!define"*"2%# ""!define"2"2%# ""!define"!ser0ice-manager msg# """"!cond """"""9!s2m8o+&A"msg"'*#"*: """"""9!s2m8o+&A"msg"'2#"2: """"""9else"!error"'posn 1...1#:### """"ser0ice-manager## !define"!f-posn-*"p# ""!p"'*## !define"!f-posn-2"p# ""!p"'2##

Figure 11&' A )unctional analog o) posn Ta.e a loo. at )igure ((9, The le)t2hand side is the one2line de)inition o) a posn structure, The right2hand side is a )unctional de)inition that pro+ides almost all the same ser+ices, In particular! the de)inition pro+ides a constructor that consumes two +alues and constructs a compound +alue! and two selectors )or e8tracting the +alues that went into the construction o) a compound +alue, To understand wh$ f-ma-e-posn is a constructor and wh$ f-posn-* and f-posn-2 are selectors! we can discuss how the$ wor.! and we can con)irm that the$ +alidate the e8pected e?uations, Here we do both! because the de)initions are unusual,

The de)inition o) f-ma-e-posn encapsulates two +ariable de)initions and one )unction de)inition, The two +ariables stand )or the arguments o) f-ma-e-posn and the )unction is a ser+ice managerE it produces the +alue o) * when gi+en '* and the +alue o) 2 when gi+en '2, In the preceding section! we might ha+e written something li.e
!define"a-posn"!f-ma-e-posn"3"4## !+"!a-posn"'*#"!a-posn"'2##

to de)ine and to compute with f-ma-e-posn, Since selecting +alues is such a )re?uent operation! )igure ((9 introduces the )unctions f-posn-* and f-posn-2! which per)orm these computations, 1hen we )irst introduced structures rigorousl$ in interme**o (! we said that the selectors and constructors can be described with e?uations, For a de)inition such as that )or posn! the two rele+ant e?uations are:
""!posn-*"!ma-e-posn"W-1"W-2##" &"W-1 and ""!posn-2"!ma-e-posn"W-1"W-2##" &"W-2

where W-1 and W-2 are arbitrar$ +alues, To con)irm that f-posn-* and f-ma-e-posn are in the same relationship as posn-* and ma-e-posn! we can +alidate that the$ satis)$ the )irst e?uation:
""!f-posn-*"!f-ma-e-posn"3"4## &"!f-posn-*"!local"!!define"*"3# """"!define"2"4# """"!define"!ser0ice-manager"msg# """"""!cond 9!s2m8o+&A"msg"'*#"*: 9!s2m8o+&A"msg"'2#"2: 9else"!error"'posn"1...1#:### """"ser0ice-manager## &"!f-posn-*"ser0ice-manager# ""66"add"to"top-+e0e+"definitions: ""!define"*"3# ""!define"2"4# ""!define"!ser0ice-manager"msg# """"!cond """"""9!s2m8o+&A"msg"'*#"*: """"""9!s2m8o+&A"msg"'2#"2: """"""9else"!error"'posn"1...1#:## &"!ser0ice-manager"'*# &"!cond """"9!s2m8o+&A"'*"'*#"*: """"9!s2m8o+&A"'*"'2#"2: """"9else"!error"'posn"1...1#:# &"* &"3

It is an e8ercise to show that f-posn-2 and f-ma-e-posn satis)$ the analogous e?uation, E ercise #.<1<1< 1hich )unction does the simulation o) structures not pro+ideH 1h$ notH Solution E ercise #.<1<2< Here is $et another implementation o) posn structures:
!define"!ff-ma-e-posn"*"2# ""!lambda"!se+ect# """"!se+ect"*"2### !define"!ff-posn-*"a-ff-posn# ""!a-ff-posn"!lambda"!*"2#"*### !define"!ff-posn-2"a-ff-posn# ""!a-ff-posn"!lambda"!*"2#"2###

#+aluate !ff-posn-*"!ff-ma-e-posn"W-1"W2## in this conte8t, 1hat does the calculation demonstrateH Solution E ercise #.<1<!< Show how to implement the )ollowing structure de)initions as )unctions: (, !define-struct"mo0ie"!tit+e"prod.cer## &, !define-struct"8o2friend"!name"hair"e2es"phone## 5, !define-struct"cheer+eader"!name"n.m8er## 6, !define-struct"7D"!artist"tit+e"price## 7, !define-struct"sweater"!materia+"si@e"prod.cer##

Pic. one and demonstrate that the e8pected laws hold,

Solution

)8#" /uta&le +unctional Structures


!define"!fm-ma-e-posn"*%"2%# ""!local"!!define"*"2%# ""!define"2"2%# ""!define"!ser0ice-manager"msg# """"!cond """"""9!s2m8o+&A"msg"'*#"*: """"""9!s2m8o+&A"msg"'2#"2: """"""9!s2m8o+&A"msg"'set-*#"!lambda"!*-new#"!set!"*"*-new##: """"""9!s2m8o+&A"msg"'set-2#"!lambda"!2-new#"!set!"2"2-new##: """"""9else"!error"'posn"1...1#:### """"ser0ice-manager## !define"!fm-posn-*"p# ""!p"'*## !define"!fm-posn-2"p# ""!p"'2## !define"!fm-set-posn-*D"p"new-0a+.e# ""!!p"'set-*#"new-0a+.e## !define"!fm-set-posn-2D"p"new-0a+.e#

//p =set2$0 new2+alue00 Figure 11(' An implementation o) posns with mutators Together! sections 5> and 6',( suggest that structures are mutable, That is! we should be able to change the +alues o) some )ield in a structure, A)ter all! we introduced the ser+ice managers in section 5> to hide state +ariables! not Fust ordinar$ +ariable de)initions, Figure ((; shows how a small change to the de)initions o) )igure ((9 turns the locall$ hidden +ariables into state +ariables, The modi)ied ser+ice manager o))ers two ser+ices per state +ariable: one )or loo.ing up the current +alue and one )or changing it, Consider the )ollowing de)inition and e8pression:
!define"a-posn"!fm-ma-e-posn"3"4## !begin ""!fm-set-posn-*D"a-posn"5# ""!+"!posn-*"a-posn#"$##

#+aluating them b$ hand shows how structures change, Here is the )irst step:
""..." &" ""!define"*-for-a-posn"3# ""!define"2-for-a-posn"4# ""!define"!ser0ice-manager-for-a-posn"msg# """"!cond """"""9!s2m8o+&A"msg"'*#"*-for-a-posn: """"""9!s2m8o+&A"msg"'2#"2-for-a-posn: """"""9!s2m8o+&A"msg"'set-*#

"""""""!lambda"!*-new#"!set!"*-for-a-posn"*-new##: """"""9!s2m8o+&A"msg"'set-2# """""""!lambda"!2-new#"!set!"2-for-a-posn"2-new##: """"""9else"!error"'posn"1...1#:## ""!define"a-posn"ser0ice-manager-for-a-posn# ""!begin """"!fm-set-posn-*D"a-posn"5# """"!+"!posn-*"a-posn#"$##

It renames and li)ts the local de)initions )rom inside o) fm-ma-e-posn, Because the )unction de)inition doesnCt change )or the rest o) the e+aluation! we )ocus on Fust the +ariable de)initions:
""!define"*-for-a-posn"3# ""!define"2-for-a-posn"4# ""!begin """"!fm-set-posn-*D"a-posn"5# """"!+"!posn-*"a-posn#"$## &"!define"*-for-a-posn"3# ""!define"2-for-a-posn"4# ""!begin """"!fm-set-posn-*D"ser0ice-manager-for-a-posn"5# """"!+"!posn-*"a-posn#"$## &"!define"*-for-a-posn"3# ""!define"2-for-a-posn"4# ""!begin """"!!ser0ice-manager-for-a-posn"'set-*#"5# """"!+"!posn-*"a-posn#"$## &"!define"*-for-a-posn"3# ""!define"2-for-a-posn"4# ""!begin """"!set!"*-for-a-posn"5# """"!+"!posn-*"a-posn#"$## &"!define"*-for-a-posn"5# ""!define"2-for-a-posn"4# ""!+"!posn-*"a-posn#"$#"

At this point! the de)inition o) *-for-a-posn has been modi)ied in the e8pected manner, From now on e+er$ re)erence to this state +ariable! which represents the /simulated0 * )ield a-posn! stands )or 5, #+er$ )urther re)erence to *-for-a-posn produces 5, E ercise #.<2<1< De+elop a )unctional representation )or the )ollowing structure de)inition:
!define-struct"8o2friend"!name"hair"e2es"phone##

such that the )ields o) the simulated structure can be changed,

Solution

E ercise #.<2<2< Here is a modi)ication o) the )unction2based implementation o) posn structures in e8ercise 6',(,&:

!define"!ffm-ma-e-posn"*%"2%# ""!local"!!define"*"*%# ""!define"!set-*"new-*#"!set!"*"new-*## ""!define"2"2%# ""!define"!set-2"new-2#"!set!"2"new-2### ""!lambda"!se+ect# """"!se+ect"*"2"set-*"set-2#### !define"!ffm-posn-*"a-ffm-posn# ""!a-ffm-posn"!lambda"!*"2"s*"s2#"*### !define"!ffm-posn-2"a-ffm-posn# ""!a-ffm-posn"!lambda"!*"2"s*"s2#"2### !define"!ffm-set-posn-*D"a-ffm-posn"new-0a+.e# ""!a-ffm-posn"!lambda"!*"2"s*"s2#"!s*"new-0a+.e#### !define"!ffm-set-posn-2D"a-ffm-posn"new-0a+.e# ""!a-ffm-posn"!lambda"!*"2"s*"s2#"!s2"new-0a+.e####

Demonstrate how to modi)$ a structure li.e !ffm-ma-e-posn"3"4# so that its 2 )ield contains 5, Solution

)8#( /uta&le Structures


Scheme structures are mutable, In 'd0anced"Ct.dent Scheme! a structure de)inition such as
!define-struct"posn"!*"2##

introduces si8 primiti+es! not Fust )our: (, ma-e-posn! the constructorE &, posn-* and posn-2! the selectorsE 5, posnA! the predicateE and 6, set-posn-*D and set-posn-2D! the MATAT@RS, The mutators are operations that change the contents o) a structure, Recall that we thin. o) a structure as a bo8 with compartments, For e8ample! the structure
!ma-e-posn"3"4#

should be +isuali*ed as a bo8 with two compartments:

A constructor creates a bo8E a selector e8tracts the +alue )rom a particular compartmentE the predicate recogni*es itE and the mutator changes the content o) a compartment, That is! a mutator has an e))ect on its argumentsE its result is the in+isible +alue, Pictoriall$! we should imagine an e+aluation step )or an e8pression such as
!define"p"!ma-e-posn"3"4## !set-posn-*D"p"5#

as a bo8 with the old * +alue deleted and a new one inserted into the same bo8:

Consider the )ollowing de)initions:


!define-struct"star"!name"instr.ment## !define"p"!ma-e-star"'3hi+7o++ins"'dr.ms##

"etCs consider the e))ect and computation o) the )ollowing e8pression:


!begin ""!set-star-instr.mentD"p"'0oca+s# ""!+ist"!star-instr.ment"p###

According to our e8planation! the )irst sube8pression modi)ies the instr.ment )ield o) the star structure named pE the second one produces a list o) one item! the current +alue the instr.ment )ield in the structure named p, B$ analog$ to section 6',&! the e+aluation proceeds as )ollows:
""!define-struct"star"!name"instr.ment## ""!define"p"!ma-e-star"'3hi+7o++ins"'dr.ms## ""!begin """"!set-star-instr.mentD"p"'0oca+s# """"!+ist"!star-instr.ment"p### &"!define-struct"star"!name"instr.ment## ""!define"p"!ma-e-star"'3hi+7o++ins"'0oca+s## ""!begin """"!0oid# """"!+ist"!star-instr.ment"p### &"!define-struct"star"!name"instr.ment## ""!define"p"!ma-e-star"'3hi+7o++ins"'0oca+s## ""!+ist"'0oca+s#

The )irst step changes one part o) the +alue in the de)inition o) p! but not the entire +alue, The second one e8tracts the current +alue o) the instr.ment )ield and places it in a list,

The introduction o) mutators )or structures re?uires two changes to our s$stem o) e+aluation rules: (, #+er$ constructor e8pression adds a de)inition with a new! uni?ue name to the top le+el! unless it alread$ occurs in a de)inition,;7 &, A name that stands )or a structure is a +alue, 1e can understand these changes i) we thin. o) each structure as a )unction that manages ser+ices such as loo.ing up the current +alue o) a )ield and modi)$ing the )ield, A)ter all! local )unction de)initions also create top2le+el de)initions with uni?ue names, And the names o) )unctions are +alues! too, Asing these two new rules we can stud$ the unusual beha+ior o) mutators in more depth, Here is a )irst e8ample:
!define-struct"star"!name"instr.ment## !define"p"!ma-e-star"'3hi+7o++ins"'dr.ms## !define")"p# !begin ""!set-star-instr.mentD"p"'0oca+s# ""!+ist"!star-instr.ment")###

It di))ers )rom the )irst in two wa$s, First! it de)ines ) to be p, Second! the second sube8pression o) the begin2e8pression re)ers to )! not p, "etCs chec. our understanding o) the e+aluation process:
""!define-struct"star"!name"instr.ment## ""!define"p"!ma-e-star"'3hi+7o++ins"'dr.ms## ""!define")"p# ""!begin """"!set-star-instr.mentD"p"'0oca+s# """"!+ist"!star-instr.ment")### &"!define-struct"star"!name"instr.ment## ""!define"p"!ma-e-star"'3hi+7o++ins"'0oca+s## ""!define")"p# ""!begin """"!0oid# """"!+ist"!star-instr.ment")###

As be)ore! the )irst step changes one part o) the de)inition o) p, The second step is to loo. up )Cs current +alue:
"""... &"!define-struct"star"!name"instr.ment## ""!define"p"!ma-e-star"'3hi+7o++ins"'0oca+s## ""!define")"p# ""!+ist"!star-instr.ment"p##

&"!define-struct"star"!name"instr.ment## ""!define"p"!ma-e-star"'3hi+7o++ins"'0oca+s## ""!define")"p# ""!+ist"'0oca+s#

Because ) is p and the current +alue o) the instr.ment )ield o) p instrument is '0oca+s! the result is again !+ist"'0oca+s#, 1hat we ha+e Fust seen is the e))ect o) SHARI-= /the e))ects o) mutators0! which means that a modi)ication o) a struture a))ects the program in more than one place, Sharing is also +isible inside lists as our second e8ample shows:
!define-struct"star"!name"instr.ment## !define")"!+ist"!ma-e-star"'3hi+7o++ins"'dr.ms### !begin ""!set-star-instr.mentD"!first")#"'0oca+s# ""!+ist"!star-instr.ment"!first")####

Here! the right2hand side o) the de)inition o) ) is an e8pression whose onl$ sube8pression isnCt a +alue, More precisel$! it is a structure e8pression that must be e+aluated:
""..." &"!define-struct"star"!name"instr.ment## ""!define"p"!ma-e-star"'3hi+7o++ins"'dr.ms## ""!define")"!+ist"p## ""!begin """"!set-star-instr.mentD"!first")#"'0oca+s# """"!+ist"!star-instr.ment"!first")#### &"!define-struct"star"!name"instr.ment## ""!define"p"!ma-e-star"'3hi+7o++ins"'dr.ms## ""!define")"!+ist"p## ""!begin """"!set-star-instr.mentD"p"'0oca+s# """"!+ist"!star-instr.ment"!first")####

Thus the )irst step is to introduce a new de)inition! )or which we choose p as the name, The second step replaces !first")# b$ p! because ) is a list o) one item: p, The rest proceeds almost as abo+e:
..." &"!define-struct"star"!name"instr.ment## ""!define"p"!ma-e-star"'3hi+7o++ins"'0oca+s## ""!define")"!+ist"p## ""!begin """"!0oid# """"!+ist"!star-instr.ment"!first")#### &"!define-struct"star"!name"instr.ment## ""!define"p"!ma-e-star"'3hi+7o++ins"'0oca+s## ""!define")"!+ist"p## ""!+ist"!star-instr.ment"p## &"!define-struct"star"!name"instr.ment##

""!define"p"!ma-e-star"'3hi+7o++ins"'0oca+s## ""!define")"!+ist"p## ""!+ist"'0oca+s#

Finall$! e))ects can be shared among items in di))erent lists, Ta.e a loo. at this third +ariant o) our program:
!define-struct"star"!name"instr.ment## !define")"!+ist"!ma-e-star"'3hi+7o++ins"'dr.ms### !define"r"!+ist"!first")#"!star-instr.ment"!first")#### !begin ""!set-star-instr.mentD"!first")#"'0oca+s# ""!+ist"!star-instr.ment"!first"r####

The new de)inition introduces the +ariable r! which stands )or a list that contains two items, "etCs use our new rules to determine the +alues and the e))ects o) this program:
..." &"!define-struct"star"!name"instr.ment## ""!define"p"!ma-e-star"'3hi+7o++ins"'dr.ms## ""!define")"!+ist"p## ""!define"r"!+ist"!first")#"!star-instr.ment"!first")#### ""!begin """"!set-star-instr.mentD"!first")#"'0oca+s# """"!+ist"!star-instr.ment"!first"r#### &"!define-struct"star"!name"instr.ment## ""!define"p"!ma-e-star"'3hi+7o++ins"'dr.ms## ""!define")"!+ist"p## ""!define"r"!+ist"p"!star-instr.ment"p### ""!begin """"!set-star-instr.mentD"!first")#"'0oca+s# """"!+ist"!star-instr.ment"!first"r#### &"!define-struct"star"!name"instr.ment## ""!define"p"!ma-e-star"'3hi+7o++ins"'dr.ms## ""!define")"!+ist"p## ""!define"r"!+ist"p"'dr.ms## ""!begin """"!set-star-instr.mentD"!first")#"'0oca+s# """"!+ist"!star-instr.ment"!first"r####

As abo+e! the )irst step introduces a de)inition )or the new star structure, The second and third step create the list named r! which contains p! the newl$ created structure! and '0oca+s! its current instr.ment +alue, The ne8t step selects the )irst item )rom ) and modi)ies its instr.ment )ield:
..." &"!define-struct"star"!name"instr.ment## ""!define"p"!ma-e-star"'3hi+7o++ins"'0oca+s## ""!define")"!+ist"p## ""!define"r"!+ist"p"'dr.ms## ""!begin """"!0oid#

""""!+ist"!star-instr.ment"!first"r#### &"!define-struct"star"!name"instr.ment## ""!define"p"!ma-e-star"'3hi+7o++ins"'0oca+s## ""!define")"!+ist"p## ""!define"r"!+ist"p"'dr.ms## ""!+ist"!star-instr.ment"p## &"!define-struct"star"!name"instr.ment## ""!define"p"!ma-e-star"'3hi+7o++ins"'0oca+s## ""!define")"!+ist"p## ""!define"r"!+ist"p"'dr.ms## ""!+ist"'0oca+s#

Because r contains p as the )irst item and because the instrument )ield o) p is still '0oca+s! the result is !+ist"'0oca+s# here! too, But! this program still has some .nowledge o) 'dr.ms! the original +alue o) the star structure, In summar$! mutators gi+e us more power than constructors and selectors, Instead o) Fust creating new structures and re+ealing their contents! we can now change their contents! while the structures remain the same, -e8t we must contemplate what this means )or the design o) programs, E ercise #.<!<1< -ame the mutators that the )ollowing structure de)initions introduce: (, !define-struct"mo0ie"!tit+e"prod.cer## &, !define-struct"8o2friend"!name"hair"e2es"phone## 5, !define-struct"cheer+eader"!name"n.m8er## 6, !define-struct"7D"!artist"tit+e"price##

7, !define-struct"sweater"!materia+"si@e"prod.cer##

Solution

E ercise #.<!<2< De+elop the )unction swap-posn! which consumes a posn structure and swaps the +alues in the two )ields, Its result is !0oid#, Solution E ercise #.<!<!< De+elop the )unction one-more-date! which consumes a gir+friends structure and increases the contents o) the n.m8er-past-dates )ield b$ 1, The structure de)inition is
!define-struct"gir+friends"!name"hair"e2es"n.m8er-past-dates##

The result o) one-more-date is !0oid#,

Solution

E ercise #.<!<#< #+aluate the )ollowing program! step b$ step:


!define-struct"cheer+eader"!name"n.m8er## !define"'"!ma-e-cheer+eader"'To'nn"2## !define"("!ma-e-cheer+eader"'(e++e"1## !define"7"!ma-e-cheer+eader"'\riss2"1##" !define"a++"!+ist"'"("7## !+ist ""!cheer+eader-n.m8er"!second"a++## ""!begin """"!set-cheer+eader-n.m8erD"!second"a++#"17# """"!cheer+eader-n.m8er"!second"a++####

Anderline in the last program where de)initions di))er )rom the initial program, Solution E ercise #.<!<$< #+aluate the )ollowing program:
!define-struct"7D"!artist"tit+e"price## !define"in-stoc""!+ist """"!!ma-e-7D"'Q.5.H"1Jew"'d0ent.res"in"=i-fi1"%# """""!ma-e-7D"'>rance"1simp+e"Se1"%# """""!ma-e-7D"'7ran8erries"1no"need"to"arg.e1"%#### !begin ""!set-7D-priceD"!first"in-stoc-#"12# ""!set-7D-priceD"!second"in-stoc-#"1,# ""!set-7D-priceD"!third"in-stoc-#"11# ""!+"!7D-price"!first"in-stoc-## """""!7D-price"!second"in-stoc-## """""!7D-price"!third"in-stoc-####

Show e+er$ step,

Solution

)8#) /uta&le 'ectors


Recall )rom interme**o &> that +ectors! li.e structures! are compound +alues, To e8tract a +alue )rom a structure! programs use selector operations, To e8tract a +alue )rom a +ector! programs use natural numbers as indices, Hence )unctions that process +ectors de)er to au8iliar$ )unctions that process +ectors and natural numbers,

-ot surprisingl$! +ectors! li.e structures! are mutable compound +alues, The onl$ mutator )or +ectors is 0ector-setD! a )unction that consumes a +ector! an inde8! and a +alue, Thus! )or e8ample! the )ollowing program e+aluates to '8+an-:
!define"R"!0ector"'a"'8"'c"'d## !begin ""!0ector-setD"R"%"'8+an-# ""!0ector-setD"R"1"'8+an-# ""!0ector-setD"R"2"'8+an-# ""!0ector-setD"R"3"'8+an-# ""!0ector-ref"R"2##

The )our 0ector-setD e8pressions change R so that all o) its )our )ields contain '8+an-, The last e8pression e8tracts the +alue o) one o) the )ields, In general! an e+aluation concerning mutable +ectors proceeds Fust li.e an e+aluation )or mutable structures, In particular! a 0ector e8pression introduces a new de)inition:
""!+ist"!0ector"1"2"3## &"!+ist"0# ""66"add"to"top-+e0e+"definitions:" ""!define"0"!0ector"1"2"3##

The +ariable name 0 is new and uni?ue, Similarl$! a 0ector-setD e8pression modi)ies a part o) a +ector de)inition:
""!set-0ectorD"!0ector"1"2"3#"%"'a# &"!define"0"!0ector"1"2"3## ""!set-0ectorD"0"%"'a# &"!define"0"!0ector"'a"2"3## ""!0oid#

Finall$! e))ects to +ectors are shared Fust li.e e))ects to structures, E ercise #.<#<1< #+aluate the )ollowing program:
!define"R"!0ector"%"%"%"%## !define"I"R# !begin ""!0ector-setD"R"%"2# ""!0ector-setD"I"1"!+"!0ector-ref"I"%#"!0ector-ref"I"1### ""!0ector-ref"I"1##

Show all steps,

Solution

E ercise #.<#<2< De+elop the )unction c+ear! which consumes a +ector with three slots and sets them to %, Solution

E ercise #.<#<!< De+elop the )unction swap! which consumes a +ector with two slots and swaps the +alues in these slots, Solution E ercise #.<#<#< #8tend the board representation o) e8ercise &>,5,(6 with the )unction
66"8oard-f+ipD":"8oard"N"N""-/""8oo+ean 66"to"negate"the"8oard"position"with"indices"i<"S"on"a-8oard !define"!8oard-f+ipD"a-8oard"i"S#"...#

DonCt )orget to de+elop e8amples and tests )or the )unction,

Solution

)8#* Changing 'aria&les2 Changing Structures


Structure mutators and setD2e8pressions are related, Indeed! in section 6',& we e8plained the e))ects o) the )irst with the second, Still! there are also important di))erences that a programmer must understand, "etCs start with the s$nta8:
!set!"?0aria8+e/ ?e*pression/# "set-?str.ct.re-tag/?fie+d/D

A setD2e8pression is an e8pression that consists o) two pieces: a +ariable and an e8pression, The +ariable is )i8edE it is ne+er e+aluated, The e8pression is e+aluated, In contrast! a structure mutator is a )unction, As such! it is a +alue that the program can appl$ /to two arguments0! pass to other )unctions! store inside o) structures! and so on, Structure mutators are created in response to structure de)initions! Fust as structure constructors and selectors, -e8t we must consider le8ical scope issues /see section (<,&0, A setD2e8pression contains a +ariable, For the setD2e8pression to be +alid! this +ariable must be bound, The connection between a setD2e8pressionCs +ariable and its binding occurrence is static and can ne+er be changed, The scope o) a mutator is that o) its corresponding define-struct, Thus! in the )ollowing program
!define-struct"aaa"!**"22## !define"PJI4P5" ""!local"!! """ define-struct""" " aaa"! " ""** """ """## 22""# " """"!ma-e-aaa"'m2"'wor+d### ...

the underlined occurrence o) define-struct has a limited le8ical scope! and its scope is a hole in the scope o) the top2le+el define-struct, A result o) this scoping is that the mutator )or the top2le+el define-struct cannot mutate the structure called PJI4P5, The two mutators are unrelated )unctions that coincidentall$ ha+e the same nameE the rules )or the e+aluation o) local2e8pression dictate that we rename one consistentl$,

To highlight the di))erences in s$nta8 and le8ical scope! ta.e a loo. at the )ollowing two! apparentl$ similar programs:
!define"the-point"!ma-e-posn 3"4## !set!"*"17# !define"the-point"!ma-e-posn 3"4## !set-posn-*D"the-point"17#

The one on the le)t is illegal! because the * in the setD2e8pression is an unbound +ariable, The program on the right is per)ectl$ legalE it re)ers to the )ield * o) a posn structure, The largest di))erence between setD2e8pressions and mutators concerns their semantics, "etCs stud$ two e8amples to understand the di))erences once and )or all, The )irst illustrates how similar loo.ing e8pressions e+aluate in a radicall$ di))erent manner:
!define"the-point"!ma-e-posn 3"4## !set!"the-point"17# !define"the-point"!ma-e-posn 3"4## !set-posn-*D"the-point"17#

The program on the le)t consists o) a de)inition )or the-point and an assignment to the-pointE the one on the right starts with the same de)inition )or the-point )ollowed b$ an application o) the mutator, The e+aluation o) both a))ects the +ariable de)inition but in di))erent wa$s:
!define"the-point"17# !0oid# !define"the-point"!ma-e-posn"17"4## !0oid#

@n the le)t! the-point now stands )or a numberE on the right! it is still a posn structure but with a new +alue in the *2)ield, More generall$! a setD2e8pression changes the +alue on the right2hand side o) a de)inition! and the application o) a mutator changes the +alue o) Fust one )ield in a structure that occurs on the right2hand side o) a de)inition, The second e8ample shows how an application o) mutator e+aluates the arguments! which is not the case )or setD2e8pressions:
!define"the-point"!ma-e-posn 3"4## !define"an-other"!ma-e-posn 12"5## !set!"!cond 9!@eroA"!point-*"thepoint## "the-point: 9else "an-other:# """"""1# !define"the-point"!ma-e-posn 3"4## !define"an-other"!ma-e-posn 12"5## !set-posn-*D ""!cond """"9!@eroA"!point-*"thepoint## """""the-point: """"9else """""an-other:# ""1#

1hereas the program on the le)t is illegal! because a setD2e8pression must contain a )i8ed +ariable in the second position! the one on the right is legitimate, The e+aluation o) the program on the right changes the *2)ield in an-other to 1, Finall$! m.tators are +alues! which means a )unction can consume a mutator and appl$ it:
66"set-to-2":"C-m.tator"C-str.ct.re""-/""0oid 66"to"change"a"fie+d"in"s"to"2"0ia"m.tator

!define"!set-to-2"m.tator"s# ""!m.tator"s"2## !define-struct"888"!@@"ww## !local"!!define"s"!ma-e-posn"3"4## !define"t"!ma-e-888"'a"'8### ""!begin """"!set-to-2"set-posn-*D"s# """"!set-to-2"set-888-wwD"t###

The )unction set-to-2 consumes a mutator and a structure that the mutator can modi)$, The program uses it to change the *2)ield in a posn structure and the ww2)ield in a 888 structure, In contrast! i) we were to appl$ a )unction to a setD2e8pression! it would recei+e !0oid# and nothing else, /i ing setD and Structure /utators: 1hen a program uses both setD2e8pressions and structure mutators! our e+aluation rules )ail )or some cases, Speci)icall$! the$ donCt e8plain sharing properl$, Consider this program )ragment:
!define"the-point"!ma-e-posn"3"4## !define"another-point"the-point# !begin ""!set!"the-point"17# ""!&"!posn-*"another-point#"3##

According to our rules! the two de)initions re)er to the same structure, The second one does so b$ indirection, The setD2e8pression changes what the-point stands )or! but it shouldnCt a))ect the second de)inition, In particular! the program should produce tr.e, I) we were to use our rules in a nai+e manner! we would not be able to +alidate this point, A proper e8planation o) structures must introduce a new de)inition )or e+er$ application o) a structure constructor! including those on the right2hand side o) de)initions in the original program, 1e will place the new de)initions at the beginning o) the se?uence o) de)initions, Furthermore! the +ariable in the new de)inition must be uni?ue so that it cannot occur in a setD2e8pression, 1e will use +ariables such as str.ct-1! str.ct-2! and so on! and agree to use them )or this purpose onl$, These names! and onl$ these names! are +alues, Asing the minor changes to our rules! we can e+aluate the program )ragment properl$:
""!define"the-point"!ma-e-posn"3"4## ""!define"another-point"the-point# ""!begin """"!set!"the-point"17# """"!&"!posn-*"another-point#"3## &"!define"str.ct-1"!ma-e-posn"3"4## ""!define"the-point"str.ct-1# ""66"evaluate!from!here"

""!define"another-point"the-point# ""!begin """"!set!"the-point"17# """"!&"!posn-*"another-point#"3## &"!define"str.ct-1"!ma-e-posn"3"4## ""!define"the-point"str.ct-1# ""!define"another-point"str.ct-1# ""66"evaluate!from!here" ""!begin """"!set!"the-point"17# """"!&"!posn-*"another-point#"3##

At this point! the structure is created! and both o) the original +ariables re)er to the new structure, The rest o) the e+aluation changes the de)inition o) the-point but not another-point:
""... &"!define"str.ct-1"!ma-e-posn"3"4## ""!define"the-point"17# ""!define"another-point"str.ct-1# ""66"evaluate!from!here" ""!begin """"!0oid# """"!&"!posn-*"another-point#"3## &"!define"str.ct-1"!ma-e-posn"3"4## ""!define"the-point"17# ""!define"another-point"str.ct-1# ""66"evaluate!from!here" ""!&"!posn-*"another-point#"3# &"!define"str.ct-1"!ma-e-posn"3"4## ""!define"the-point"17# ""!define"another-point"str.ct-1# ""66"evaluate!from!here" ""!&"3"3#

The )inal result is tr.e! as e8pected, The modi)ied e+aluation rules are a bit more cumbersome than the old ones, But the$ )ull$ e8plain the di))erence between the e))ects o) setD2e8pressions and those o) structure mutation! which! )or programming in modern languages! is an essential concept,

For simplicit$! we use this simple appro8imation, 1hen a program also uses setD2 e8pression! we must rel$ on the re)inement o) interme**o <,5 to understand its beha+ior completel$, Also see the note on this topic on page 7',
;7

Section #1

Designing Functions that Change Structures


Sections 5> and 6' graduall$ introduced the idea o) mutable structures, In the )irst o) the two sections we studied the idea o) changing a locall$ de)ined +ariable through a )unction, In the second one! we discussed how structures could be modi)ied! too, -ow we need to learn when and how to use this new power, The )irst subsection concerns the ?uestion o) wh$ a program should modi)$ a structure, The second re+iews how the e8isting design recipes appl$ when we wish to use mutators, The third one discusses some di))icult cases, The last one is dedicated to the di))erences between set! and structure mutators,

)$#$ Why /utate Structures


1hene+er we appl$ a structure constructor! we create a new structure, @n some occasions! this is trul$ what we want, Consider a )unction that consumes a list o) personnel records and produces a list o) phone boo. entries, The personnel records ma$ contain in)ormation about a personCs address! including the phone number! date o) birth! marital status! closest relati+es! and salar$ le+el, The entr$ )or the phone boo. should contain the name and the phone number and nothing else, This .ind o) program should de)initel$ generate a new structure )rom each structure in the gi+en list, @n other occasions! though! creating a new structure doesnCt correspond to our intuition, Suppose we wish to gi+e someone a raise, The onl$ wa$ o) accomplishing this at the moment is to create a new personnel record that contains all the old in)ormation and the new salar$ in)ormation, @r! suppose someone has mo+ed and recei+ed a new phone number! and we wish to update the phone boo. on our PDA, Just li.e the program that changes a personCs salar$ le+el! the program that updates the phone boo. would create a new phone boo. entr$, In realit$! howe+er! we would not create a new personnel record or a new entr$ in the phone boo., 1e would instead correct the e8isting personnel record and the e8isting entr$ in our phone boo., A program should be able to per)orm the same .ind o) correcti+e action and! with mutators! we can indeed de+elop such programs, Roughl$ spea.ing! the e8amples suggest two cases, First! i) a structure corresponds to a ph$sical obFect and the computation corresponds to a correcti+e action! the program ma$ mutate the structure, Second! i) a structure does not correspond to a ph$sical obFect or i) the computation creates a new .ind o) +alue )rom e8isting in)ormation! the program should create a new structure, These two rules are not clear2cut, 1e will o)ten encounter situations where both solutions are )easible, In that case! we must consider an ease2o)2 programming argument, I) one o) the two solutions is easier to design 22 o)ten the

creation o) a new structure! choose it, I) the decision leads to a per)ormance bottlenec. 22 and onl$ then! restructure it,

)$#" Structural Design Recipes and /utation2 Part $


Surprisingl$! programming with mutators does not re?uire an$ new design recipes 22 as long as the mutated )ields alwa$s contain atomic +alues, @ur receipes wor. per)ectl$ )ine, 1hile the design o) non2mutating programs re?uires the combination o) +alues! programming with mutators re?uires the combination o) e))ects, Hence the .e$ is to add a well2)ormulated e))ect statement to a )unctionCs contract and to ma.e up e8amples that illustrate the e))ects, 1e practiced both o) these acti+ities )or set! e8pressions alread$ in section 59, In this section we learn to adapt the design recipes and e))ect statements to structural mutations, To do that! we consider a short series o) e8amples, #ach illustrates how an applicable design recipe helps with the design o) structure2modi)$ing or +ector2 modi)$ing )unctions, The )irst e8ample concerns the mutation o) plain structures, Suppose we are gi+en a structure and a data de)inition )or personnel records:
!define-struct"personne+"!name"address"sa+ar2## 66"'"personne+"record"!/0#"is"a"str.ct.re:" 66"!ma-e-personne+"n"a"s# 66"where"n"is"a"s2m8o+<"a"is"a"string<"and"s"is"a"n.m8er."

A )unction that consumes such a record is based on the )ollowing template:


!define"!f.n-for-personne+"pr# ""..."!personne+-name"pr#"... ""..."!personne+-address"pr#"... ""..."!personne+-sa+ar2"pr#"...#""

Consider a )unction )or increasing the salar$ )ield:


66"increase-sa+ar2":"3Q"n.m8er""-/""0oid 66"effect:"to"modif2"the"sa+ar2"fie+d"of"a-pr"82"adding"a-raise !define"!increase-sa+ar2"a-pr"a-raise#"...#

The contract speci)ies that the )unction consumes a 3Q and a number, The purpose statement is an e))ect statement! which e8plains how the argument o) increase-sa+ar2 is modi)ied, De+eloping e8amples )or increase-sa+ar2 re?uires the techni?ues o) section 59, Speci)ciall$! we must be able to compare the be)ore and a)ter state o) some 3Q structure:
!local"!!define"pr1"!ma-e-personne+"'(o8"'3itts8.rgh"7%%%%### ""!begin """"!increase-sa+ar2"pr1"1%%%%# """"!&"!personne+-sa+ar2"pr1#"$%%%%###

The result o) the e8pression is tr.e i)! and onl$ i)! increase-sa+ar2 wor.s properl$ )or this e8ample, 1e can now use the template and the e8ample to de)ine the )unction:
66"increase-sa+ar2":"3Q"n.m8er""-/""0oid 66"effect:"to"modif2"the"sa+ar2"fie+d"of"a-pr"82"adding"in"a-raise !define"!increase-sa+ar2"a-pr"a-raise# ""!set-personne+-sa+ar2D"a-pr"!+"!personne+-sa+ar2"a-pr#"araise###

As usual! the )ull de)inition uses onl$ one o) se+eral sube8pressions )rom the template! but the template reminds us o) what in)ormation we can use: the arguments and their piecesE and what parts we can modi)$: the )ields )or which we ha+e selectors, E ercise #1<2<1< Ma.e up e8amples )or increase-sa+ar2 and test the )unction, Formulate the tests as boolean2+alued e8pressions, Solution E ercise #1<2<2< Adapt increase-sa+ar2 such that it accepts onl$ +alues )or a-raise between 5R and ;R o) the salar$, It calls error otherwise, Solution E ercise #1<2<!< De+elop increase-percentage, The )unction consumes a 3Q and a percentage between 5R and ;R, It increases the +alue in the salar$ )ield o) the 3Q b$ the lesser o) the percentage increase or 7%%%, Solution E ercise #1<2<#< De+elop the )unction new-date, It consumes a cheer+eader record and adds a date to the beginning o) a list, Here are the rele+ant de)initions:
!define-struct"cheer+eader"!name"dates## 66"'"cheerleader"is"a"str.ct.re:" 66"!ma-e-cheer+eader"n"d# 66"where"n"is"a"s2m8o+"and"d"is"a"+ist"of"s2m8o+s."

For e8ample! !ma-e-cheer+eader"'To'nn"'!7ar+"(o8"D.de"'dam"5mi+## is a +alid cheer+eader record, De+elop an e8ample that shows what it means to add '>ran- as a date, Solution E ercise #1<2<$< Recall the structure de)initions )or squares:
!define-struct"square"!nw"length##

The matching data de)inition speci)ies that the nw )ield is alwa$s a posn structure and that length is a number: A s& are is a structure:

!ma-e-s).are"p"s#

where p is a posn and s is a number, De+elop the )unction mo0e-s).areD, It consumes a s?uare! called s)! and a number! called de+ta, It modi)ies s) b$ adding de+ta to its + coordinate, "oo. up the structure and data de)inition )or circles and de+elop the )unction mo0ecirc+e! which is analogous to mo0e-s).are, Solution The second e8ample recalls the design recipe )or )unctions that wor. on unions o) classes, @ne o) our )irst e8amples o) this .ind concerned the class o) geometric shapes, Here is the rele+ant data de)inition: A shape is either (, a circ+e! or &, a square, See e8ercise 6(,&,7 or part I )or the de)initions o) circ+e and square, Following our recipe! a template )or shape2processing )unctions consists o) a two2 clause cond2e8pression:
!define"!f.n-for-shape"a-shape# ""!cond """"9!circ+eA"a-shape#"..."!f.n-for-circ+e"a-shape#"...: """"9!s).areA"a-shape#"..."!f.n-for-s).are"a-shape#"...:##

#ach cond2clause re)ers to a )unction with the same purpose )or the matching .ind o) shape, So! suppose we wish to mo+e a shape in the + direction b$ a )i8ed number o) pi8els, In part I! we created a new structure )or this purpose, -ow we can use the mutators )or circ+e and square structures instead 22 that is! the )unction can ha+e an e))ect:
66"mo0e-shapeD":"shape"n.m8er""-/""0oid 66"effect:"to"mo0e"a-shape"in"the"+"direction"82"de+ta"pi*e+s !define"!mo0e-shapeD"a-shape# ""!cond """"9!circ+eA"a-shape#"!mo0e-circ+e"a-shape"de+ta#: """"9!s).areA"a-shape#"!mo0e-s).are"a-shape"de+ta#:##

The )unctions mo0e-circ+e and mo0e-s).are are the subFect o) e8ecise 6(,&,7 because the$ consume and a))ect plain structures, E ercise #1<2<&< Ma.e up e8amples )or mo0e-shapeD and test the )unction, Formulate the tests as boolean2+alued e8pressionsL Solution E ercise #1<2<(< The )ollowing structure de)initions are to represent items that a music store sells:
!define-struct"7D"!price"tit+e"artist## !define-struct"record"!price"anti).e"tit+e"artist## !define-struct"DWD"!price"tit+e"artist"to-appear## !define-struct"tape"!price"tit+e"artist##

Pro+ide a data de)inition )or the class o) m sic items! which comprises cds! records! d0ds! and tapes, The price must be a number in each case, De+elop the program inf+ateD! which consumes a m.sic-item and a percentage, Its e))ect is to increase the price in the gi+en structure according to the percentage, Solution E ercise #1<2<)< De+elop a program that .eeps trac. o) the )eeding o) *oo animals, @ur *oo has three .inds o) animals: elephants! mon.e$s! and spiders, #ach animal has a name and two )eeding times per da$: morning and e+ening, Initiall$ a structure that represents an animal /structure0 contains fa+se in the )ields )or )eeding times, The program feed-anima+ should consume a structure that represents an animal and the name o) a )eeding time, It should switch the corresponding )ield in the animal structure to tr.e, Solution The ne8t two e8amples are about mutations when the underl$ing data de)initions in+ol+e sel)2re)erences, Sel)2re)erences are needed i) we wish to deal with data that has no si*e limit, "ists were the )irst class o) such data we encountered and natural numbers the second one, "etCs )irst ta.e a loo. at mutation o) lists o) structures! using the running data e8ample o) this part: the address boo., An address boo. is a list o) entriesE )or completeness! here are the structure and data de)initions:
!define-struct"entr2"!name"n.m8er##

An entry is a structure:
!ma-e-entr2"n"p#

where n is a s$mbol and p is a number,

An address-boo$ is (, the empt$ list! empt2! or &, !cons"an-e"an-a8# where an-e is an entr$ and an-a8 is an address boo., @nl$ the second one is sel)2re)erential! so we )ocus on the template )or it:
66"f.n-for-a8":"address-8oo-""-/""RI] !define"!f.n-for-a8"a8# ""!cond """"9!empt2A"a8#"...: """"9else"..."!f.n-for-entr2"!first"a8##"..."!f.n-for-a8"!rest a8##"...:##

I) we needed an au8iliar$ )unction )or processing an entr2! we might also wish to write out the template )or structure2processing )unctions, So suppose we want a )unction that updates an e8isting entr$, The )unction consumes an address-8oo-! a name! and a phone number, The )irst entr2 that contains the name is modi)ied to contain the new phone number:
66"change-n.m8erD":"s2m8o+"n.m8er"address-8oo-""-/""0oid 66"effect:"to"modif2"the"first"entr2"for"name"in"a8"so"that"its 66"n.m8er"fie+d"is"phone !define"!change-n.m8erD"name"phone"a8#"...#

It is Fusti)ied to de+elop this )unction with mutators because Fust as in realit$! most o) the address boo. sta$s the same while one entr$ is changed, Here is an e8ample:
!define"a8 ""!+ist """"!ma-e-entr2"''dam"1# """"!ma-e-entr2"'7hris"3# """"!ma-e-entr2"'50e"2### !begin ""!change-n.m8erD"'7hris"17"a8# ""!&"!entr2-n.m8er"!second"a8##"17##

The de)inition introduces a8! an address-8oo- with three items, The begin2e8pression )irst changes a8 b$ associating '7hris with 17E then it compares the phone number o) the second item on a8 with 17, I) change-n.m8erD )unctions properl$! the result o) the begin2e8pression is tr.e, An e+en better test would ensure that nothing else in a8 changes,

The ne8t step is to de+elop the )unction de)inition! using the template and the e8amples, "etCs consider each case separatel$: (, I) a8 is empt$! name doesnCt occur in it, An)ortunatel$! the purpose statement doesnCt speci)$ what the )unction should compute in this case! and there is indeed nothing sensible the )unction can do, To be sa)e! we use error to signal that no matching entr$ was )ound, &, I) a8 contains a )irst entr2! it might or might not contain name, To )ind out! the )unction must distinguish the two cases with a cond2e8pression:
3. !cond 4. ""9!s2m8o+&A"!entr2-name"!first"a8##"name#"...: 5. ""9else"...:#

In the )irst subcase! the )unction must modi)$ the structure, In the second! name can occur onl$ in !rest"a8#! which means the )unction must mutate some entr2 in the rest o) the list, Fortunatel$! the natural recursion accomplishes Fust that, Putting e+er$thing together! we get the )ollowing de)inition:
!define"!change-n.m8erD"name"phone"a8# ""!cond """"9!empt2A"a8#"!error"'change-n.m8erD"1name"not"in"+ist1#: """"9else"!cond """"""""""""9!s2m8o+&A"!entr2-name"!first"a8##"name# """""""""""""!set-entr2-n.m8erD"!first"a8#"phone#: """"""""""""9else" """""""""""""!change-n.m8erD"name"phone"!rest"a8##:#:##

The onl$ uni?ue aspect o) this )unction is that it uses a structure mutator in one o) the cases, @therwise it has the )amiliar recursi+e shape: a cond with two clauses and a natural recursion, It is especiall$ instructi+e to compare the )unction with containsdo++A )rom section >,5 and containsA )rom e8ercise >,5,5, E ercise #1<2<-< De)ine test-change-n.m8er, The )unction consumes a name! a phone number! and an address boo., It uses change-n.m8erD to update the address boo.! and then ensures that it was changed properl$, I) so! it produces tr.eE i) not! it produces an error message, Ase this new )unction to test change-n.m8erD with at least three di))erent e8amples, Solution E ercise #1<2<1.< De+elop mo0e-s).ares, It consumes a list o) squares! as de)ined abo+e! and a number de+ta, The )unction modi)ies each on the list b$ adding de+ta to the +2component o) its position, Solution

E ercise #1<2<11< De+elop the )unction a++-fed, It consumes a list o) anima+s! as de)ined in e8ercise 6(,&,<! and modi)ies them so that their )ield )or morning )eedings is switched to tr.e, Solution E ercise #1<2<12< De+elop the )unction for-a++! which abstracts mo0e-s).ares and a++-fed )rom e8ercises 6(,&,(' and 6(,&,((, It consumes two +alues: a )unction that consumes structures and produces !0oid#E and a list o) structures, Its result is !0oid#, Solution E ercise #1<2<1!< De+elop the )unction ft-descendants, It consumes a descendant )amil$ tree /see section (7,(0 based on the )ollowing structure de)inition:
!define-struct"parent"!chi+dren"name"date"e2es"no-descendants##

The last )ield in a parent structure is originall$ %, The )unction ft-descendants tra+erses the tree and modi)ies these slots so that the$ contain the total number o) descendants o) the corresponding )amil$ member, Its result is the number o) total descendants o) the gi+en tree, Solution -atural numbers ma.e up another class o) +alues that re?uires a sel)2re)erential description, Recursion on natural numbers per se isnCt use)ul in conFunction with mutation! but recursion on natural numbers as indices into +ectors is use)ul when a problemCs data representation in+ol+es +ectors, "etCs start with a snippet o) an ele+ator control program, An ele+ator control program must .now at which )loor people ha+e pressed the call buttons, 1e assume that the ele+ator hardware can mutate some status +ector o) booleans, That is! we assume that the program contains a +ector! call it ca++-stat.s! and that a )ield in ca++-stat.s is tr.e i) someone has pushed the call button at the corresponding )loor, @ne important ele+ator operation is to reset all the buttons, For e8ample! an operator ma$ ha+e to restart the ele+ator a)ter it has been out o) ser+ice )or a while, 1e start the de+elopment o) reset b$ restating the .nown )acts in a Scheme outline:;9
66"ca++-stat.s":"!vectorof"8oo+ean# 66"to"-eep"trac-"of"the"f+oors"from"which"ca++s"ha0e"8een"iss.ed" !define"ca++-stat.s"!0ector"tr.e"tr.e"tr.e"fa+se"tr.e"tr.e"tr.e fa+se## 66"reset":""-/""0oid 66"effect:"to"set"a++"fie+ds"in"ca++-stat.s"to"fa+se !define"!reset#"...#

The )irst de)inition speci)ies ca++-stat.s as a state +ariable! but o) course we use each slot in the +ector as a state +alue! not the entire +ariable, The second part consists o) three pieces: a contract! an e))ect statement! and a header )or the )unction reset! which implements the in)ormall$ speci)ied ser+ice,

1hile it is possible to implement the ser+ice as


!define"!reset# ""!set!"ca++-stat.s """"!8.i+d-0ector"!0ector-+ength"ca++-stat.s#"!lambda"!i# fa+se####

this tri+ial solution is clearl$ not what we want because it creates a new +ector, Instead! we want a )unction that modi)ies each )ield o) the e8isting +ector, Following the suggestions o) interme**o 7! we de+elop an au8iliar$ )unction with the )ollowing template:
66"reset-a.*":"!vectorof"8oo+ean#"N""-/""0oid 66"effect:"to"set"the"fie+ds"of"0"with"inde*"in"9%<"i#"to"fa+se !define"!reset-a.*"0"i#" ""!cond """"9!@eroA"i#"...: """"9else"..."!reset-a.*"0"!s.81"i##"...:##

That is! the au8iliar$ )unction consumes not onl$ the +ector but also an inter+al bound, The shape o) the template is based on the data de)inition o) the latter, The e))ect statement suggests the )ollowing e8amples: (, !reset-a.*"ca++-stat.s"%# lea+es ca++-stat.s unchanged! because the purpose statement sa$s to change all indices in V%!%0 and there are noneE &, !reset-a.*"1# changes ca++-stat.s so that !0ector-ref"ca++-stat.s"%# is fa+se! because % is the onl$ natural number in V%! 10E 5, !reset-a.*"ca++-stat.s"!0ector-+ength"ca++-stat.s## sets all )ields o) ca++-stat.s to fa+se, The last e8ample implies that we can de)ine reset with !reset-a.*"ca++-stat.s !0ector-+ength"ca++-stat.s##, #?uipped with e8amples! we can turn our attention to the de)inition, The .e$ is to remember that the additional argument must be interpreted as an inde8 into the +ector, eeping the e8ample and the guideline in mind! letCs loo. at each o) the two cases separatel$: (, I) !@eroA"i# holds! the )unction has no e))ect and produces !0oid#,

&, @therwise i is positi+e, In that case! the natural recursion sets all )ields in ca++stat.s with an inde8 in V'!!s.81"i#0 to fa+se, Furthermore! to complete the tas.! the )unction must set the +ector )ield with inde8 !s.81"i# to fa+se, The combination o) the two e))ects is achie+ed with a begin2e8pression that se?uences the natural recursion and the additional 0ector-setD, Figure ((< puts e+er$thing together, The second clause in the de)inition o) reset-a.* changes the +ector at inde8 !s.81"i# and then uses the natural recursion, Its result is the result o) the begin2e8pression,
66"ca++-stat.s":"!vectorof"8oo+ean# 66"to"-eep"trac-"of"the"f+oors"from"which"ca++s"ha0e"8een"iss.ed" !define"ca++-stat.s"!0ector"tr.e"tr.e"tr.e"fa+se"tr.e"tr.e"tr.e fa+se## 66"reset":""-/""0oid 66"effect:"to"set"a++"fie+ds"in"ca++-stat.s"to"fa+se !define"!reset# ""!reset-a.*"ca++-stat.s"!0ector-+ength"ca++-stat.s### 66"reset-a.*":"!vectorof"8oo+ean#"N""-/""0oid 66"effect:"to"set"the"fie+ds"of"0"with"inde*"in"9%<"i#"to"fa+se !define"!reset-a.*"0"i# ""!cond """"9!@eroA"i#"!0oid#: """"9else"!begin """"!0ector-setD"0"!s.81"i#"fa+se#

/reset2au8 + /sub( i000W00 Figure 11)' Resetting call2buttons )or an ele+ator

E ercise #1<2<1#< Ase the e8amples to de+elop tests )or reset-a.*, Formulate the tests as boolean2+alued e8pressions, Solution E ercise #1<2<1$< De+elop the )ollowing +ariant o) reset:
66"reset-inter0a+":"N"N""-/""0oid 66"effect:"to"set"a++"fie+ds"in"9from<"to:"to"fa+se 66"ass.me:"!?&"from"to#"ho+ds" !define"!reset-inter0a+"from"to#"...#

Ase reset-inter0a+ to de)ine reset,

Solution

E ercise #1<2<1&< Suppose we represent the position o) an obFect with a +ector and the +elocit$ o) an obFect with a second +ector, De+elop the )unction mo0eD! which consumes a position +ector and an e?uall$ long +elocit$ +ector, It modi)ies the position +ector b$ adding in the numbers o) the speed +ector! )ield b$ )ield:
66"mo0eD":"!vectorof"n.m8er#"!vectorof"n.m8er#""-/""0oid 66"effect:"to"add"the"fie+ds"of"0"to"the"corresponding"fie+ds"of pos" 66"

66"ass.mption:"pos"and"0"ha0e"e).a+"+ength !define"!mo0eD"pos"0#"...#

Justi)$ wh$ the use o) a +ector2modi)$ing )unction is appropriate to model the mo+ement o) an obFect, Solution E ercise #1<2<1(< De+elop the )unction 0ec-for-a++! which abstracts reset-a.* and the au8iliar$ +ector2processing )unction )or mo0eD )rom e8ercise 6(,&,(9, It consumes two +alues: a )unction f and a +ector 0ec, The )unction f consumes indices /N0 and +ector items, The result o) 0ec-for-a++ is !0oid#E its e))ect is to appl$ f to each inde8 and corresponding +alue in 0ec:
66"0ec-for-a++":"!N"R""-/""0oid#"!vectorof"R#""-/""0oid 66"effect:"to"app+2"f"to"a++"indices"and"0a+.es"in"0ec 66"e).ation:" 66"!0ec-for-a++"f"!0ector"0-%"..."0-J##" 66"&" 66"!begin"!f"J"0-J#"..."!f"%"0-%#"!0oid## !define"!0ec-for-a++"f"0ec#"...#

Ase 0ec-for-a++ to de)ine 0ector*D! which consumes a number s and a +ector o) numbers and modi)ies the +ector b$ multipl$ing each )ieldCs +alue with s, Solution The last e8ample co+ers the common situation when we wish to compute se+eral numeric +alues at once and place them in a +ector, In section 5; we saw that the use o) e))ects is on occasion use)ul to communicate se+eral results, In the same manner! it is sometimes best to create a +ector and to modi)$ it within the same )unction, Consider the problem o) counting how man$ times each +owel occurs in a list o) letters:
66"co.nt-0owe+s":"!listof"+etter#" 66"""""""""""-/""!0ector"n.m8er"n.m8er"n.m8er"n.m8er"n.m8er# 66"where"a"letter"is"a"s2m8o+"in"'a"..."'@ 66"to"determine"how"man2"times"the"fi0e"0owe+s"occ.r"in"chars 66"the"res.+ting"0ector"+ists"the"co.nts"in"the"+e*icographic order !define"!co.nt-0owe+s"chars#"...#

The choice o) +ector as a result is appropriate because the )unction must combine )i+e +alues into one and each o) the +alues is e?uall$ interesting, Asing the purpose statement! we can also come up with e8amples:
""!co.nt-0owe+s"'!a"8"c"d"e"f"g"h"i## &"!0ector"1"1"1"%"%# ""!co.nt-0owe+s"'!a"a"i".".## &"!0ector"2"%"1"%"2#

=i+en that the input is a list! the natural choice )or the template is that )or a list2 processing )unction:

!define"!co.nt-0owe+s"chars# ""!cond """"9!empt2A"chars#"...: """"9else"..."!first"chars#"..."!co.nt-0owe+s"!rest chars##"...":## 66"co.nt-0owe+s":"!listof"+etter#" 66"""""""""""-/""!0ector"n.m8er"n.m8er"n.m8er"n.m8er"n.m8er# 66"where"a"letter"is"a"s2m8o+"in"'a"..."'@ 66"to"determine"how"man2"times"the"fi0e"0owe+s"occ.r"in"chars 66"the"res.+ting"0ector"+ists"the"co.nts"in"the"+e*icographic order !define"!co.nt-0owe+s"chars# ""!cond """"9!empt2A"chars#"!0ector"%"%"%"%"%#: """"9else """""!local"!!define"co.nt-rest"!co.nt-0owe+s"!rest"chars#### """""""!begin """""""""!co.nt-a-0owe+"!first"chars#"co.nt-rest# """""""""co.nt-rest##:## 66"co.nt-a-0owe+":"+etter"!0ector"n.m8er"n.m8er"n.m8er"n.m8er n.m8er#""-/""0oid 66"effect:"to"modif2"co.nts"at"the"appropriate"p+ace"if"+"is"a 0owe+<" 66"none"otherwise !define"!co.nt-a-0owe+"+"co.nts#"

,,,0 Figure 11-' Counting +owels To )ill the gaps in the template! we consider each o) the two clauses: (, I) !empt2A"chars# is tr.e! the result is a +ector o) )i+e %Cs, A)ter all! there are no +owels in an empt$ list, &, I) chars isnCt empt2! the natural recursion counts how man$ +owels and which ones occur in !rest"chars#, To get the correct result! we also ha+e to chec. whether !first"chars# is a +owel! and depending on the outcome! increase one o) the +ector )ields, Since this .ind o) tas. is a separate! repeated tas.! we lea+e it to an au8iliar$ )unction:
3. 66"co.nt-a-0owe+":"+etter 4. 66""""""!0ector"n.m8er"n.m8er"n.m8er"n.m8er"n.m8er#""-/" 0oid 5. 66"effect:"to"modif2"co.nts"at"the"appropriate"p+ace"if"+"is a"0owe+<" . !define"!co.nt-a-0owe+"+"co.nts#" 7. ""...#

In other words! the second clause )irst counts the +owels in the rest o) the list, This computation is guaranteed to $ield a +ector according to the purpose statement, "etCs call this +ector co.nts, Then! it uses co.nt-a-0owe+ to increase the appropriate )ield in co.nts! i) an$, The result is co.nts! a)ter the )irst letter on the list has been counted,

Figure ((> contains the complete de)inition o) the main )unction, De)ining the au8iliar$ )unction )ollows the recipe )or non2recursi+e structure mutations, E ercise #1<2<1)< De+elop the )unction co.nt-a-0owe+, Then test the complete co.nt-0owe+s program, Solution E ercise #1<2<1-< At the end o) interme**o 7! we could ha+e de)ined co.nt-0owe+s as shown in )igure (&', This +ersion does not use 0ector-setD! but constructs the +ector directl$ using 8.i+d-0ector,
!define"!co.nt-0owe+s-80"chars# ""!local"!!define"!co.nt-0owe+"*"chars# """"""""""""!cond """"""""""""""9!empt2A"chars#"%: """"""""""""""9else"!cond """"""""""""""""""""""9!s2m8o+&A"*"!first"chars## """""""""""""""""""""""!+"!co.nt-0owe+"*"!rest"chars##"1#: """"""""""""""""""""""9else"!co.nt-0owe+"*"!rest"chars##:#:### """"!8.i+d-0ector"5"!lambda"!i#" """"""""""""""""""""""!cond """"""""""""""""""""""""9!&"i"%#"!co.nt-0owe+"'a"chars#: """"""""""""""""""""""""9!&"i"1#"!co.nt-0owe+"'e"chars#: """"""""""""""""""""""""9!&"i"2#"!co.nt-0owe+"'i"chars#: """"""""""""""""""""""""9!&"i"3#"!co.nt-0owe+"'o"chars#:

V/O i 60 /count2+owel =u chars0W00000 Figure 12.' Another wa$ o) counting +owels Measure the per)ormance di))erence between co.nt-0owe+s-80 and co.nt-0owe+s, >int' De)ine a )unction that generates a large list o) random letters /with! sa$! 7!''' or ('!''' items0, #8plain the per)ormance di))erence between co.nt-0owe+s-80 and co.nt-0owe+s, Does the e8planation re)lect the measured di))erenceH 1hat does this suggest concerning the 0ector-setD operationH Solution E ercise #1<2<2.< De+elop histogram, The )unction consumes a list o) grades between ' and (''E it produces a +ector o) si*e ('( where each slot contains the number o) grades at that le+el, Solution E ercise #1<2<21< De+elop co.nt-chi+dren, The )unction consumes a descendant )amil$ tree! which is a )amil$ tree that leads )rom a )amil$ member to the descendants, It produces a +ector with si8 )ields, The )irst )i+e slots contain the number o) )amil$ members that ha+e that man$ childrenE the si8th )ield contains the number o) )amil$ members that ha+e )i+e or more children, Solution

)$#( Structural Design Recipes and /utation2 Part "


In the preceding sections! we studied structure mutation )or )ields that contain atomic data, 1e .now! howe+er! that structures can contain structures, Starting in section (6,(! we e+en encountered sel)2re)erential data de)initions in+ol+ing structures in structures, @n occasion! processing such classes o) data ma$ also re?uire mutations o) structure )ields that contain structures, In this section! we wor. through one such e8ample,

Figure 121' Pla$ing with cards Suppose we wish to simulate a card game as a program, #ach card has two important characteristics: its s it and its ran$, A pla$erCs collection o) cards is called a hand, For now we also assume that e+er$ pla$er has at least one card! that is! a hand is ne+er empt$, Figure (&( contains a screen shot o) DrScheme with structure and data de)initions )or manipulating cards and hands, The program )ragment does not introduce separate classes o) cards and hands! but a single structure and a single data de)inition )or hands, A hand consists o) a hand structure! which contains a ran-! a s.it! and a ne*t )ield,

The data de)inition shows that the ne8t )ield ma$ contain two .inds o) +alues: empt2! which means that there are no other cards! and a hand structure! which contains the remainder o) the cards, From a global perspecti+e! a hand )orms a chain o) cardsE onl$ the last one contains empt2 in the ne*t )ield,;; At )irst! a pla$er has no cards, Pic.ing up the )irst card creates a hand, @thers cards are then inserted into the e8isting hand as needed, This calls )or two )unctions: one )or creating a hand and another one )or inserting a card into a hand, Because a hand e8ists onl$ once and corresponds to a ph$sical obFect! it is natural to thin. o) the second )unction as one that modi)ies an e8isting +alue rather than building a new one, For now! we accept this premise and e8plore its conse?uences, Creating a hand is a simple act and eas$ to implement as a )unction:
66"create-hand":"ran-"s.it""-/""hand 66"to"create"a"sing+e-card"hand"from"r"and"s !define"!create-hand"r"s# ""!ma-e-hand"r"s"empt2##

The )unction consumes the properties o) a cardE it creates a hand with one card and no others,
ran. suit ne8t

/de)ine hand' /create2hand (5 spades00

(5
ran. suit

empt$
ne8t

/add2at2endL diamonds ( hand'0

(5

ran. suit

ne8t

(5

empt$

Figure 122' Building a hand Adding a card to the end o) a hand is a more di))icult tas., To simpli)$ our li)e a bit! letCs sa$ that a pla$er alwa$s adds new cards to the end o) the hand, In this case we must process an arbitraril$ large +alue! which means we need a recursi+e )unction, Here are the contract! e))ect statement! and header:
66"add-at-endD":"ran-"s.it"hand""-/""0oid 66"effect":"to"add"a"card"with"r"as"ran-"and"s"as"s.it"at"the"end" !define"!add-at-endD"ran-"s.it"a-hand#"...#

These speci)ications sa$ that the )unction has the in+isible +alue as the result and that it communicates with the rest o) the program e8clusi+el$ through its e))ects, "etCs start with e8amples:
!define"hand%"!create-hand"13"C3'D5C##

I) we were to e+aluate the )ollowing e8pression


!add-at-endD"1"DI'HNJDC"hand%#

in the conte8t o) this de)inition! hand% becomes a hand with two cards: a spades2(5 )ollowed b$ a diamonds2(, Figure (&& depicts the change o) hand'E the top hal) displa$s the initial state o) hand%! the lower hal) displa$s the state a)ter add-at-endD has added a card, I) we )urthermore e+aluate
!add-at-endD"2"7LP(C"hand%##

in this conte8t! hand% becomes a hand with three cards, The last one is a clubs2&, In terms o) an e+aluation! the de)inition o) hand% should change to
!define"hand%" ""!ma-e-hand"13"C3'D5C """"!ma-e-hand"1"DI'HNJDC """"""!ma-e-hand"2"7LP(C"empt2####

a)ter both additions ha+e been carried out, =i+en that the ran- and s.it argument to add-at-endD are atomic +alues! the template must be based on the data de)inition )or hands:
!define"!add-at-endD"ran-"s.it"a-hand# ""!cond """"9!empt2A"!hand-ne*t"a-hand##" """""..."!hand-ran-"a-hand#"..."!hand-s.it"a-hand#"...: """"9else"..."!hand-ran-"a-hand#"..."!hand-s.it"a-hand#"... """""..."!add-at-endD"ran-"s.it"!hand-ne*t"a-hand##"...:##

The template consists o) two clauses! which chec. the content o) the ne*t )ield o) ahand, It is recursi+e in the second clause! because the data de)inition )or hands is sel)2 re)erential in that clause, In short! the template is completel$ con+entional, The ne8t step is to consider how the )unction should a))ect a-hand in each clause: (, In the )irst case! a-handCs ne*t )ield is empt2, In that case! we can modi)$ the ne*t )ield so that it contains the new card:
2. !set-ne*t-handD"a-hand"!ma-e-hand"ran-"s.it"empt2##

The newl$ created hand structure is now the one that contains empt2 in its ne8t )ield! that is! it is the new end o) the a-hand +alue, 5, In the second case! the natural recursion adds a new card to the end o) a-hand, Indeed! because the gi+en a-hand isnCt the last one in the chain! the natural recursion does e+er$thing that needs to be done,

Here is the complete de)inition o) add-at-endD:


66"add-at-endD":"ran-"s.it"hand""-/""0oid 66"effect:"to"add"a"card"with"0"as"ran-"and"s"as"s.it"at"the"end of"a-hand !define"!add-at-endD"ran-"s.it"a-hand# ""!cond """"9!empt2A"!hand-ne*t"a-hand## """""!set-hand-ne*tD"a-hand""!ma-e-hand"ran-"s.it"empt2##: """"9else"!add-at-endD"ran-"s.it"!hand-ne*t"a-hand##:##

It closel$ resembles the list2processing )unctions we designed in part II, This should come as no surprise! because add-at-endD processes +alues )rom a class that closel$ resembles the data de)inition o) lists and the design recipes are )ormulated in a general manner, E ercise #1<!<1< #+aluate the )ollowing program b$ hand:
!define"hand%"!create-hand"13"C3'D5C## !begin ""!add-at-endD"1"DI'HNJDC"hand%# ""!add-at-endD"2"7LP(C"hand%# ""hand%#

Test the )unction with this e8ample, Ma.e up two other e8amples, Recall that each e8ample consists o) an initial hand! cards to be added! and a prediction o) what the result should be, Then test the )unction with the additional e8amples, Formulate the tests as boolean2+alued e8pressions, Solution E ercise #1<!<2< De+elop the )unction +ast-card, It consumes a hand and produces a list with the last cardCs ran. and suit, How can we use this )unction to test the add-atendD )unctionH Solution E ercise #1<!<!< Suppose a )amil$ tree consists o) structures that record the name! social securit$ number! and parents o) a person, Describing such a tree re?uires a structure de)inition:
!define-struct"chi+d"!name"socia+"father"mother##

and a data de)inition: A fami!y-tree-node /short: ftn0 is either (, fa+se! or

&, !ma-e-chi+d"name"socsec"f"m# where name is a s$mbol! socsec is a number! and f and m are ftns, For now! we assume that e+er$one has a social securit$ number and that social securit$ numbers are uni?ue, Following our con+ention )rom part III! fa+se represents a lac. o) .nowledge about someoneCs )ather or mother, As we )ind out more in)ormation! though! we can add nodes to our )amil$ tree, De+elop the )unction add-ftnD, It consumes a )amil$ tree a-ft! a social securit$ number ssc! a s$mbol anc! and a chi+d structure, Its e))ect is to modi)$ that structure in a-ft whose social securit$ number is ssc, I) anc is 'father! it modi)ies the father )ield to contain the gi+en chi+d structureE otherwise! anc is the s$mbol 'mother and add-ftnD mutates the mother )ield, I) the respecti+e )ields alread$ contain a chi+d structure! add-ftnD signals an error, 8sing Functions as +rguments: Instead o) accepting 'father and 'mother )or anc! the )unction could also accept one o) the two structure mutators: set-chi+d-fatherD or set-chi+d-motherD, Modi)$ add-ftnD accordingl$, Solution E ercise #1<!<#< De+elop an implementation o) a hand with create-hand and addat-endD ser+ices using encapsulated state +ariables and )unction de)initions, Ase set! e8pression but no structure mutators, Solution -ot all mutator )unctions are as easil$ designed as the add-at-endD )unction, Indeed! in some cases things donCt e+en wor. out at all, "etCs consider two additional ser+ices, The )irst one remo+es the last card in a hand, Its contract and e))ect statement are +ariations on those )or add-at-endD:
66"remo0e-+astD":"hand""-/""0oid 66"effect":"to"remo0e"the"+ast"card"in"a-hand<".n+ess"it"is"the on+2"one !define"!remo0e-+astD"a-hand#"...#

The e))ect is restricted because a hand must alwa$s contain one card, 1e can also adapt the e8ample )or add-at-endD without di))icult$:
!define"hand%"!create-hand"13"C3'D5C## !begin ""!add-at-endD"1"DI'HNJDC"hand%# ""!add-at-endD"2"7LP(C"hand%# ""!remo0e-+astD"hand%#

""!remo0e-+astD"hand%##""

The resulting +alue is 0oid, The e))ect o) the computation is to return hand% in its initial state, The template )or remo0e-+astD is the same as that )or add-at-endD because both )unctions process the same class o) +alues, So the ne8t step is to anal$*e what e))ects the )unction must compute )or each case in the template: (, Recall that the )irst clause represents the case when a-handCs ne*t )ield is empt2, In contrast to the situation with add-at-endD! it is not clear what we need to do now, According to the e))ect statement! we must do one o) two things: a, I) a-hand is the last item in a chain that consists o) more than one hand structure! it must be remo+ed, b, I) a-hand is the onl$ structure that remo0e-+astD consumed! the )unction should ha+e no e))ect, But we canCt .now whether a-hand is the last item in a long chain o) hands or the onl$ one, 1e ha+e lost .nowledge that was a+ailable at the beginning o) the e+aluationL The anal$sis o) the )irst clause suggests the use o) an accumulator, 1e tried the natural route and disco+ered that .nowledge is lost during an e+aluation! which is the criterion )or considering a switch to an accumulator2based design recipe, @nce we ha+e recogni*ed the need )or an accumulator2st$le )unction! we encapsulate the template in a local2e8pression and add an accumulator argument to its de)inition and applications:
!define"!remo0e-+astD"a-hand%# ""!local"!66"acc.m.+ator"..." ""!define"!remD"a-hand"acc.m.+ator# """"!cond """"""9!empt2A"!hand-ne*t"a-hand##" """""""..."!hand-ran-"a-hand#"..."!hand-s.it"a-hand#"...: """"""9else"..."!hand-ran-"a-hand#"..."!hand-s.it"a-hand#"... """""""..."!remD"!hand-ne*t"a-hand#"... accumulator"...#"...:### """"..."!remD"a-hand%"...#"...##

The ?uestions to as. now are what the accumulator represents and what its )irst +alue is,

The best wa$ to understand the nature o) accumulators is to stud$ wh$ the plain structural design o) remo0e-+astD )ailed, Hence we return to the anal$sis o) our )irst clause in the template, 1hen remD reaches that clause! two things should ha+e been accomplished, First! remD should .now that a-hand is not the onl$ hand structure in ahand%, Second! remD must be enabled to remo+e a-hand )rom a-hand%, For the )irst goal! remDCs )irst application should be in a conte8t where we .now that a-hand% contains more than one card, This argument suggests a cond2e8pression )or the bod$ o) the local2e8pression:
!cond ""9!empt2A"!hand-ne*t"a-hand##"!0oid#: ""9else"!remD"a-hand%"...#:#

For the second goal! remDCs accumulator argument should alwa$s represent the hand structure that precedes a-hand in a-hand%, Then remD can remo+e a-hand b$ modi)$ing the predecessorCs ne*t )ield:
!set-hand-ne*tD"acc.m.+ator"empt2#

-ow the pieces o) the design pu**le )all into place, The complete de)inition o) the )unction is in )igure (&5, The acc.m.+ator parameter is renamed to predecessorof:a-hand to emphasi*e the relationship to the parameter proper, The )irst application o) remD in the bod$ o) the local2e8pression hands it the second hand structure in ahand%, The second argument is a-hand%! which establishes the desired relationship,
66"remo0e-+astD":"hand""-/""0oid 66"effect":"to"remo0e"the"+ast"card"in"a-hand%<".n+ess"it"is"the on+2"one !define"!remo0e-+astD"a-hand%# ""!local"!66"predecessor-of:a-hand"represents"the"predecessor"of ""66"a-hand"in"the"a-hand%"chain" ""!define"!remD"a-hand"predecessor-of:a-hand# """"!cond """"""9!empt2A"!hand-ne*t"a-hand## """""""!set-hand-ne*tD"predecessor-of:a-hand"empt2#: """"""9else"!remD"!hand-ne*t"a-hand#"a-hand#:### """"!cond """"""9!empt2A"!hand-ne*t"a-hand%##"!0oid#: """"""9else"!remD"!hand-ne*t"a-hand%#"a-hand%#:###

Both applications o) remD ha+e the shape /remL /hand2ne8t a2hand0 a2hand0 Figure 12!' Remo+ing the last card It is now time to re+isit the basic assumption about the card game that the cards are added to the end o) a hand, 1hen human pla$ers pic. up cards! the$ hardl$ e+er Fust add them to the end, Instead! man$ use some special arrangement and maintain it o+er the course o) a game, Some arrange hands according to suits! others according to ran.! and $et others according to both criteria, "etCs consider an operation )or inserting a card into a hand based on its ran.:

66"sorted-insertD":"ran-"s.it"hand""-/""0oid 66"ass.me:"a-hand"is"sorted"82"ran-<"in"descending"order 66"effect:"to"add"a"card"with"r"as"ran-"and"s"as"s.it"at"the proper"p+ace !define"!sorted-insertD"r"s"a-hand#"...#

The )unction assumes that the gi+en hand is alread$ sorted, The assumption naturall$ holds i) we alwa$s use create-hand to create a hand and sorted-insertD to insert cards, Suppose we start with the same hand as abo+e )or add-at-endD:
!define"hand%"!create-hand"13"C3'D5C##

I) we e+aluate !sorted-insertD"1"DI'HNJDC"hand%# in this conte8t! hands% becomes


!ma-e-hand"13"C3'D5C ""!ma-e-hand"1"DI'HNJDC"empt2##

I) we now e+aluate !sorted-insertD"2"7LP(C"hand%# in addition! we get


!ma-e-hand"13"C3'D5C ""!ma-e-hand"2"7LP(C """"!ma-e-hand"1"DI'HNJDC"empt2###

)or hand%, This +alue shows what it means )or a chain to be sorted in descending order, As we tra+erse the chain! the ran.s get smaller and smaller independent o) what the suits are, @ur ne8t step is to anal$*e the template, Here is the template! adapted to our present purpose:
!define"!sorted-insertD"r"s"a-hand# ""!cond """"9!empt2A"!hand-ne*t"a-hand##" """""..."!hand-ran-"a-hand#"..."!hand-s.it"a-hand#"...: """"9else"..."!hand-ran-"a-hand#"..."!hand-s.it"a-hand#"... """"""..."!sorted-insertD"r"s"!hand-ne*t"a-hand##"...:##

The .e$ step o) the )unction is to insert the new card between two cards such that )irst cardCs ran. is larger than! or e?ual to! r and r is larger than! or e?ual to! the ran. o) the second, Because we onl$ ha+e two cards in the second clause! we start b$ )ormulating the answer )or the second clause, The condition we Fust speci)ied implies that we need a nested cond2e8pression:
!cond ""9!/&"!hand-ran-"a-hand#"r"!hand-ran-"!hand-ne*t"a-hand###"...: ""9else"...:#

The )irst condition e8presses in Scheme what we Fust discussed, In particular! !handran-"a-hand# pic.s the ran. o) the )irst card in a-hand and !hand-ran-"!hand-ne*t

pic.s the ran. o) the second one, The comparison determines whether the three ran.s are properl$ ordered,
a-hand##

#ach case o) this new cond2e8pression deser+es its own anal$sis: (, I) !/&"!hand-ran-"a-hand#"r"!hand-ran-"!hand-ne*t"a-hand### is true! then the new card must go between the two cards that are currentl$ lin.ed, That is! the ne*t )ield o) a-hand must be changed to contain a new hand structure, The new structure consists o) r! s! and the original +alue o) a-handCs ne*t )ield, This $ields the )ollowing elaboration o) the cond2e8pression:
2. !cond 3. ""9!/&"!hand-ran-"a-hand#"r"!hand-ran-"!hand-ne*t"a-hand### 4. """!set-hand-ne*tD"a-hand"!ma-e-hand"r"s"!hand-ne*t"ahand###: 5. ""9else"...:#

9, I) !/&"!hand-ran-"a-hand#"r"!hand-ran-"!hand-ne*t"a-hand### is )alse! the new card must be inserted at some place in the rest o) the chain, @) course! the natural recursion accomplishes Fust that! which )inishes the anal$sis o) the second clause o) sorted-insertD, Putting all the pieces together $ields a partial )unction de)inition:
!define"!sorted-insertD"r"s"a-hand# ""!cond """"9!empt2A"!hand-ne*t"a-hand##" """""..."!hand-ran-"a-hand#"..."!hand-s.it"a-hand#"...: """"9else" """"""!cond 9!/&"!hand-ran-"a-hand#"r"!hand-ran-"!hand-ne*t"a-hand### "!set-hand-ne*tD"a-hand"!ma-e-hand"r"s"!hand-ne*t"a-hand###: 9else"!sorted-insertD"r"s"!hand-ne*t"a-hand##:#:##

The onl$ remaining gaps are now in the )irst clause, The di))erence between the )irst and the second cond2clause is that there is no second hand structure in the )irst clause so we cannot compare ran.s, Still! we can compare r and !hand-ran-"a-hand# and compute something based on the outcome o) this comparison:
!cond ""9!/&"!hand-ran-"a-hand#"r#"...: ""9else"...:#

Clearl$! i) the comparison e8pression e+aluates to tr.e! the )unction must mutate the ne*t )ield o) a-hand and add a new hand structure:
!cond ""9!/&"!hand-ran-"a-hand#"r#"

"""!set-hand-ne*tD"a-hand"!ma-e-hand"r"s"empt2##: ""9else"...:#

The problem is that we ha+e nothing to mutate in the second clause, I) r is larger than the ran. o) a-hand! the new card should be inserted between the predecessor o) a-hand and a-hand, But that .ind o) situation would ha+e been disco+ered b$ the second clause, The seeming contradiction suggests that the dots in the second clause are a response to a singular case: The dots are e+aluated onl$ i) sorted-insertD consumes a ran. r that is larger than all the +alues in the ran- )ields o) a-hand, In that singular case! a-hand shouldnCt change at all, A)ter all! there is no wa$ to create a descending chain o) cards b$ mutating a-hand or an$ o) its embedded hand structures, At )irst glance! we can o+ercome the problem with a set! e8pression that changes the de)inition o) hand%:
!set!"hand%"!ma-e-hand"r"s"hand%##

This )i8 doesnCt wor. in general though! because we canCt assume that we .now which +ariable de)inition must be modi)ied, Since e8pressions can be abstracted o+er +alues but not +ariables! there is also no wa$ to abstract o+er hand% in this setD2e8pression,

A hand is an inter)ace: (, 'insert :: ran-"s.it""-/""0oid


66"create-hand":"ran-"s.it""-/""hand 66"to"create"a"hand"from"the"ran-"and"s.it"of"a"sing+e"card !define"!create-hand"ran-"s.it# ""!local"!!define-struct"hand"!ran-"s.it"ne*t## "" """"""""""!define"the-hand"!ma-e-hand"ran-"s.it"empt2## "" """"""""""66"insert-a.*D":"ran-"s.it"hand""-/""0oid """"""""""66"ass.me:"hand"is"sorted"82"ran-"in"descending"order """"""""""66"effect:"to"add"a"card"with"r"as"ran-"and"s"as"s.it """"""""""66"at"the"proper"p+ace """"""""""!define"!insert-a.*D"r"s"a-hand# """"""""""""!cond """"""""""""""9!empt2A"!hand-ne*t"a-hand##" """""""""""""""!set-hand-ne*tD"a-hand"!ma-e-hand"r"s"empt2##: """"""""""""""9else"!cond """"""""""""""""""""""9!/&"!hand-ran-"a-hand# """r """!hand-ran-"!hand-ne*t"a-hand### """""""""""""""""""""""!set-hand-ne*tD"a-hand "!ma-e-hand"r"s"!hand-ne*t"a-hand###: """"""""""""""""""""""9else"!insert-a.*D"r"s"!hand-ne*t"ahand##:#:## "" ""..."66"other"ser0ices"as"needed "" """"""""""!define"!ser0ice-manager"msg# """"""""""""!cond """"""""""""""9!s2m8o+&A"msg"'insertD#" """""""""""""""!lambda"!r"s# """""""""""""""""!cond """""""""""""""""""9!/"r"!hand-ran-"the-hand## """"""""""""""""""""!set!"the-hand"!ma-e-hand"r"s"the-hand##: """""""""""""""""""9else"!insert-a.*D"r"s"the-hand#:##: """"""""""""""9else"!error"'managed-hand"1message"not .nderstood1#:###

ser+ice2manager00 Figure 12#' #ncapsulation and structure mutation )or hands o) cards

1eCre stuc., It is impossible to de)ine sorted-insertD! at least as speci)ied abo+e, The anal$sis suggests a remed$! howe+er, I) we introduce a single +ariable that alwa$s stands )or the current hand structure! we can use a combination o) assignments and structure mutators to insert a new card, The tric. is not to let an$ other part o) the program re)er to this +ariable or e+en change it, @therwise a simple set! wonCt wor.! as argued be)ore, In other words! we need a state +ariable )or each hand structure! and we need to encapsulate it in a local2e8pression, Figure (&6 displa$s the complete )unction de)inition, It )ollows the pattern o) section 5>, The )unction itsel) corresponds to create-hand! though instead o) producing a structure the new create-hand )unction produces a manager )unction, At this point! the manager can deal with onl$ one message: 'insertE all other messages are reFected, An 'insert message )irst chec.s whether the new ran. is larger than the )irst

one in the-hand! the hidden state +ariable, I) so! the manager Fust changes the-handE i) not! it uses insert-a.*D! which ma$ now assume that the new card belongs into the middle o) the chain, E ercise #1<!<$< #8tend the de)inition in )igure (&6 with a ser+ice )or remo+ing the )irst card o) a gi+en ran.! e+en i) it is the onl$ card, Solution E ercise #1<!<&< #8tend the de)inition in )igure (&6 with a ser+ice )or determining the suits o) those cards in the-hand that ha+e a gi+en ran., The )unction should produce a list o) suits, Solution E ercise #1<!<(< Re)ormulate create-hand in )igure (&6 such that the manager uses a single setD2e8pression and sorted-insert does not use an$ structure mutation, Solution E ercise #1<!<)< Recall the de)inition o) a binar$ tree )rom section (6,&: A binary-tree /short: 1T0 is either (, fa+se or &, !ma-e-node"soc"pn"+ft"rgt# where soc is a number! pn is a s$mbol! and +ft and rgt are (;s, The re?uired structure de)inition is
!define-struct"node"!ssn"name"+eft"right##

A binar$ tree is a binary-search-tree i) e+er$ node structure contains a social securit$ number that is larger than all those in the le)t subtree and smaller than all those in the right subtree, De+elop the )unction insert-8stD, The )unction consumes a name n! a social securit$ number s! and a bst, It modi)ies the bst so that it contains a new node with n and s while maintaining it as a search tree, Also de+elop the )unction remo0e-8stD! which remo+es a node with a gi+en social securit$ number, It combines the two subtrees o) the remo+ed node b$ inserting all the nodes )rom the right tree into the le)t one, Solution

The discussion in this subsection and the e8ercises suggest that adding or remo+ing items )rom lin.ed structures is a mess$ tas., Dealing with an item in the middle o) the lin.ed structures is best done with accumulator2st$le )unctions, Dealing with the )irst structure re?uires encapsulation and management )unctions, In contrast! as e8ercise 6(,5,; shows! a solution without mutators is much easier to produce than a solution based on structure mutation, And the case o) cards and hands! which deals with at most 7& structures! is e?uall$ e))icient, To decide which o) the two approaches to use re?uires a better understanding o) algorithmic anal$sis /see interme**o 70 and o) the language mechanisms and program design recipes )or encapsulating state +ariables,

)$#) E,tended E,ercise. /oving Pictures2 a Last Time


In sections 9,9! ;,6! (',5! and &(,6 we studied how to mo+e pictures across a can+as, A picture is a list o) shapesE a shape is one o) se+eral basic geometric shapes: circles! rectangles! etc, Following our most basic design principle 22 one )unction per concept 22 we )irst de)ined )unctions )or mo+ing basic geometric shapes! then )or mi8ed classes o) shapes! and )inall$ )or lists o) shapes, #+entuall$ we abstracted o+er related )unctions, The )unctions )or mo+ing basic shapes create a new shape )rom an e8isting shape, For e8ample! the )unction )or mo+ing a circle consumes a circ+e structure and produces a new circ+e structure, I) we thin. o) the circ+e as a painting with a round )rame and the can+as as a wall! howe+er! creating a new shape )or each mo+e is inappropriate, Instead! we should change the shapeCs current position, E ercise #1<#<1< Turn the )unctions trans+ate-circ+e and trans+ate-rectang+e o) e8ercises 9,9,& and 9,9,<! respecti+el$! into structure2mutating )unctions, Adapt mo0e-circ+e )rom section 9,9 and mo0e-rectang+e )rom e8ercise 9,9,(& so that the$ use these new )unctions, Solution E ercise #1<#<2< Adapt the )unction mo0e-pict.re )rom e8ercise (',5,9 to use the structure2mutating )unctions )rom e8ercise 6(,6,(, Solution E ercise #1<#<!< Ase SchemeCs for-each )unction /see Help Des.0 to abstract where possible in the )unctions o) e8ercise 6(,6,&, Solution

;9

The notation !vectorof"R# is analogous to !listof"R#,

Scheme proper pro+ides list mutators! and a Scheme programmer would use them to represent a hand as a list o) cards,
;;

Section #2 E9ualit%
As we mutate structures or +ectors! we use words such as DDthe +ector now contains fa+se in its )irst )ieldCC to describe what happens, Behind those words is the idea that the +ector itsel) sta$s the same 22 e+en though its properties change, 1hat this obser+ation suggests is that there are reall$ two notions o) e?ualit$: the one we ha+e used so )ar and a new one based on e))ects on a structure or +ector, Anderstanding these two notions o) e?ualit$ is criticall$ important )or a programmer, 1e there)ore discuss them in detail in the )ollowing two subsections,

)"#$ E,tensional E:uality


Recall the class o) posn structures )rom part I, A posn combines two numbersE its )ields are called * and 2, Here are two e8amples:
!ma-e-posn"3"4# !ma-e-posn"12"1# !ma-e-posn"$" # !ma-e-posn"12"1#

The$ are ob+iousl$ distinct, In contrast! the )ollowing two are e?ual, The$ both contain 12 in the *2)ield and 1 in the 22)ield, More generall$! we consider two structures to be e?ual i) the$ contain e?ual components, This assumes that we .now how to compare the components! but thatCs not surprising, It Fust reminds us that processing structures )ollows the data de)inition that comes with the structure de)inition, Philosophers re)er to this notion o) e?ualit$ as #NT#-SI@-A" #BAA"IT3, Section (;,< introduced e8tensional e?ualit$ and discussed its use )or building tests, As a reminder! letCs consider a )unction )or determining the e8tensional e?ualit$ o) posn structures:
66"e).a+-posn":"posn"posn""-/""8oo+ean 66"to"determine"whether"two"posns"are"e*tensiona++2"e).a+" !define"!e).a+-posn"p1"p2# ""!and"!&"!posn-*"p1#"!posn-*"p2## """""""!&"!posn-2"p1#"!posn-2"p2####

The )unction consumes two posn structures! e8tracts their )ield +alues! and then compares the corresponding )ield +alues using &! the predicate )or comparing numbers, Its organi*ation matches that o) the data de)inition )or posn structuresE its design is standard, This implies that )or recursi+e classes o) data! we naturall$ need recursi+e e?ualit$ )unctions,

E ercise #2<1<1< De+elop an e8tensional e?ualit$ )unction )or the class o) chi+d structures )rom e8ercise 6(,5,5, I) ft1 and ft2 are )amil$ tree nodes! how long is the ma8imal abstract running time o) the )unctionH Solution E ercise #2<1<2< Ase e8ercise 6&,(,( to abstract e).a+-posn so that its instances can test the e8tensional e?ualit$ o) an$ gi+en class o) structures, Solution

)"#" 3ntensional E:uality


Consider the )ollowing to$ program:
!define"a"!ma-e-posn"12"1## !define"8"!ma-e-posn"12"1## !begin ""!set-posn-*D"a"1# ""!e).a+-posn"a"8##

It de)ines two posn structures, The two structures are initiall$ e?ual in the sense o) the preceding subsection, 3et when we e+aluate the begin2e8pression! the result is fa+se, #+en though the two structures initiall$ consist o) the same +alues! the$ are di))erent because the structure mutation in the begin2e8pression changes the *2)ield o) the )irst structure and lea+es the second one alone, More generall$! the e8pression has an e))ect on one structure but not the other, -ow ta.e a loo. at a slightl$ di))erent program:
!define"a"!ma-e-posn"12"1## !define"8"a# !begin ""!set-posn-*D"a"1# ""!e).a+-posn"a"8##

Here a and 8 are two di))erent names )or the same structure, There)ore! the e+aluation o) !set-posn-*D"a"1# a))ects both a and 8! which means that !e).a+-posn"a"8# is going to $ield tr.e this time, The two obser+ations ha+e a general moral, I) the e+aluation o) an e8pression a))ects one structure and simultaneousl$ some other structure! the two structures are e?ual in a deeper sense than e).a+-posn can determine, Philosophers re)er to this notion o) e?ualit$ as I-T#-SI@-A" #BAA"IT3, In contrast to e8tensional e?ualit$! this notion o) e?ualit$ re?uires not onl$ that two structures consist o) e?ual parts! but that the$ also simultaneousl$ react to structure mutations, It is a direct conse?uence that two intensionall$ e?ual structures are also e8tensionall$ e?ual,

Designing a )unction )or determining the intensional e?ualit$ o) structures is more wor. than designing one )or determining their e8tensional e?ualit$, 1e start with a precise description:
66"e)-posn":"posn"posn""-/""8oo+ean 66"to"determine"whether"two"posn"str.ct.res" 66"are"affected"82"the"same"m.tation" !define"!e)-posn"p1"p2#"...#

1e alread$ ha+e an e8ample! so we mo+e on to a discussion o) the template:


!define"!e)-posn"p1"p2# ""..."!posn-*"p1#"..."!posn-*"p2#"... ""..."!posn-2"p1#"..."!posn-2"p2#"..."#

The template contains )our e8pressions! each one reminding us o) the a+ailable in)ormation and which structure )ields we can mutate, Translating the abo+e obser+ations into a )ull de)inition $ields the )ollowing dra)t:
!define"!e)-posn"p1"p2# ""!begin """"!set-posn-*D"p1"5# """"!&"!posn-*"p2#"5###

This )unction sets p1Cs *2)ield to 5 and then chec.s whether p2Cs *2)ield also became 5, I) so! both structures reacted to the mutation and are! b$ de)inition! intensionall$ e?ual, An)ortunatel$! our reasoning has a problem, Consider the )ollowing application:
!e)-posn"!ma-e-posn"1"2#"!ma-e-posn"5" ##

The two posnCs arenCt e+en e8tensionall$ e?ui+alent! so the$ should not be intensionall$ e?ui+alent, But our )irst +ersion o) e)-posn would produce tr.e! and that is a problem, 1e can impro+e the )irst +ersion with a second mutation:
!define"!e)-posn"p1"p2# ""!begin """"!set-posn-*D"p1"5# """"!set-posn-*D"p2" # """"!&"!posn-*"p1#" ###

This )unction changes p1 and then p2, I) the structures are intensionall$ e?ual! then the mutation o) p2 must a))ect p1, Furthermore! we .now that p1Cs *2)ield canCt coincidentall$ contain ! because we )irst changed it to 5, Thus! when !e)-posn"a"8# produces tr.e! a changes when 8 changes and +ice +ersa! and the structures are intensionall$ e?ual,

The onl$ problem le)t now is that e)-posn has e))ects on the two structures that it consumes but has no e))ect statement, Indeed! it should not ha+e a +isible e))ect because its onl$ purpose is to determine whether two structures are intensionall$ e?ual, 1e can a+oid this e))ect b$ )irst sa+ing the old +alues in p1Cs and p2Cs * )ields! mutating the )ields! and then restoring the old +alues, Figure (&7 contains a )unction de)inition that per)orms an intensional e?ualit$ chec. without an$ +isible e))ects,
66"e)-posn":"posn"posn""-/""8oo+ean 66"to"determine"whether"two"posn"str.ct.res" 66"are"affected"82"the"same"m.tation" !define"!e)-posn"p1"p2# ""!local"!66"sa0e"o+d"*"0a+.es"of"p1"and"p2 ""!define"o+d-*1"!posn-*"p1## ""!define"o+d-*2"!posn-*"p2## ""66"modif2"8oth"*"fie+ds"of"p1"and"p2 ""!define"effect1"!set-posn-*D"p1"5## ""!define"effect2"!set-posn-*D"p2" ## ""66"now"compare"the"two"fie+ds ""!define"same"!&"!posn-*"p1#"!posn-*"p2### ""66"restore"o+d"0a+.es ""!define"effect3"!set-posn-*D"p1"o+d-*1## ""!define"effect4"!set-posn-*D"p2"o+d-*2###

same00 Figure 12$' Determining the intensional e?ualit$ o) two structures The e8istence o) e)-posn sa$s that all structures ha+e a uni?ue DD)ingerprint,CC 1e can inspect two structures /o) the same class0 )or this )ingerprint i) we ha+e access to the mutators, Scheme and man$ other languages t$picall$ pro+ide built2in )unctions )or comparing two structural +alues e8tensionall$ and intensionall$, The corresponding Scheme )unctions are e).a+A and e)A, In Scheme! both )unctions are applicable to all +alues! whether mutators and selectors are accessible or hidden, The e8istence o) e)A suggests a re+ision )or our guideline on testing,

=uideline on Testing
Ase e)A )or testing when comparing the identit$ o) obFects matters, Ase e).a+A )or testing otherwise, The guideline is general, Still! programmers should use e?ualit$ )unctions that indicate what .ind o) +alues the$ e8pect to compare! such as s2m8o+&A! 8oo+eanA! or &! because the additional in)ormation helps readers understand the purpose o) the program more easil$, E ercise #2<2<1< #+aluate the )ollowing e8pressions b$ hand:
1."!e)-posn"!ma-e-posn"1"2#"!ma-e-posn"1"2## 2."!local"!!define"p"!ma-e-posn"1"2### !e)-posn"p"p## 3."!local"!!define"p"!ma-e-posn"1"2## """""!define"a"!+ist"p###

!e)-posn"!first"a#"p##

Chec. the answers with DrScheme,

Solution

E ercise #2<2<2< De+elop an intensional e?ualit$ )unction )or the class o) chi+d structures )rom e8ercise 6(,5,5, I) ft1 and ft2 are )amil$ tree nodes! how long is the ma8imal abstract running time o) the )unctionH Solution E ercise #2<2<!< Ase e8ercise 6&,&,& to abstract e)-posn so that its instances can test the intensional e?ualit$ o) an$ gi+en class o) structures, Solution

Section #! Changing Structures, "ectors, and :b;ects


This section introduces se+eral small proFects on programming with mutable structures, The ordering o) the subsections roughl$ matches the outline o) the boo.! proceeding )rom simple classes o) data to complicated ones and )rom structural recursion to generati+e recursion with bac.trac.ing and accumulators,

)(#$ /ore Practice !ith 'ectors


Programming with mutable +ectors is hardl$ e+er needed in the .inds o) programs that we encountered, Still! because it is )ar more pre+alent in con+entional languages! it is an important s.ill and deser+es more practice than section 6(,& suggests, This section co+ers sorting with +ectors! but its goal is to practice reasoning about inter+als when processing +ectors, 1e encountered the idea o) sorting as earl$ as section (&,&! where we designed the sort )unction, It consumes a list o) numbers and produces a list o) numbers with the same items in sorted /ascending or descending0 order, An analogous )unction )or +ectors consumes a +ector and produces a new +ector, But! using +ector mutation! we can also design a )unction that changes the +ector so that it contains the same items as be)ore! in a sorted order, Such a )unction is called an I-2P"AC# S@RT because it lea+es all the items inside the e8isting +ector,

An in2place2sort )unction relies e8clusi+el$ on e))ects on its input +ector to accomplish its tas.:
66"in-p+ace-sort":"!vectorof"n.m8er#""-/""0oid 66"effect:"to"modif2"W"s.ch"that"it"contains"the"same"items" 66"as"8efore"8.t"in"ascending"order" !define"!in-p+ace-sort"W#"...#

#8amples must demonstrate the e))ect:


!local"!!define"01"!0ector"7"3"%"4"1### ""!begin """"!in-p+ace-sort"01# """"!e).a+A"01"!0ector"%"1"3"4"7####

@) course! gi+en that in-p+ace-sort consumes a +ector! the true problem is to design the au8iliar$ )unction that wor.s on speci)ic segments o) the +ector, The standard template )or a +ector2processing )unction uses an au8iliar$ )unction:
!define"!in-p+ace-sort"W# ""!local"!!define"!sort-a.*"W"i# """"!cond """"""9!@eroA"i#"...: """"""9else ..."!0ector-ref"W"!s.81"i##"... ..."!sort-a.*"W"!s.81"i##"...:### """"!sort-a.*"W"!0ector-+ength"W####

Following the design ideas o) interme**o 7! the au8iliar$ )unction consumes a natural number and uses it as an inde8 into the +ector, Because the initial argument is !0ector+ength"W#! the accessible inde8 is alwa$s !s.81"i#, Recall that the .e$ to designing )unctions such as sort-a.* is to )ormulate a rigorous purpose andKor e))ect statement, The statement must clari)$ on which inter+al o) the possible +ector indices the )unction wor.s and what e8actl$ it accomplishes, @ne natural e))ect statement )ollows:
66"sort-a.*":"!vectorof"n.m8er#"N""-/""0oid 66"effect:"to"sort"the"inter0a+"9%<i#"of"W"in"p+ace" !define"!sort-a.*"W"i#"...#

To understand this e))ect statement in the larger conte8t! letCs adapt our original e8ample:
!local"!!define"01"!0ector"7"3"%"4"1### ""!begin """"!sort-a.*"01"5# """"!e).a+A"01"!0ector"%"1"3"4"7####

I) sort-a.* is applied to a +ectorCs length! it should sort the entire +ector, This statement implies that i) the )irst argument is less than the +ectorCs length onl$ some initial segment o) the +ector is sorted:

!local"!!define"01"!0ector"7"3"%"4"1### ""!begin """"!sort-a.*"01"4# """"!e).a+A"01"!0ector"%"3"4"7"1####

In this particular e8ample! the last number remains in its original place! and onl$ the )irst )our +ector items are sorted,
66"in-p+ace-sort":"!vectorof"n.m8er#""-/""0oid 66"effect:"to"modif2"W"s.ch"that"it"contains"the"same"items" 66"as"8efore"8.t"in"ascending"order" !define"!in-p+ace-sort"W# ""!local"!66"sort-a.*":"!vectorof"n.m8er#"N""-/""0oid ""66"effect:"to"sort"the"inter0a+"9%<i#"of"W"in"p+ace" ""!define"!sort-a.*"W"i# """"!cond """"""9!@eroA"i#"!0oid#: """"""9else"!begin """"""66"sort"the"segment"9%<!s.81"i##: """"""!sort-a.*"W"!s.81"i## """"""66"insert"!0ector-ref"W"!s.81"i##"into"the segment" """"""66"9%<i#"so"that"it"8ecomes"sortedKK """"""!insert"!s.81"i#"W##:## "" ""66"insert":"N"!vectorof"n.m8er#""-/""0oid ""66"to"p+ace"the"0a+.e"in"the"i-th"into"its"proper"p+ace" ""66"in"the"segement"9%<i:"of"W ""66"ass.me:"the"segment""9%<i#"of"W"is"sorted ""!define"!insert"i"W# """"...##

/sort2au8 4 /+ector2length 40000 Figure 12&' An in2place sort )unction: First part -ow we can anal$*e each case in the template o) sort-a.*:

(, I) i is %! the inter+al o) the e))ect statement is V%!%0, This means that the inter+al is empt$ and that the )unction has nothing to do, &, The second clause in the template contains two e8pressions:
3. !0ector-ref"W"!s.81"i## 4. and 5. !sort-a.*"W"!s.81"i##

The )irst reminds us that we can use the i - (2st )ield o) WE the second one reminds us o) the natural recursion, In this case! the natural recursion sorts the inter+al V%!!s.81"i#0, To )inish the tas.! we must insert the +alue o) the i - (2st )ield into its proper place in the inter+al V%!i0, The abo+e e8amples ma.e this case concrete, 1hen we e+aluate !sort-a.*"01 4#! the number in the last )ield o) 01 remains at its place, The )irst )our items in

the +ectors are: %! 3! 4! and 7, To sort the entire inter+al V%!50! we must insert 1! which is !0ector-ref"W"!s.81"5##! between % and 3, In short! the design o) in-p+ace-sort )ollows the same pattern as that o) the )unction sort in section (&,& up to this point, For sort! we also designed the main )unction onl$ to )ind out that we needed to design an au8iliar$ )unction )or inserting one more item into its proper place, Figure (&9 gathers what we ha+e discussed about in-p+ace-sort so )ar, It also includes a speci)ication o) insert! the second au8iliar$ )unction, To understand its e))ect statement! we re)ormulate the e8ample )or the second clause o) sort-a.*:
!local"!!define"01"!0ector"%"3"4"7"1### ""!begin """"!insert"4"01# """"!e).a+A"01"!0ector"%"1"3"4"7####

In this case! insert mo+es 1 o+er three numbers: )irst 7! then 4! and )inall$ 3, It stops when the ne8t number in the le)twards direction! that is! %! is smaller than the number that is being inserted, "etCs loo. at a second e8ample )or insert:
!local"!!define"01"!0ector"7"3"%"4"1### ""!begin """"!insert"1"01# """"!e).a+A"01"!0ector"3"7"%"4"1####

Here the problem is to insert 3 into a segment that contains onl$ one number: 7, This means that insert must swap the +alues in the )irst two )ields and must stop then! because 3 canCt mo+e an$ )urther to the le)t,

/sort2au8 4 /+ector2length 40000 Figure 12(' An in2place sort )unction: Second part -ow ta.e a loo. at the template )or insert:
!define"!insert"i"W#" ""!cond """"9!@eroA"i#"...: """"9else """"""..."!0ector-ref"W"!s.81"i##"... """"""..."!insert"!s.81"i#"W#"...":##

!define"!in-p+ace-sort"W# ""!local"!66"sort-a.*":"!vectorof"n.m8er#"N""-/""0oid ""66"effect:"to"sort"the"inter0a+"9%<i#"of"W"in"p+ace" ""!define"!sort-a.*"W"i# """"...# "" ""66"insert":"N"!vectorof"n.m8er#""-/""0oid ""66"to"p+ace"the"0a+.e"in"the"i-th"into"its"proper"p+ace" ""66"in"the"9%<i:"segement"of"W ""!define"!insert"i"W#" """"!cond """"""9!@eroA"i#"!0oid#: """"""9else"!cond """"""9!/"!0ector-ref"W"!s.81"i##"!0ector-ref"W"i## """""""!begin "!swap"W"!-"i"1#"i# "!insert"!s.81"i#"W##: """"""9else"!0oid#:#:## "" ""66"swap":"!vectorof"R#"N"N"0oid" ""!define"!swap"W"i"S# """"!local"!!define"temp"!0ector-ref"W"i### """"""!begin !0ector-setD"W"i"!0ector-ref"W"S## !0ector-setD"W"S"temp#####

It is the standard template )or a +ector2processing au8iliar$ )unction, As usual we distinguish two cases: (, I) i is %! the goal is to insert !0ector-ref"W"%# into the segment V%!%W, Since this inter+al contains onl$ one number! insert has accomplished its tas., &, I) i is positi+e! the template implies that we ma$ consider another item in W! namel$ !0ector-ref"W"!s.81"i##! and that we can per)orm a natural recursion, The immediate ?uestion is whether !0ector-ref"W"!s.81"i## is smaller or larger than !0ector-ref"W"i#! the item that is to be mo+ed around, I) so! W is sorted on the entire inter+al V%!iW! because W is sorted on V%!i0 b$ assumption, I) not! the item at i is out o) order still, The cond2e8pression that emplo$s the necessar$ conditions is
!cond

""9!/"!0ector-ref"W"!s.81"i##"!0ector-ref"W"i##"...: ""9!?&"!0ector-ref"W"!s.81"i##"!0ector-ref"W"i##"!0oid#:#

The second clause contains !0oid# because there is nothing le)t to do, In the )irst clause! insert must 22 at a minimum 22 swap the +alues in the two )ields, That is! insert must place !0ector-ref"W"i# into )ield !s.81"i# and !0ector-ref"W"!s.81"i## into )ield i, But e+en that ma$ not be enough, A)ter all! the +alue in the i2th )ield ma$ ha+e to wander o+er se+eral )ields as the )irst e8ample demonstrated, Fortunatel$! we can easil$ sol+e this problem with the natural recursion! which inserts the !0ector-ref"W"!s.81"i## into its proper place in V'!!s.81"i#W a)ter the swapping has ta.en place, Figure (&; contains the complete de)inition o) insert and swap, This second )unction is responsible )or swapping the +alue o) two )ields, E ercise #!<1<1< Test the au8iliar$ )unctions )or in-p+ace-sort )rom )igures (&9 and (&;, Formulate the tests as boolean2+alued e8pressions, De+elop and test more e8amples )or in-p+ace-sort, Integrate the pieces, Test the integrated )unction, #liminate super)lous arguments )rom the au8iliar$ programs in the integrated de)inition! step b$ step! testing the complete )unction a)ter each step, Finall$! change in-p+ace-sort so that its result is the modi)ied +ector, Solution

Figure 12)' Inserting an item into a sorted +ector segment

E ercise #!<1<2< The insert )unction o) )igure (&; per)orms two +ector mutations )or each time the )unction recurs, #ach o) these mutations pushes !0ector-ref"W"i#! )or the original +alue o) i! to the le)t in W until its proper place is )ound,

Figure (&< illustrates a slightl$ better solution, The situation in the top row assumes that the +alues a! 8! and c are properl$ arranged! that is!
!?"a"8"..."c#

holds, Furthermore! d is to be inserted and its place is between a and 8! that is!
!?"a"d"8#

holds! too, The solution is to compare d with all the items in $ I ( through i and to shi)t the items to the right i) the$ are larger than d, #+entuall$! we )ind a /or the le)t end o) the +ector0 and ha+e a DDholeCC in the +ector! where d must be inserted, /The hole actuall$ contains 8,0 This situation is illustrated in the middle row, The last one shows how d is placed between a and 8, De+elop a )unction insert that implements its desired e))ect according to this description, >int' The new )unction must consume d as an additional argument, Solution E ercise #!<1<!< For man$ other programs! we could swap the order o) the sube8pressions in begin2e8pressions and still get a wor.ing program, "etCs consider this idea )or sort-a.*:
66"sort2-a.*":"!vectorof"n.m8er#""N""-/""0oid !define"!sort2-a.*"W"i# ""!cond """"9!@eroA"i#"!0oid#: """"9else"!begin """"""""""""!insert2"!s.81"i#"W# """"""""""""!sort2-a.*"W"!s.81"i###:##

The order implies that sort2-a.* )irst inserts the item )rom !s.81"i# into some alread$ sorted part o) W and then sorts the remainder o) W, Here is a picture that illustrates the situation graphicall$: i2( a le)t right

The depicted +ector consists o) three pieces: a! the item in )ield !s.81"i#! the le)t )ragment! and the right )ragment, The ?uestions are which o) the two )ragments is sorted and into which )ragment a should be inserted, Considering that sort2-a.* decreases its )irst argument and thus sweeps o+er the +ector )rom right to le)t! the answers are that the right )ragment is initiall$ empt$ and thus sorted in ascending order b$ de)aultE the le)t )ragment is still unorderedE and a must be inserted into its proper place in the right )ragment,

De+elop a precise e))ect statement )or sort-a.* based on these obser+ations, Then de+elop the )unction insert2 so that sort2-a.* sorts +ectors properl$, Solution In section &7,&! we got to .now )sort! a )unction based on generati+e recursion, =i+en a list! )sort constructs a sorted +ersion in three steps: (, choose an item )rom the list! call it pi0otE &, create two sublists: one with all those items strictl$ smaller than pi0ot! another one with all those items strictl$ larger than pi0otE 5, sort each o) the two sublists! using the same steps! and then append the two lists with the pi+ot item in the middle, It isnCt di))icult to see wh$ the result is sorted! wh$ it contains all the items )rom the original list! and wh$ the process stops, A)ter all! at e+er$ stage! the )unction remo+es at least one item )rom the list so that the two sublists are shorter than the gi+en oneE e+entuall$ the list must be empt$, a +ector )ragment with pi+ot item p: !eft right p sm-1 !a-1 sm-2 sm-3 !a-2 partitioning the +ector )ragment into two regions! separated b$ p !eft1 right1 !eft2 right2 sm-2 sm-1 sm-3 p !a-1 !a-2 Figure 12-' The partitioning step )or in2place ?uic.2sort

Figure (&> illustrates how this idea can be adapted )or an in2place +ersion that wor.s on +ectors, At each stage! the algorithm wor.s on a speci)ic )ragment o) the +ector, It pic.s the )irst item as the pi0ot item and rearranges the )ragment so that all items smaller than the pi+ot appear to the le)t o) pi0ot and all items larger than pi0ot appear to its right, Then )sort is used twice: once )or the )ragment between +eft1 and right1 and again )or the )ragment between +eft2 and right2, Because each o) these two inter+als is shorter than the originall$ gi+en inter+al! )sort e+entuall$ encounters the empt$ inter+al and stops, A)ter )sort has sorted each )ragment! there is nothing le)t to doE the partitioning process has arranged the +ector into )ragments o) ascending order, Here is the de)inition o) )sort! an in2place sorting algorithm )or +ectors:
66")sort":"!vectorof"n.m8er#""-/""!vectorof"n.m8er# 66"effect:"to"modif2"W"s.ch"that"it"contains"the"same"items"as 8efore<

66"in"ascending"order"" !define"!)sort"W# ""!)sort-a.*"W"%"!s.81"!0ector-+ength"W#### 66")sort-a.*":"!vectorof"n.m8er#"J"J""-/""!vectorof"n.m8er# 66"effect:"sort"the"inter0a+"9+eft<right:"of"0ector"W 66"generati0e"rec.rsion !define"!)sort-a.*"W"+eft"right# ""!cond """"9!/&"+eft"right#"W: """"9else"!local"!!define"new-pi0ot-position"!partition"W"+eft right### """"""""""""!begin"!)sort-a.*"W"+eft"!s.81"new-pi0ot-position## """""""""""""""""""!)sort-a.*"W"!add1"new-pi0ot-position# right###:##

The main )unctionCs input is a +ector! so it uses an au8iliar$ )unction to do its Fob, As suggested abo+e! the au8iliar$ )unction consumes the +ector and two boundaries, #ach boundar$ is an inde8 into the +ector, Initiall$! the boundaries are % and !s.81 !0ector-+ength"W##! which means that )sort-a.* is to sort the entire +ector, The de)inition o) )sort-a.* closel$ )ollows the algoritmCs description, I) +eft and right describe a boundar$ o) si*e ( or less! its tas. is done, @therwise! it partitions the +ector, Because the partitioning step is a separate comple8 process! it re?uires a separate )unction, It must ha+e both an e))ect and a result proper! the new inde8 )or the pi+ot item! which is now at its proper place, =i+en this inde8! )sort-a.* continues to sort W on the inter+als V+eft!!s.81"new-pi0ot-position#W and V!add1"new-pi0otposition#! rightW, Both inter+als are at least one item shorter than the original! which is the termination argument )or )sort-a.*, -aturall$! the .e$ problem here is the partitioning step! which is implemented b$ partition:
66"partition":"!vectorof"n.m8er#"N"N""-/""N 66"to"determine"the"proper"position"p"of"the"pi0ot-item" 66"effect:"rearrange"the"0ector"W"so"that" 66"--"a++"items"in"W"in"9+eft<p#"are"sma++er"than"the"pi0ot"item 66"--"a++"items"of"W"in"!p<right:"are"+arger"than"the"pi0ot"item !define"!partition"W"+eft"right#"...#

For simplicit$! we choose the le)t2most item in the gi+en inter+al as the pi+ot item, The ?uestion is how partition can accomplish its tas.! )or e8ample! whether it is a )unction based on structural recursion or whether it is based on generati+e recursion, Furthermore! i) it is based on generati+e recursion! the ?uestion is what the generati+e step accomplishes,

right sm-2 !a-1 !a-2 ne--right ne--!eft )inding the swapping points )or partition: !eft right p sm-1 !a-1 sm-2 sm-3 !a-2 ne--!eft ne--right swapping the items and recuring on a new inter+al: !eft right p sm-1 sm-3 sm-2 !a-1 !a-2 p sm-1 stopping the generati+e recursion and clean2up: Figure 1!.' The partitioning process )or in2place ?uic.2sort

!eft sm-3

The best strateg$ is to consider an e8ample and to see how the partitioning step could be accomplished, The )irst e8ample is a small +ector with si8 numbers:
!0ector"1.1"%.75"1.,"%.35"%.5$"2.2#

The pi+otCs position is %E the pi+ot item is 1.1, The boundaries are % and 5, @ne item! 1.,! is ob+iousl$ out o) place, I) we swap it with %.5$! then the +ector is almost per)ectl$ partitioned:
!0ector"1.1"%.75"%.5$"%.35"1.,"2.2#

In this modi)ied +ector! the onl$ item out o) place is the pi+ot item itsel), Figure (5' illustrates the swapping process that we Fust described, First! we must )ind two items to swap, To do that! we search W )or the )irst item to the right o) +eft that is larger than the pi+ot item, Analogousl$! we search W )or the )irst item to the le)t o) right that is smaller than the pi+ot item, These searches $ield two indices: new-+eft and new-right, Second! we swap the items in )ields new-+eft and new-right, The result is that the item at new-+eft is now smaller than the pi+ot item and the one at new-right is larger, Finall$! we can continue the swapping process with the new! smaller inter+al, 1hen the )irst step $ields +alues )or new-+eft and new-right that are out o) order! as in the bottom row o) )igure (5'! then we ha+e a mostl$ partitioned +ector /)ragment0, 1or.ing through this )irst e8ample suggests that partition is an algorithm! that is! a )unction based on generati+e recursion, Following our recipe! we must as. and answer )our ?uestions: (, 1hat is a tri+iall$ sol+able problemH

&, 1hat is a corresponding solutionH 5, How do we generate new problems that are more easil$ sol+able than the original problemH Is there one new problem that we generate or are there se+eralH 6, Is the solution o) the gi+en problem the same as the solution o) /one o)0 the new problemsH @r! do we need to per)orm an additional computation to combine these solutions be)ore we ha+e a )inal solutionH And! i) so! do we need an$thing )rom the original problem dataH The e8ample addressed issues (! 5! and 6, The )irst step is to determine the new-+eft and new-right indices, I) new-+eft is smaller than new-right! the generati+e wor. is to swap items in the two )ields, Then the process recurs with the two new boundaries, I) new-+eft is larger than new-right! the partitioning process is )inished e8cept )or the placement o) the pi+ot itemE placing the pi+ot item answers ?uestion &, Assuming we can sol+e this DDtri+iall$ sol+ableCC problem! we also .now that the o+erall problem is sol+ed, "etCs stud$ ?uestion & with some e8amples, 1e stopped wor.ing on the )irst e8ample when the +ector had been changed to
!0ector"1.1"%.75"%.5$"%.35"1.,"2.2#

and the inter+al had been narrowed down to V2!4W, The search )or new-+eft and newright now $ields 4 and 3! respecti+el$, That is!
!?&"new-right"new-+eft#

holds, Switching the item in )ield new-right with the original le)t2most boundar$ places the pi+ot item in the proper spot:
!0ector"%.35"%.75"%.5$"1.1"1.,"2.2#

because new-right points to the right2most item in the +ector that is smaller than the pi+ot item, Be)ore we accept this seemingl$ simple solution! letCs chec. it with some additional e8amples! especiall$ +ector )ragments where the pi+ot item is the largest or smallest item, Here is one such e8ample:
!0ector"1.1"%.1"%.5"%.4#

Assuming the initial inter+al is V%!3W! the pi+ot item is 1.1, Thus! all other items in the +ector are smaller than the pi+ot item! which means that it should end up in the right2 most position,

@ur process clearl$ $ields 3 )or new-right, A)ter all! %.4 is smaller than pi+ot, The search )or new-+eft! though! wor.s di))erentl$, Since none o) the items in the +ector is larger than the pi+ot item! it e+entuall$ generates 3 as an inde8! which is the largest legal inde8 )or this +ector, At this point the search must stop, Fortunatel$! new-+eft and new-right are e?ual at this point! which implies that the partitioning process can stop and means that we can still swap the pi+ot item with the one in )ield new-right, I) we do that! we get a per)ectl$ well2partitioned +ector:
!0ector"%.4"%.1"%.5"%.4"1.1#

The third sample +ectorCs items are all larger than the pi+ot item:
!0ector"1.1"1.2"3.3"2.4#

In this case! the search )or new-+eft and new-right must disco+er that the pi+ot item is alread$ in the proper spot, And indeed! it does, The search )or new-+eft ends at )ield (! which is the )irst )ield that contains an item larger than the pi+ot item, The search )or new-right ends with %! because it is the smallest legal inde8 and the search must stop there, As a result! new-right once again points to that )ield in the +ector that must contain the pi+ot item )or the +ector /)ragment0 to be properl$ partitioned, In short! the e8amples suggest se+eral things: (, The termination condition )or partition is !?&"new-right"new-+eft#, &, The +alue o) new-right is the )inal position o) the pi+ot item! which is in the original le)t2most point o) the inter+al o) interest, It is alwa$s acceptable to swap the contents o) the two )ields, 5, The search )or new-right starts at the right2most boundar$ and continues until it either )inds an item that is smaller than the pi+ot item or until it hits the le)t2most boundar$, 6, Duall$! the search )or new-+eft starts at the le)t2most boundar$ and continues until it either )inds an item that is larger than the pi+ot item or until it hits the right2most boundar$, And! the two searches are comple8 tas.s that deser+e their own )unction, 1e can now graduall$ translate our discussion into Scheme, First! the partitioning process is a )unction o) not Fust the +ector and some inter+al! but also o) the original le)t2most position o) the +ector and its content, This suggests the use o) locall$ de)ined )unctions and +ariables:

!define"!partition"W"+eft"right# ""!local"!!define"pi0ot-position"+eft# """"""""""!define"the-pi0ot"!0ector-ref"W"+eft## """"""""""!define"!partition-a.*"+eft"right#" """"...## """"!partition-a.*"+eft"right###

The alternati+e is to use an au8iliar$ )unction that consumes the pi+otCs original position in addition to the +ector and the current inter+al, Second! the au8iliar$ )unction consumes an inter+alCs boundaries, It immediatel$ generates a new pair o) indices )rom these boundaries: new-+eft and new-right, As mentioned! the searches )or the two new boundaries are comple8 tas.s and deser+e their own )unctions:
66"find-new-right":"!vectorof"n.m8er#"n.m8er"N"N"9/&"+eft:""-/""N 66"to"determine"an"inde*"i"8etween"+eft"and"right"!inc+.si0e# 66"s.ch"that"!?"!0ector-ref"W"i#"the-pi0ot#"ho+ds !define"!find-new-right"W"the-pi0ot"+eft"right#"...# 66"find-new-+eft":"!vectorof"n.m8er#"n.m8er"N"N"9/&"+eft:""-/""N 66"to"determine"an"inde*"i"8etween"+eft"and"right"!inc+.si0e# 66"s.ch"that"!/"!0ector-ref"W"i#"the-pi0ot#"ho+ds !define"!find-new-+eft"W"the-pi0ot"+eft"right#"...#

Asing these two )unctions! partition-a.* can generate the new boundaries:
!define"!partition"W"+eft"right# ""!local"!!define"pi0ot-position"+eft# """"""""""!define"the-pi0ot"!0ector-ref"W"+eft## """"""""""!define"!partition-a.*"+eft"right# """"""""""""!local"!!define"new-right"!find-new-right"W"the-pi0ot +eft"right## """"""""""""""""""""!define"new-+eft"!find-new-+eft"W"the-pi0ot +eft"right### """"""..."### """"!partition-a.*"+eft"right###

From here the rest o) the de)inition is a plain transliteration o) our discussion into Scheme,

66"partition":"!vectorof"n.m8er#"N"N""-/""N 66"to"determine"the"proper"position"p"of"the"pi0ot-item" 66"effect:"rearrange"the"0ector"W"so"that" 66"--"a++"items"in"W"in"9+eft<p#"are"sma++er"than"the"pi0ot"item 66"--"a++"items"of"W"in"!p<right:"are"+arger"than"the"pi0ot"item 66"generati0e"rec.rsion !define"!partition"W"+eft"right# ""!local"!!define"pi0ot-position"+eft# """"""""""!define"the-pi0ot"!0ector-ref"W"+eft## """"""""""!define"!partition-a.*"+eft"right# """"""""""""!local"!!define"new-right"!find-new-right"W"the-pi0ot +eft"right## """"""""""""""""""""!define"new-+eft"!find-new-+eft"W"the-pi0ot +eft"right### """"""""""""""!cond """"""""""""""""9!/&"new-+eft"new-right# """""""""""""""""!begin """""""""""""""""""!swap"W"pi0ot-position"new-right# """""""""""""""""""new-right#: """"""""""""""""9else"6"!?"new-+eft"new-right# """""""""""""""""!begin """""""""""""""""""!swap"W"new-+eft"new-right# """""""""""""""""""!partition-a.*"new-+eft"new-right##:#### """"!partition-a.*"+eft"right### 66"find-new-right":"!vectorof"n.m8er#"n.m8er"N"N"9/&"+eft:""-/""N 66"to"determine"an"inde*"i"8etween"+eft"and"right"!inc+.si0e# 66"s.ch"that"!?"!0ector-ref"W"i#"the-pi0ot#"ho+ds 66"str.ct.ra+"rec.rsion:"see"te*t !define"!find-new-right"W"the-pi0ot"+eft"right# ""!cond """"9!&"right"+eft#"right: """"9else"!cond """"9!?"!0ector-ref"W"right#"the-pi0ot#"right:

Velse /)ind2new2right 4 the2pi+ot le)t /sub( right00W0W00 Figure 1!1' Rearranging a +ector )ragment into two partitions Figure (5( contains the complete de)inition o) partition! partition-a.*! and findnew-rightE the )unction swap is de)ined in )igure (&;, The de)inition o) the search )unction uses an unusual structural recursion based on subclasses o) natural numbers whose limits are parameters o) the )unction, Because the search )unctions are based on a rarel$ used design recipe! it is best to design them separatel$, Still! the$ are use)ul onl$ in the conte8t o) partition! which means that the$ should be integrated into its de)inition when their design is completed, E ercise #!<1<#< Complete the de)inition o) find-new-+eft, The two de)initions ha+e the same structureE de+elop the common abstraction, Ase the de)initions o) find-new-right and find-new-+eft to pro+ide a termination argument )or partition-a.*,

Ase the e8amples to de+elop tests )or partition, Recall that the )unction computes the proper place )or the pi+ot item and rearranges a )ragment o) the +ector, Formulate the tests as boolean2+alued e8pressions, 1hen the )unctions are properl$ tested! integrate find-new-right and find-new-+eft into partition and eliminate super)luous parameters, Finall$! test )sort and produce a single )unction de)inition )or the in2place ?uic.2sort algorithm, Solution E ercise #!<1<$< De+elop the )unction 0ector-re0erseD, It in+erts the contents o) a +ectorE its result is the modi)ied +ector,

>int' Swap items )rom both ends until there are no more items to swap,

Solution

E ercise #!<1<&< #conomists! meteorologists! and man$ others consistentl$ measure +arious things and obtain time series, All o) them need to understand the idea o) DDn2 item a+eragesCC or DDsmoothing,CC Suppose we ha+e wee.l$ prices )or some bas.et o) groceries: (,(' (,(& (,'< (,'> (,(( Computing the corresponding three2item a+erage time series proceeds as )ollows:

There are no a+erages )or the end points! which means a series with $ items turns into $ - & a+erages, De+elop the )unction +ist-3-a0erage! which computes the 52item sliding a+erages o) a list o) numbers, That is! we represent a series o) grocer$ prices with lists! and +ist-3a0erages consumes a list such as
!+ist"1.1%"1.12"1.%$"1.%,"1.11#

and produces
!+ist"1.1%"32,/3%%"$2/75#

in return,

De+elop the )unction 0ector-3-a0erages! which computes the 52item sliding a+erages o) a +ector o) numbers, Since +ectors are mutable! this gi+es us the alternati+e o) producing a new +ector or mutating the e8isting one, De+elop both +ersions o) the )unction: one that produces a new +ector and another one that mutates the +ector it is handed, @arning: This is a di))icult e8ercise, Compare all three +ersions and the comple8it$ o) designing them, Solution E ercise #!<1<(< All the e8amples in this section deal with +ector )ragments! that is! inter+als o) natural numbers, Processing an inter+al re?uires a starting point )or an inter+al! an end point! and! as the de)initions o) find-new-right and find-new-+eft show! a direction o) tra+ersal, In addition! processing means appl$ing some )unction to each point in the inter+al, Here is a )unction )or processing inter+als:
66"for-inter0a+":""N"!N""-/""N#"!N""-/""N#"!N""-/""R#""-/""R 66"to"e0a+.ate"!action"i"!0ector-ref"W"i##"for"i<"!step"i#<"... 66".nti+"!endA"i#"ho+ds"!inc+.si0e# 66"generati0e"rec.rsion:"step"generates"new"0a+.e<"endA"detects end 66"termination"is"not"g.aranteed" !define"!for-inter0a+"i"endA"step"action# ""!cond """"9!endA"i#"!action"i#: """"9else"!begin """"!action"i# """"!for-inter0a+"!step"i#"endA"step"action#:###

It consumes a starting inde8! called i! a )unction )or determining whether the end o) the inter+al has been reached! a )unction that generates the ne8t inde8! and a )unction that is applied to each point in between, Assuming !endA"!step"!step"..."!step i#"...### holds! for-inter0a+ satis)ies the )ollowing e?uation:
""!for-inter0a+"i"endA"step"action# &"!begin"!action"i# """""""""!action"!step"i## """""""""... """""""""!action"!step"!step"..."!step"i#"...####

Compare the )unction de)inition and the e?uation with those )or map, 1ith for-inter0a+ we can de+elop /some0 )unctions on +ectors without the traditional detour through an au8iliar$ )unction, Instead! we use for-inter0a+ the wa$ we used map )or processing each item on a list, Here is a )unction that adds 1 to each +ector )ield:
66"increment-0ec-r+":"!0ector"n.m8er#""-/""0oid

66"effect:"to"increment"each"item"in"W"82"1 !define"!increment-0ec-r+"W# ""!for-inter0a+"!s.81"!0ector-+ength"W##"@eroA"s.81" """"""""""""""""!lambda"!i# """"""""""""""""""!0ector-setD"W"i"!+"!0ector-ref"W"i#"1#####

It processes the inter+al V%!!s.81"!0ector-+ength"W##W! where the le)t boundar$ is determined b$ @eroA! the termination test, The starting point! howe+er! is !s.81 !0ector-+ength"W##! which is the right2most legal +ector inde8, The third argument to for-inter0a+! s.81! determines the tra+ersal direction! which is )rom right to le)t! until the inde8 is %, Finall$! the action is to mutate the contents o) the i2th )ield b$ adding 1, Here is a )unction with the same +isible e))ect on +ectors but a di))erent processing order:
66"increment-0ec-+r":"!0ector"n.m8er#""-/""0oid 66"effect:"to"increment"each"item"in"W"82"1 !define"!increment-0ec-+r"W# ""!for-inter0a+"%"!lambda"!i#"!&"!s.81"!0ector-+ength"W##"i##"add1 """"""""""""""""!lambda"!i# """"""""""""""""""!0ector-setD"W"i"!+"!0ector-ref"W"i#"1#####

Its starting point is % and the end point is the right2most legal inde8 o) W, The add1 )unction determines that the +ector is processed )rom le)t to right, De+elop the )ollowing )unctions! using for-inter0a+: (, rotate-+eft! which mo+es all items in +ector into the adFacent )ield to the le)t! e8cept )or the )irst item! which mo+es to the last )ieldE &, insert-i-S! which mo+es all items between two indices i and S to the right! e8cept )or the right2most one! which gets inserted into the i2th )ield /cmp, )igure (&<0E 5, 0ector-re0erseD! which swaps the le)t hal) o) a +ector with its right hal)E 6, find-new-right! that is! an alternati+e to the de)inition in )igure (5(E 7, 0ector-s.mD! which computes the sum o) the numbers in a +ector using set! />int' see section 5;,50, The last two tas.s show that for-inter0a+ is use)ul )or computations that ha+e no +isible e))ects, @) course! e8ercise &>,5 shows that there is no need )or a clums$ )ormulation such as 0ector-s.mD,

1hich o) these )unctions can be de)ined in terms o) 0ec-for-a++ )rom e8ercise 6(,&,(;H ,ooping Constructs: Man$ programming languages /must0 pro+ide )unctions li.e forinter0a+ as built2in constructs! and )orce programmers to use them )or processing +ectors, As a result! man$ more programs than necessar$ use set! and re?uire comple8 temporal reasoning, Solution

)(#" Collections of Structures !ith Cycles


Man$ obFects in our world are related to each other in a circular manner, 1e ha+e parentsE our parents ha+e children, A computer ma$ connect to another computer! which in turn ma$ connect to the )irst, And we ha+e seen data de)initions that re)er to each other, Since data represents in)ormation about real2world obFects! we will encounter situations that call )or the design o) a class o) structures with a circular relationship, In the past! we ha+e s.irted the issue! or we used a tric. to represent such collections, The tric. is to use an indirection, For e8ample! in section &<,(! we associated each structure with a s$mbol! .ept a table o) s$mbols and structures around! and placed s$mbols into structures, Then! when we needed to )ind out whether some structure re)ers to another! we e8tracted the rele+ant s$mbol and loo.ed in the table to )ind the structure )or the s$mbol, 1hile this use o) indirection allows us to represent structures with mutual re)erences or structures in a c$clic relationship! it also leads to aw.ward data representations and programs, This section demonstrates that we can simpli)$ the representation o) collections with structure mutation, To ma.e this idea concrete! we discuss two e8amples: )amil$ trees and simple graphs, Consider the case o) )amil$ trees, Thus )ar! we ha+e used two .inds o) )amil$ trees to record )amil$ relationships, The )irst is the ancestor treeE it relates people to their parents! grandparents! and so on, The second is the descendant treeE it relates people to their children! grandchildren! and so on, In other words! we ha+e a+oided the step o) combining the two )amil$ trees into one! the wa$ it is done in the real world, The reason )or s.irting the Foint representation is also clear, Translated into our data language! a Foint tree re?uires that a structure )or a )ather should contain the structures )or his children! and each o) the child structures should contain the )ather structure, In the past! we couldnCt create such collections o) structures, 1ith structure mutations! we can now create them, Here is structure de)inition that ma.es this discussion concrete:
!define-struct"person"!name"socia+"father"mother"chi+dren##

The goal is to create )amil$ trees that consist o) person structures, A person structure has )i+e )ields, The content o) each is speci)ied b$ the )ollowing data de)inition:

An fami!y-tree-node /short: ftn0 is either (, fa+se or &, a person, A person is a structure: where n is a s$mbol! s is
!ma-e-person"n"s"f"m"c# number! f and m are ftns! and c is

a !listof"person#,

As usual! the fa+se in the de)inition o) fami+2"tree"nodes represents missing in)ormation about a portion o) the )amil$ tree, Asing ma-e-person alone! we cannot establish the mutual re)erence between a )amil$ tree node )or a )ather and his child, Suppose we )ollow an ancestral tree strateg$! that is! we create the structure )or the )ather )irst, Then we canCt add an$ child to the chi+dren )ield! because! b$ assumption! the corresponding structure doesnCt e8ist $et, Con+ersel$! i) we )ollow a descendant tree strateg$! we )irst create a structure )or all o) a )atherCs children! but those structures canCt contain an$ in)ormation about the )ather $et,

The /rele+ant0 tree a)ter the creation o) the structure )or 'L.dwig:

...and

a)ter the mutation o) the structure )or ''dam and '50e:

Figure 1!2' Adding a child 1hat this suggests is that a simple constructor )or this .ind o) data isnCt reall$ enough, Instead! we should de)ine a =#-#RA"IM#D C@-STRACT@R that not onl$ creates a person structure but also initiali*es it properl$ when possible, To de+elop this )unction! it is best to )ollow the real world! where upon the birth o) a child! we create a new entr$ in the )amil$ tree! record the childCs parents! and record in the e8isting parentsC entries that the$ ha+e a newborn, Here is the speci)ication )or Fust such a )unction:
66"add-chi+dD":"s2m8o+"n.m8er"person"person""-/""person 66"to"constr.ct"a"person"str.ct.re"for"a"new8orn" 66"effect:"to"add"the"new"str.ct.re"to"the"chi+dren"of"father"and mother !define"!add-chi+dD"name"soc-sec"father"mother#"...#

Its tas. is to create a new structure )or a newborn child and to add the structure to an e8isting )amil$ tree, The )unction consumes the childCs name! social securit$ number! and the structures representing the )ather and the mother, The )irst step o) the design o) add-chi+dD is to create the new structure )or the child:
!define"!add-chi+dD"name"soc-sec"father"mother# ""!local"!!define"the-chi+d """"!ma-e-person"name"soc-sec"father"mother"empt2### """"...##

This co+ers the )irst part o) the contract, B$ naming the structure in a local2e8pression we can mutate it in the bod$ o) the e8pression, The second step o) the design o) add-chi+dD is to add a bod$ to the local2e8pression that per)orms the desired e))ects:
!define"!add-chi+dD"name"soc-sec"father"mother# ""!local"!!define"the-chi+d """"!ma-e-person"name"soc-sec"father"mother"empt2### """"!begin """"""!set-person-chi+drenD"father """"""""""""""""""""!cons"the-chi+d"!person-chi+dren"father### """"""!set-person-chi+drenD"mother """"""""""""""""""""!cons"the-chi+d"!person-chi+dren"mother### """"""the-chi+d###

Since there are two speci)ied e))ects and since the purpose statement also speci)ies a result! the bod$ o) the local2e8pression is a begin2e8pression with three sube8pressions, The )irst mutates father! adding the-chi+d to the list o) children, The second mutates mother in an analogous manner, The last one produces the desired result, Figure (5& illustrates the e+aluation o) an application o) add-chi+dD:
!add-chi+dD"'L.dwig"3 """"""""""""!ma-e-person"''dam"..."..."...#" """"""""""""!ma-e-person"'50e"..."..."...##

The top2hal) shows the new structure )or 'L.dwig and how it re)ers to the father and mother structures, Just as in section (6,(! the picture uses arrows to relate the nodes o) a )amil$ tree, But now this choice isnCt Fust a con+enience! it is dictated b$ necessit$, As the bottom hal) o) the )igure shows! the structure mutation o) add-chi+dD modi)$ the chi+dren )ields o) the father and mother structure, The$ add an additional item to the list in this )ield! and this new item is the structure )or 'L.dwig, 1ithout arrows! we wouldnCt be able to draw this constellation o) structures because it is impossible to draw the two structures as nested in each other, 1ith add-chi+dD we can create )amil$ trees! one child at a time, 1hat we need to learn is how to design )unctions that process this new class o) )amil$ trees, In this case! we can almost alwa$s pic. one o) the two +iews that we used be)ore: the ancestor )amil$ tree or the descendant )amil$ tree, #ither +iew Fust ignores certain )ields in the structures, @nce we ha+e chosen a +iew! we design the desired )unctions )ollowing the .nown recipes, #+en i) we decide to use the bi2directional relations in the new )amil$ tree representation! designing a )unction is usuall$ simpl$ a matter o) )ormulating those au8iliar$ )unctions that correspond to the real2world )amil$ relationships and to compose them properl$, The )ollowing )ew e8ercises demonstrate these principles, E ercise #!<2<1< Modi)$ add-chi+dD so that it has the )ollowing contract:
66"add-chi+dD":"s2m8o+"n.m8er"ftn"ftn""-/""person

The )unction otherwise beha+es Fust li.e the original +ersion, @nce we ha+e the modi)ied )unction! there is no need )or ma-e-person an$ more, 1e can create all )orms o) person structures with add-chi+dD directl$, Transliterate the )amil$ tree in )igure 57 into the new representationE use the new modi)ied add-chi+dD )unction e8clusi+el$, Solution E ercise #!<2<2< De+elop the )unction how-man2-ancestors! which consumes a )amil$ tree node and determines how man$ ancestors there are, The node itsel) counts as an ancestor, Solution E ercise #!<2<!< De+elop how-man2-descendants! which consumes a )amil$ tree node and determines how man$ descendants there are, The node itsel) counts as a descendant, Solution E ercise #!<2<#< De+elop names-of-co.sins, The )unction consumes a person and produces the names o) the cousins, >ints' /(0 DonCt )orget to use SchemeCs built2in )unctions )or processing lists, /&0 Ase a su))icientl$ large portion o) $our own )amil$ tree to test the )unctions, /50 For the testing step! compare the names o) the results o) the au8iliar$ )unctions with the e8pected results, Because the structures are mutuall$ re)erential! it is di))icult to compare them automaticall$, Alternati+el$! use e)A! SchemeCs intensional e?ualit$ predicate! to compare two structures, 1h$ does this wor.H Solution In sections &<,( and 5',&! we encountered the problem o) representing and tra+ersing graphs, Recall that a graph is a collection o) nodes and connections between nodes, The graph tra+ersal problem is to determine whether there is a route )rom a node labeled orig to one called dest, In a simple graph! each node has e8actl$ one one2wa$ connection to another node, @riginall$! we represented a graph as a list o) named nodes, I) one node was connected to another! the corresponding structure )or the )irst node contained the name o) the second node! not the node itsel), #8ercise 5',&,5 introduced a +ector2based representation, Still! all o) our representations used the indirection tric.! so that i) we wanted to mo+e )rom one node to another! we )irst had to loo. up the connection in a table, Asing structure mutation! we can eliminate this indirection and create structures )or nodes that contain each other! e+en i) the graph contains a c$cle, To understand how this

wor.s in a concrete manner! letCs discuss how to model simple graphs such as those in )igure <7 and how to design programs that )ind routes through such graphs, First! we need a structure de)inition )or nodes:
!define-struct"node"!name"to##

The name )ield records the name o) the node! and the to )ield speci)ies to which other node it is connected, Second! we need a data de)inition: A simp!e-graph-node /node0 is a structure:
!ma-e-node"n"t#

where n is a s$mbol and t is a node, The data de)inition is unusual in that it is sel)2re)erential! but it doesnCt consist o) se+eral clauses, This immediatel$ raises the ?uestion o) how we can construct a node that complies with this de)inition, Clearl$! appl$ing ma-e-node doesnCt wor.E instead! we need to de)ine a generali*ed constructor that immediatel$ sets the to )ield o) a node, The generali*ed constructor consumes the atomic data )or a node structure and constructs a legal node structure )rom there:
66"create-node":"s2m8o+""-/""node 66"to"create"a"simp+e"+ega+"graph"node"with"a-name"in"the"name fie+d !define"!create-node"a-name# ""!local"!!define"the-node"!ma-e-node"a-name"fa+se###"...##

The natural candidate to place into the to )ield is the node itsel), In other words! the generali*ed constructor creates a node that contains itsel):
66"create-node":"s2m8o+""-/""node 66"to"create"a"simp+e"graph"node"that"contains"a-name"and"itse+f !define"!create-node"a-name# ""!local"!!define"the-node"!ma-e-node"a-name"fa+se### """"!begin """"""!set-node-toD"the-node"the-node# """"""the-node###

The generali*ed constructor ma.es the node using the ordinar$ constructor! initiali*ing the name )ield properl$ and putting fa+se into the to )ield, Although the latter is an improper action according to our data de)inition! it is acceptable because it is immediatel$ corrected in the local2e8pressionCs bod$, Hence an application o) createnode produces a node as promised, 1ith create-node we can create the nodes in a graph! but we canCt establish the connections between them, To connect two nodes! we must modi)$ the to )ield o) one o) the structures so that it contains the other, 1hile this suggestion is generall$ on target! it raises the problem o) how to identi)$ the nodes, The )amil$ tree e8ample suggests one solution! namel$! to introduce one +ariable de)inition per node, Another

comes )rom our orginal wor. with graphs! where we represented graphs as lists o) s$mbolic pairs o) connections or lists o) nodes or +ectors o) nodes, Here we pursue the second option: A simp!e-graph is a !listof"node#, Assuming we ha+e a list o) all nodes! sa$ the-graph! and a )unction )or loo.ing up the node with a gi+en name! sa$ +oo-.p-node! we can create a connection )rom one node to the other with a structure mutation:
!set-node-toD"!+oo-.p-node"from-name"the-graph# """"""""""""""!+oo-.p-node"to-name"the-graph##

1e can ma.e connecting two nodes more con+enient than that with an au8iliar$ )unction:
66"connect-nodes":"s2m8o+"s2m8o+"graph""-/""0oid 66"effect:"to"m.tate"the"to"fie+d"in"the"str.ct.re"with 66"from-name"in"the"name"fie+d"so"that"it"contains 66"the"str.ct.re"with"to-name"in"the"name"fie+d !define"!connect-nodes"from-name"to-name"a-graph# ""!set-node-toD"!+oo-.p-node"from-name"a-graph# """"""""""""""""!+oo-.p-node"to-name"a-graph###

De)ining +oo-.p-node is an e8ercise in structural )unction design! though it is best done using SchemeCs assf )unction! which abstracts this situation,

66"create-node":"s2m8o+""-/""node 66"to"create"a"simp+e"graph"node"that"contains"itse+f !define"!create-node"name# ""!local"!!define"the-node"!ma-e-node"name"fa+se### """"!begin """"""!set-node-toD"the-node"the-node# """"""the-node### 66"connect-nodes":"s2m8o+"s2m8o+"graph""-/""0oid 66"effect:"to"m.tate"the"to"fie+d"in"the"str.ct.re"named" 66"from-name"so"that"it"contains"the"str.ct.re"named"to-name !define"!connect-nodes"from-name"to-name"a-graph# ""!set-node-toD"!+oo-.p-node"from-name"a-graph# """"""""""""""""!+oo-.p-node"to-name"a-graph### 66"+oo-.p-node":"s2m8o+"graph""-/""node"or"fa+se 66"to"+oo-.p".p"the"node"named"*"in"a-graph !define"!+oo-.p-node"*"a-graph#" ""...# 66"the-graph":"graph 66"the"+ist"of"a++"a0ai+a8+e"nodes" !define"the-graph ""!+ist"!create-node"''# """"""""!create-node"'(# """"""""!create-node"'7# """"""""!create-node"'D# """"""""!create-node"'5# """"""""!create-node"'>### 66"setting".p"the"graph:" !begin ""!connect-nodes"''"'("the-graph# ""!connect-nodes"'("'7"the-graph# ""!connect-nodes"'7"'5"the-graph# ""!connect-nodes"'D"'5"the-graph#

/connect2nodes =# =B the2graph00 Figure 1!!' Creating a simple graph +ia mutation -ow we can transliterate simple graphs into a Scheme representation, Suppose we start with the graph in )igure <7! which is reproduced here in a tabular )ormat: from A B C D # F to B C# # BF The )irst step is to create a list o) all the nodes and to name it, The second step is to establish the connections according to this table, Figure (55 shows the corresponding Scheme e8pressions, The$ are straight transliterations o) the columns in the tabular representation o) the graph, There is no need to reconnect the '> node because it is alread$ connected to itsel), E ercise #!<2<$< Draw a picture o) !create-node"''# using the bo8es2in2bo8es approach )rom part II and the bo8es2and2arrow approach )rom part III, Solution E ercise #!<2<&< Transliterate the gi+en simple graph without creating a list o) all nodes, Solution

E ercise #!<2<(< De+elop the )unction s2m8o+ic-graph-to-str.ct.res, It consumes a list o) pairs and creates a graph, #8ample:
!define"the-graph" ""!s2m8o+ic-graph-to-str.ct.res"'!!'"(#"!("7#"!7"5#"!D"5#"!5"(#"!> >####

#+aluating this de)inition is e?ui+alent to e+aluating the de)initions in )igure (55, Solution @nce we ha+e a method )or representing simple graphs! we can turn our attention to the problem o) )inding a route )rom one node in the graph to another, Recall the original speci)ication )rom section 5',&:
66"ro.te-e*istsA":"node"node"simp+e-graph""-/""8oo+ean 66"to"determine"whether"there"is"a"ro.te"from"orig"to"dest"in"sg !define"!ro.te-e*istsA"orig"dest"sg#"...#

@) course! we must reinterpret the names )or our data classes in the new conte8t! but otherwise the speci)ication is per)ectl$ )ine, The de+elopment o) the original )unction demonstrated two new ideas, First! the )unction uses generati+e recursion, @nce it is .nown that orig and dest are distinct nodes! the search resumes )rom the node to which orig is connected, Second! the )unction re?uires an accumulator to remember which nodes ha+e been +isited, 1ithout the accumulator! the )unction ma$ re+isit the same node o+er and o+er again, So! letCs start )rom the template )or generati+e recursion:
!define"!ro.te-e*istsA"orig"dest"sg# ""!cond """"9!e)-nodeA"orig"dest#"tr.e: """"9else """""!ro.te-e*istsA"..."the"node"to"which"orig"is"connected"... dest"sg#:##

The )unction e)-nodeA determines whether the two nodes are the sameE this ma$ Fust use e)A! SchemeCs intentional e?ualit$ predicate! or it ma$ compare the names o) the nodes! assuming the$ are uni?ue, I) the nodes are the same! a route e8ists, I) not! we can generate a new! potentiall$ use)ul problem b$ mo+ing to the node to which orig is connected, In the graph representation o) section 5',&! this re?uires loo.ing in sg, In our new graph representation! the connection is a part o) the node representation, Hence we can use node-to instead o) loo.ing in sg:
!define"!ro.te-e*istsA"orig"dest"sg# ""!cond """"9!e)-nodeA"orig"dest#"tr.e:

""""9else"!ro.te-e*istsA"!node-to"orig#"dest"sg#:##

The )unction de)inition shows that! so )ar! sg is useless, Because a node in the new graph representation contains its neighbors! and the neighbor contains its neighbor! and so on! there is no need to use the table, The termination argument )or this )unction )ails! Fust as )or the original one in section 5',&, To see wh$ our new )unction ma$ )ail to terminate! ta.e a loo. at its de)inition, It doesnCt contain fa+se! and the )unction cannot possibl$ produce fa+se 22 e+en though we .now that our sample graph! )or e8ample! doesnCt contain a path )rom '> to '' or an$where else, I) we inspect what happens with
!ro.te-e*istsA"!+oo-.p-node"the-graph"'>#" """""""""""""""!+oo-.p-node"the-graph"''##

we see that ro.te-e*istsA repeatedl$ +isits the node '>, In short! it )orgets what it has processed so )ar, 1e .now that e?uipping ro.te-e*istsA with an accumulator o+ercomes this lac. o) .nowledge! but that re?uires another table loo.up, 1e can do better than that with a structure mutation that records a +isit b$ the ro.te-e*istsA )unction, To do that! the node structures need an addtional )ieldE we call it 0isited:
!define-struct"node"!name"0isited"to##

Initiall$ the )ield contains fa+se, As ro.te-e*istsA +isits a node! it puts tr.e into the )ield:
!define"!ro.te-e*istsA"orig"dest"sg# ""!cond """"9!e)-nodeA"orig"dest#"tr.e: """"9!node-0isited"orig#"fa+se: """"9else """"""!begin !set-node-0isitedD"orig"tr.e# !ro.te-e*istsA"!node-to"orig#"dest"sg##:##

To e8ploit this new .nowledge! the )unction chec.s the new structure )ield as one o) the new termination conditions, I) orig has been +isited be)ore! there is no route because the )unction has disco+ered a c$cle in the graph, The second structure mutation o) this e8ample illustrates two ideas, First! structure mutation can replace a table2based accumulator, In general! though! it is best to stud$ a table2based +ersion and to add structure mutations based on a solid understanding o) the accumulated .nowledge, Second! structure mutations can pla$ a role in termination tests )or generati+e recursion, A)ter all! state change is moti+ated b$ the desire to remember things across )unction applications! and termination tests must disco+er whether things ha+e changed, 1hile the combination is rare! it is use)ul! and it appears time and again in the stud$ o) algorithms,

E ercise #!<2<)< The )unction ro.te-e*istsA assumes that the 0isited )ields o) all the nodes are initiall$ fa+se, A single use o) the )unction! howe+er! sets some o) the )ields in a graph to tr.e, This implies that the )unction cannot be used twice in a row, De+elop a re+ised +ersion o) ro.te-e*istsA! with the same speci)ication! that sets all 0isited )ields to fa+se be)ore it searches )or a route between the gi+en nodes, Determine the abstract running time o) the new )unction! assuming the graph has / nodes, Solution E ercise #!<2<-< De+elop the )unction reacha8+e, It consumes a node in a simple graph, Its e))ect is to place tr.e into the 0isited )ields o) all those nodes that are reachable )rom the gi+en node and to ensure that the 0isited )ields o) all other nodes are fa+se, Solution E ercise #!<2<1.< De+elop ma-e-simp+e-graph! a )unction that manages the state o) a locall$ de)ined graph, The )unction accepts a simple graph in the )orm o) lists o) pairs o) s$mbols: !listof"!+ist"s2m8o+"s2m8o+##, It supports )our ser+ices: (, adding nodes that are connected to alread$ e8isting nodes /b$ name0E &, changing the connection o) a node /b$ name0E 5, determining whether a route between two nodes e8istsE 6, and remo+ing nodes that are not reachable )rom some gi+en node, >int' Instead o) using a list! the manager should use a node se?uence! which is analogous to the hand structure )rom section 6(,5, A node se?uence relies on the )ollowing structure:
!define-struct"se).ence"!node"ne*t##

A se?uence is similar to a list! but it supports structure mutations,

Solution

The discussion o) this section con)irms the use)ulness o) the design recipes! e+en )or collections o) structures that re)er to each other, The most important lesson is that such situations call )or a generali*ed constructor! a )unction that creates a structure and immediatel$ establishes the necessar$ connections, =enerali*ed constructors correspond to the initiali*ers o) section 57E we ha+e also seen the idea in section 6(,5 where we

created a hand )rom a single card, In some cases! such as the one )or simple graphs! we ma$ also want to introduce au8iliar$ )unctions )or mutating the structures a second time, @nce we ha+e those )unctions! we can use the standard recipes! including those )or introducing additional structure )ields,

)(#( Backtracking !ith State


Section &< introduced algorithms that bac.trac., An algorithm is a recursi+e )unction that generates new problems )or the recursi+e step rather than using the pieces o) its input data, @n occasion! an algorithm ma$ ha+e to ma.e choices among se+eral branches on the path to a solution, Some o) them ma$ lead nowhere, In such cases! an algorithm can bac.trac., That is! it can restart the search )or a solution with a di))erent branch to chec. i) it succeeds, 1hen the data representation )or a problem uses structures or +ectors! a bac.trac.ing algorithm can use structure mutation to test di))erent approaches to a solution, The .e$ is to design a pair o) )unctions that change the state o) the problem representation and that undo such a change in case the attempt )ails, In this section! we discuss two e8amples o) this .ind: the Bueens pu**le and the Peg Solitaire problem, Recall the Bueens pu**le )rom section &<,&, The goal o) the pu**le is to place n ?ueens on some board o) arbitrar$ si*e m2b$2m such that the ?ueens do not threaten each other, A ?ueen in chess threatens all places on the row! the column! and the two diagonals going through her own position, Figure ;> illustrates the notion with a single ?ueen on an <2b$2< board, In section &<,&! we represented chessboards with lists, 1hen we got to .now +ectors! we also de+eloped a +ector2based representation in e8ercise &>,5,(6! as )ollows:
66"'"chess!*oard"7("is"a"!vectorof"!vectorof"8oo+ean## 66"s.ch"that"a++"0ectors"ha0e"the"same"si@e. 66"ma-e-chess-8oard":"N""-/""7( !define"!ma-e-chess-8oard"m# ""!8.i+d-0ector"m"!lambda"!i#"!8.i+d-0ector"m"!lambda"!S# tr.e#####

The initial +alue o) tr.e indicates that it is still legitimate to place a ?ueen on the corresponding )ield, The ?ueen2placement algorithm places a ?ueen on one o) the a+ailable )ields on the gi+en board and creates a new board that re)lects the addition o) the ?ueen, This step is repeated until there are no more ?ueens to be placed! in which case the pu**le is sol+ed! or until there are no more places to choose )rom, In the second case! the algorithm bac.trac.s, That is! the algorithm remo+es the last ?ueen that was added and chooses some other a+ailable )ield, I) there are no more )ields! it bac.trac.s )urther, The algorithm signals a complete )ailure when it becomes impossible to bac.trac.,

@n one hand! creating a new board at each stage is acceptable because the chosen )ield ma$ turn out to be the wrong one in which case the old board is the starting point )or the ne8t step, @n the other hand! a human pla$er is more li.el$ to place the ?ueen on the board and to remo+e it i) the position turns out to be a bad choice, Thus the Bueens problem is an e8ample o) where the abilit$ o) computer programs to create man$ alternati+e DDworldsCC clashes with the human world! which o))ers e8tremel$ limited possibilities o) this .ind;< and thus restricts human imagination, Still! it is worth e8ploring how the addition o) +ector mutation to our +ocablular$ enables us to mimic the actions o) a human pla$er more closel$ than be)ore, E ercise #!<!<1< Placing an additional ?ueen on a chessboard means that some o) the )ields on the chessboard ha+e to be set to fa+se because the$ are now threatened and no longer a+ailable )or )uture placements o) ?ueens, The placement o) a ?ueen is a )unction o) the gi+en chessboard and the indices o) the new ?ueen:
66"p+ace-).een":"7("N"N""-/""0oid 66"effect:"to"set"those"fie+ds"in"7("to"fa+se"that"are"threatened 82" 66"a").een"on"row"i<"co+.mn"S !define"!p+ace-).een"7("i"S#"...##

>ints' /(0 Recall threatenedA )rom e8ercise &<,&,5, /&0 Consider de+eloping an abstract )unction )or processing all items on a board, The )unction is analogous to 0ecfor-a++ )rom e8ercise 6(,&,(;, Solution E ercise #!<!<2< De+elop .np+ace-).een, The )unction remo+es a ?ueen and its threats )rom a chessboard:
66".np+ace-).een":"7("N"N""-/""0oid 66"effect:"to"set"those"fie+ds"in"7("to"fa+se"that"were"threatened 82" 66"a").een"on"row"i<"co+.mn"S !define"!.np+ace-).een"7("i"S#"...##

=i+en an$ chessboard 7(! the )ollowing e?uation holds:


""!begin" """"!p+ace-).een"7("i"S# """"!.np+ace-).een"7("i"S# """"7(# &"7(

)or all legal positios i and S, 1h$ is this not true i) we swap the )irst two sube8pressionsH Solution E ercise #!<!<!< Modi)$ the solution o) the Bueens problem in section &<,& to use the +ector2based representation o) chessboards and the )unctions p+ace-).een and .np+ace-).een )rom e8ercises 65,5,( and 65,5,&, Solution

E ercise #!<!<#< Ase the draw.ss teachpac. to de+elop a +iew )or the Bueens problem, Recall that a +iew is a )unction that illustrates certain aspects o) a problem in a graphical manner, The natural solution here is to displa$ the intermediate stages o) the solution process according to the algorithm o) e8ercise 65,5,5! including the bac.trac.ing steps, Solution In section 5&,5 we discussed the Peg Solitaire problem, The goal o) the game is to eliminate the pegs one b$ one! until onl$ one peg is le)t, A pla$er can eliminate a peg i) one o) the neighboring holes is unoccupied and i) there is a peg in the hole in the opposite direction, In that case! the second peg can Fump o+er the )irst one and the )irst one is eliminated, Just as with the Bueens pu**le! we can represent the problem state with +ectors and indicators )or pegs and holes, In the real world! mo+ing a peg corresponds to a ph$sical action that changes the state o) the board, 1hen a pla$er bac.trac.s! the two pegs are placed bac. in their original positions, E ercise #!<!<$< Design a +ector representation )or the triangular peg solitaire board, De+elop a )unction )or creating a board with a single hole, Solution E ercise #!<!<&< Design a data representation )or a mo+e in the Peg Solitaire problem, De+elop a )unction )or ma.ing a mo+e, De+elop a )unction )or undoing a mo+e, The two )unctions should rel$ e8clusi+el$ on e))ects, Do the )unctions satis)$ an e?uation analogous to p+ace-).een and .np+ace-).een in e8ercise 65,5,&H Solution E ercise #!<!<(< De+elop a bac.trac.ing algorithm )or sol+ing a Peg Solitaire problem whose hole is placed randoml$, Solution E ercise #!<!<)< Ase the draw.ss teachpac. to de+elop a +iew )or the Peg Solitaire problem, Recall that a +iew is a )unction that illustrates certain aspects o) a problem in a graphical manner, The natural solution here is to displa$ the intermediate stages o) the solution process according to the algorithm o) e8ercise 65,5,;! including the bac.trac.ing steps, Solution

A program could set up an entirel$ new board )or e+er$ new stage in the algorithm and search )or solutions in parallel, The additional wor. is! howe+er! prohibiti+e )or a human being! which is wh$ humans sh$ awa$ )rom such simulations,
;<

Epilogue
:86@ I mean% -hat e+act!y do yo do( *L,4):@ #e $eep to o r s a! st ff% more or !ess% on!y inside o t" #e do on stage things that are s pposed to happen off" #hich is a $ind of integrity% if yo !oo$ on every e+it as being an entrance some-here e!se" 22 Tom Stoppard! :osencrant' and > i!denstern are 0ead 1e ha+e reached the end o) this introduction to computing and program design, 1hile there is more to learn about both subFects! this is a good point to stop! to summari*e! and to loo. ahead,

Computing
From elementar$ school to high school we learn to compute with one )orm o) data: numbers, @ur )irst use o) numbers is to count real things! sa$! three apples! )i+e )riends! twel+e bagels, "ater we use numbers without an$ appeal to concrete obFects! but we ha+e learned that numbers represent in)ormation in the real world, Computing with so)tware is a!gebra for a!! $inds of data! not Fust numbers, -owada$s! computer programs process representations o) music! molecules! law cases! electrical diagrams! architectures o) houses! and poems, Fortunatel$! we ha+e learned to represent in)ormation with other )orms o) data than Fust numbers, @therwise! computing and programming would become e8tremel$ tedious tas.s, Abo+e all! we shouldnCt )orget that computing means manipulating data through proper basic operations, Some operations create new +alues, @thers e8tract +alues )rom +alues, 3et others modi)$ +alues, Finall$! there are also basic operations )or determining to which class a piece o) data belongs, Built2in operations and )unctions are o) course Fust another class o) data, De)inition is +alue creationE application is a )orm o) +alue e8traction,;> 1hen we de)ine a )unction! we combine basic data operations, There are two )undamental mechanisms )or combining )unctions: )unction composition and

conditional e8pressions, The )ormer means that the result o) one )unction becomes the argument o) another one, The latter represents a choice among se+eral possibilities, 1hen we e+entuall$ appl$ a )unction! we trigger a computation, In this boo. we ha+e studied the laws o) basic operations and the laws o) operation combination, Asing these laws we can understand! in principle! how an$ )unction processes its input data and how it produces its results and e))ects, Because the computer is e8tremel$ )ast and good at using these laws! it can per)orm such e+aluations )or more data and )or larger programs than we can do with paper and pencil,

Programming
Programs consist o) de)initions and e8pressions, "arge programs consist o) hundreds and thousands o) de)initions and e8pressions, Programmers design )unctions! use other programmerCs )unctions! lea+e! start on the proFect, 1ithout a strong discipline we cannot hope to produce so)tware o) high ?ualit$, The .e$ to programming discipline is to understand the design o) programs as a means to describe computations! which! in turn! is to manipulate data through combinations o) basic operations, For that reason! the design o) e+er$ program 22 whether it is small and )or personal use or large and )or business use 22 must start with an anal$sis o) the surrounding world o) in)ormation and a description o) the classes o) data that represent the rele+ant in)ormation, I) the classes are unusual or new! we ma.e up e8amples so we understand the structure o) the class description, A)ter we understand the world o) in)ormation surrounding our proFect and its data representation! we ma.e a plan, A proFect plan identi)ies what data we wish to produce )rom the data that the program will be gi+en, In man$ cases! though! a program doesnCt process data in Fust one wa$ but in man$ wa$s, For e8ample! a program )or managing ban. accounts must handle deposits! withdrawals! interest calculations! ta8 )orm generation! and man$ other tas.s, In other cases! a program ma$ ha+e to compute comple8 relationships, For e8ample! a program )or simulating a ping2pong game must compute the mo+ement o) the ball! bounces on the table! bounces )rom the paddle! paddle mo+ements! etc, In either case! we need to describe what the +arious wa$s o) processing data are and how the$ relate to each other, Then we ran. them and start with the most important one, 1e de+elop a wor.ing product! ma.e sure that it meets our speci)ications! and re)ine the product b$ adding more )unctions or ta.ing care o) more cases or both, Designing a )unction re?uires a rigorous understanding o) what it computes, Anless we can describe its purpose and its e))ect with concise statements! we canCt produce the )unction, In almost all cases! it helps to ma.e up e8amples and wor. through the )unctionCs computation b$ hand, For complicated )unctions or )or )unctions that use generati+e recursion! we should include some e8amples with the purpose statements, The e8amples illustrate the purpose and e))ect statements )or others who ma$ ha+e to read or modi)$ the program,

Stud$ing e8amples tends to suggest the basic design recipe, In most cases! the design o) a )unction is structural! e+en i) it uses an accumulator or structure mutation, In a )ew others! we must use generati+e recursion, For these cases! it is important to e8plain the method )or generating new problems and to s.etch wh$ the computation terminates, 1hen the de)inition is complete! we must test the )unction, Testing disco+ers mista.es! which we are bound to ma.e due to all .inds o) reasons, The best testing process turns independentl$ de+eloped e8amples into test suites! that is! a bunch o) e8pressions that appl$ the )unction to select input e8amples and compare its results and e))ects with e8pected results and e))ects /mostl$0 automaticall$, I) a mismatch is disco+ered! the test suite reports a problem, The test suite should ne+er be discarded! onl$ commented out, #+er$ time we modi)$ the )unction! we must use the test suite to chec. that we didnCt introduce mista.es, I) we changed the underl$ing process! we ma$ ha+e to adapt the test suite mutatis mutandis, -o matter how hard we wor.! a )unction /or program0 isnCt done the )irst time it wor.s )or our test suite, 1e must consider whether the de+elopment o) the )unction re+ealed new interesting e8amples and turn such e8amples into additional tests, And we must edit the program, In particular! we must use abstraction properl$ to eliminate all patterns where+er possible, I) we respect these guidelines! we will produce decent so)tware, It will wor. because we understand wh$ and how it wor.s, @thers who must modi)$ or enhance this so)tware will understand it! because we include su))icient in)ormation on its de+elopment process, Still! to produce great so)tware! we must practice )ollowing these guidelines and also learn a lot more about computing and programming than a )irst boo. can teach,

/oving ;n
The .nowledge and design s.ills )rom this boo. are a good )oundation )or learning more about programming! computing! and e+en practical wor. on so)tware, First! the s.ills are good )or learning the currentl$ )ashionable collection o) obFect2oriented languages! especiall$ Ja+a, The two languages share a philosoph$ o) programming, In both settings! computing means dealing with data! and programming means describing classes o) +alues and )unctions on them, Anli.e Scheme! howe+er! Ja+a re?uires programmers to spell out the class descriptions in Ja+a! not Fust in #nglish! and to place )unction de)initions with class descriptions, As a result! Ja+a re?uires programmers to learn a lot o) s$ntactic con+entions and is unsuitable as a )irst language, Second! a programmer must stud$ the )undamental ideas o) computing, Thus )ar! our studies ha+e )ocused on the laws o) computing )or data2oriented programming languages, Asing the programming s.ills )rom this boo.! we can design and implement a simulation o) how the hardware computes, B$ doing so we see the laws o) computing )rom a radicall$ di))erent perspecti+e, The contrast points to a number o) interesting ?uestions:

(, The two mechanisms o) computing are rather di))erent, Can one mechanism compute what the other one can compute and +ice +ersaH &, The laws we ha+e used are mathematical and abstract, The$ do not ta.e into account an$ real2world limitations, Does this mean that we can compute whate+er we wishH 5, The /simulated0 hardware shows that computers ha+e limitations, How do these limitations a))ect what we can computeH Research on these ?uestions created the discipline o) computing and still guides the design o) most computing curricula,

Full Scheme Finall$! the design .nowledge o) this boo. is enough to build some real2world programs in Scheme, DrScheme with its built2in 1eb browser and email capabilities is such a program, Building large real2world programs! howe+er! re?uires some more .nowledge about the )unctions that Scheme uses to create =AIs! to connect computers on a networ.! to script things such as shells! common gatewa$ inter)aces /C=I0! C@M obFects! and so on, Material on all three topics is a+ailable )rom this boo.Cs 1eb site in a )orm that e8tends the co+erage and the st$le o) the boo., The boo.Cs 1eb site is
http://www.htdp.org/

Chec. in with this site on a regular basis and continue to stud$ computing and programming,

An obFect in a language such as Ja+a is a )unction with man$ di))erent bodies, #ach method represents a di))erent wa$ o) e8tracting data )rom an obFect,
;>

Inde
A! V&W! V5W! V6W E

a-!ine aaa above above1 accumulator! V&W in+ariant add! V&W! V5W add-at-end add-chi!d! V&W add-to-address-boo$! V&W! V5W add-to-each add-to-pi add- p-3 address-boo$! V&W airp!ane algebra! V&W! V5W! V6W! V7W algorithm! V&W bac.trac.ing di+ide and con?uer tri+ial a!!-b! e-eyed-ancestors! V&W! V5W and! V&W! V5W! V6W andmap answer /cond0! V&W area area-of-dis$! V&W area-of-ring! V&W! V5W! V6W! V7W! V9W arguments arithmetic! V&W! V5W! V6W! V7W! V9W! V;W error e8act! V&W! V5W )i8ed2number ine8act! V&W! V5W arrangements ass) assignment atom atomic data

attendees! V&W au8iliar$ )unction

bac.trac.ing! V&W! V5W ba!!! V&W base case bbb begin be!o-! V&W! V5W be!o--ir1 be!o-1 be!o-3 beta /? 0 a8iom Big2@ binary-search-tree! V&W binary-tree! V&W! V5W b! e-eyed-ancestor! V&W b! e-eyed-chi!dren b! e-eyed-descendant! V&W board-ref! V&W board-setL bod$! V&W boolean boyfriend! V&W! V5W! V6W! V7W! V9W 16T 1T! V&W b i!d-board! V&W build2list build2number build2+ector

You might also like