Sunteți pe pagina 1din 431

An Introduction to Programming with Scala

By Mark Lewis

April 28, 2011

Preface
elome to en sntrodution to rogrmming with lF his ook is inE tended to e used in (rst nd seond semester ollege lssrooms to teh stuE dents eginning progrmming using the l lngugeF he ook ws onE struted with fous on the topis tht we wnt to get ross to students nd then we piked wht we thought ws the est wy to ommunite those idesF feuse there re two very di'erent udienes who might e reding thisD the rest of the prefe is split into two setionsF

To the Student
elome to the world of progrmmingF ou re out to emrk on (eld of study tht will hopefully open your mind to new wys of thinking nd impt the wy you view everything in the world round youF por students who intend to mjor in gomputer iene nd mke reers working with omputer tehnologyD this is your (rst step in lerning how to ommunite with the omputer nd to instrut the omputer in how it should solve prolems for youF por those who ren9t plnning to mke reer in omputing (eldD ourse in omputer progrmming n still e remrkly ene(ilF gomputer progrmming isD fundmentllyD out prolem solvingF st is out (guring out how to solve prolems nd express them in wys tht the omputer n understndF our entire future life isD in one wy or notherD going to del with how to solve prolemsF ou will need to hve pprohes to solving these prolems well formed in your own hed nd e le to ommunite them to other people in nonEmiguous wys so tht they understnd wht you wnt nd n t on itF verning to progrm omputers will help you develop or hone this ilityF here re more diret ene(ts s wellF he world you live in is lredy extremely dependent on omputingF wny of the things you own tht you don9t ll omputer inlude mirohips nd digitl proessingF hey run progrms to omplete their tsksF wny of the tsks you do through the dy re lso enled y omputer power nd the ility to proess nd store informtion quiklyF etivities like rowsing the we for work or leisure expliitly involve thisF yther tivities suh s (nnil trnstions mde with nything other thn sh only impliitly involve itF his uiquitous presene of digitl proessing is only going I

P to grow over timeF o even if you never hve to diretly write progrms s prt of your future lifeD you n only ene(t from hving n understnding of wht is going on under the hoodF iven if you don9t write the softwre yourselfD there is good hne tht you will intert with those who doD perhps s you or your ompny strives to gin ompetitive dvntge y improving the informtion tehnology you use to do your workF iven si knowledge of progrmming will help you understnd wht these people re doing nd ommunite more e'etively with themF ho knowsD even those who don9t intend to mke progrmming into reer might osionlly ome ross prolems where they relize tht they ould sve lot of time if they ould get omputer to do it for themF hen tht hppensD even si knowledge of progrmming n mke your life whole lot etterF

Using this Book


he gol of this ook is to help you in your e'orts to lern how to progrmF 333 red vs ieh

To the Instructor
here re mny di'erent pprohes nd mny di'erent lnguges tht you ould pik to use in your (rst yer of instrutionF hen looking t this ookD you might e sking yourself why you should use l nd the pproh tken hereF l is new progrmming lnguge nd prt of new reed of progrmming lnguges tht mixes prdigmsF l is puntionlEyjet lngugeF st is purely ojetEorientedF ell dt memers in it re ojetsF here re no primitivesF puntions in l re lso (rst lss vlues nd the lnguge hs strong support for funtionl style progrmming nd the expressivity tht omes with itF hose re prt of the gret resons why you should onsider l for dE vned progrmming lssesF roweverD this is n introdutory ookF hy does l lend itself to eginner progrmmersc o egin withD l supports multiple modes of intertionF st hs iv @edEivluteErint voopA enviE ronment where you n type in individul expressions nd hve them evlutedF st lso supports sripting style where ommnds re put into text (le nd the text (le is exeuted diretlyF vstlyD it gives you the ility to progrm lsses in (les tht re ompiled nd runD just like tvF his ook will exerise ll of these styles of intertionD uilding from one to the next s students develop greter pilities nd mturity with the lngugeF sn dditionD l is sttilly typed with lol type infereneF ypes re very signi(nt onept in progrmming nd stti typing helps students to understnd the notion of type nd see how it is used in progrmmingF ype inferene helps mke it so tht stti type heking doesn9t urden the lnguge s mny people who re used to more dynmi lnguges feel n often hppenF his omintion n lso e very useful erly in instrutionD espeilly when

Q used to full extent with the ivF ome of the (rst lessons in this ook del spei(lly with type nd how l determines the type of di'erent expresE sionsD using the iv environment to demonstrte this intertively nd let the student explore di'erent options themselvesF yne of the things tht drew mny people towrd tv s n introdutory progrmming lnguge ws the rod lirry supportD inluding options like qss nd grphisF l shres thisF sn ftD the primry implementtion of l ompiles to tw yteode nd l ode n semlessly ll tv lirriesF o nything you ould do with lirries in tvD you n do in l s well nd just s esily1 F e tke dvntge of tht midEwy through the (rst semester when we introdue students to qss nd grphisF e use it gin lter when we ring in networking nd other dvned pilitiesF es ws mentioned erlierD l is multiEprdigm lngugeF e ommon omplint is tht this mkes l more omplexF roweverD it truthD l hs fewer keywords thn most other lnguges nd the lnguge spei(tion for l is less thn hlf the length of the one for tv nd less thn (fth the length of truly omplex lnguge like gCCF ht l truly is isn9t omplexD ut )exileF st does ontin dvned fetures tht mke it very powerfulD ut those fetures ren9t needed to get strted nd in ftD some of them re held until n ppendix in this ook euse only lirry writers need ny detiled knowledge of how they workF he )exiility of l opens doors for those who re tehingF hile l is full ojet orientedD this ook does not fous on ojet orienttion initillyF snstedD the ook uses funtionl deomposition with mix of impertive nd funtionl styles for most of the (rst semesterF et the very end of the (rst semester students re introdued to full lss onstrution nd ojet deompoE sition of prolemsF ht is rried on in the seond hlf of the ook s students re introdued to lrger projet tht n trult ene(t from the tehniques of ojetEorienttionF

1 There

is also an implementation of Scala that compiles to the .NET CLR. While this book

uses the Java version, using the other version will give you access to the full .NET libraries.

Contents
I Introductory Concepts
1 Basics of Computers, Computing, and Programming
IFI IFP IFQ IFR IFS ristory F F F F F F F F F F F F F F F F F rrdwre F F F F F F F F F F F F F F F F oftwre F F F F F F F F F F F F F F F F xture of rogrmming F F F F F F F F rogrmming rdigms F F F F F F F F IFSFI smpertive rogrmming F F F IFSFP puntionl rogrmming F F F IFSFQ yjetEyriented rogrmming IFSFR vogi rogrmming F F F F F F IFSFS xture of l F F F F F F F F F nixGvinux gommnd vine F F PFIFI piles nd hiretories F PFIFP relpful ips F F F F F F PFIFQ ermissions F F F F F F PFIFR gompressionGerhiving PFIFS emote F F F F F F F F F PFIFT yther F F F F F F F F F F sGy ediretion F F F F F F F F ext iditors @viA F F F F F F F F l ools F F F F F F F F F F F ixpressionsD ypesD nd fsi yjets nd wethods F F F F yther fsi ypes F F F F F F fk to the xumers F F F F F he mth yjet F F F F F F F hetils of ghr nd tring F xming lues nd riles equentil ixeution F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

17
18
IV PH PP PR PT PU PU PV PW PW QH QP QT QU QW RI RP RQ RS RU

2 Getting to Know the Tools


PFI

PFP PFQ PFR QFI QFP QFQ QFR QFS QFT QFU QFV

F F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F

30

3 Scala Basics

wth F F F F F F F F F F F F F F F F F F F F F F F F F F F F

49

RW SQ SR SU TS TT TU UI

CONTENTS

S UP

QFW RFI RFP RFQ RFR RFS RFT RFU SFI SFP SFQ SFR SFS SFT SFU SFV TFI TFP TFQ TFR TFS UFI UFP UFQ UFR UFS

e ip for verning to rogrm F F F F F F F F F F F F F F F F F F F puntion efresher F F F F F F F F F F F F F F wking nd sing puntions F F F F F F F F rolem heomposition F F F F F F F F F F F puntion viterls F F F F F F F F F F F F F F F xonEpuntionl puntions F F F F F F F F F F righer yrder puntions F F F F F F F F F F F xmed nd hefult erguments @edvnedA wotivting ixmple F F F F F F F he if ixpression F F F F F F F F gomprisons F F F F F F F F F F F iqulity vsF sdentity @edvnedA foolen vogi F F F F F F F F F F figger ixpressions F F F F F F F F wthing F F F F F F F F F F F F F fitEwise erithmeti F F F F F F F fsis of eursion riting eursion ser input F F F F estrtion F F F F vooking ehed F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

4 Functions

75

US UT VI VQ VR VS VT

5 Conditionals

F WI F WP F WQ F WR F WS F WV F IHH F IHP F F F F F F F F F F F F F F F F F F F

91

6 Recursion for Iteration


F F F F

108

IHV IIH IIR IIV IPI

7 Arrays and Lists in Scala

wking errys F F F F F F F F F F sing errys F F F F F F F F F F F vists F F F F F F F F F F F F F F F F tndrd wethods F F F F F F F F e orld of ypes F F F F F F F F UFSFI he yption ype F F F F UFSFP rmetri puntions F F UFSFQ utyping F F F F F F F F UFT rile vength ergument vists UFU wutility nd elising F F F F F UFV fsi ergument ssing F F F F F UFW ssEfyExme F F F F F F F F F F UFIH pill nd ulte F F F F F F F F F UFII gomplete qrdes riptGoftwre

F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F hevelopment

126

IPT IPV IQP IQR IRQ IRR IRR IRT IRV ISH ISQ IST ISW ITI

CONTENTS

8 Loops
VFI VFP VFQ

VFR VFS VFT WFI WFP WFQ

while voop F F F F F F F F F F doEwhile voop F F F F F F F F for voop F F F F F F F F F F F VFQFI nge ype F F F F F F VFQFP yield F F F F F F F F F F VFQFQ if qurds F F F F F F F VFQFR wultiple qenertors F VFQFS rile helrtions wultidimensionl errys F F F esting F F F F F F F F F F F F F iews @edvned opiA F F F

F F F F F F F F F F F

F F F F F F F F F F F

F F F F F F F F F F F

F F F F F F F F F F F

F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

171

IUI IUQ IUR IUU IUV IUW IVH IVI IVI IVR IVT IWP IWQ IWS IWS IWT IWV IWW PHH PHI PHI PHI PHP PHQ PHQ PHR PHR PHS PIH PIH PII PII PIP PIQ PIQ PIW

9 Text Files

WFR WFS

sGy ediretion F F F F F F F F F F F F F kges nd smport ttements F F F eding from pile F F F F F F F F F F F WFQFI stertors F F F F F F F F F F F F F WFQFP tring plit wethod F F F F F F WFQFQ eding from yther hings F F WFQFR yther yptions @tv fsedA F F riting to pile F F F F F F F F F F F F F WFRFI eppending to pile F F F F F F F se gseX imple inryption F F F F F WFSFI gommnd vine erguments F F WFSFP wpping pile F F F F F F F F F WFSFQ ghrter y'set F F F F F F F F WFSFR elphet plip F F F F F F F F F F WFSFS uey ord F F F F F F F F F F F F WFSFT utting it ogether F F F F F F F WFSFU rimes nd el gryptogrphy F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

192

10 Case Classes

IHFI ser he(ned ypes F F F F F F F IHFP gse glsses F F F F F F F F F F F IHFPFI wking yjets F F F F F IHFPFP eessing ilements F F F IHFPFQ gopy wethod F F F F F F IHFQ wutle glsses F F F F F F F F IHFR utting it ogether F F F F F F F IHFS uple ipped ype @edvnedA

209

CONTENTS

11 GUIs

IIFI qs virries nd ristory F F F IIFP qs gomponents F F F F F F F F IIFPFI prmes nd indows F IIFPFP gomponents F F F F F F IIFPFQ nels nd nes F F F F IIFPFR wenus F F F F F F F F F F IIFPFS ooltips F F F F F F F F F IIFQ fsi sntertivity F F F F F F F IIFQFI rtil puntions F F F F IIFQFP ulishers nd etors IIFQFQ wnemonis F F F F F F F IIFR pile ghooser F F F F F F F F F F F IIFS les F F F F F F F F F F F F F F IIFSFI le etions F F F F F F IIFSFP le wodels F F F F F F IIFT utting it ogether F F F F F F F

F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

224

PPR PPS PPS PPU PPW PQR PQT PQT PQT PQU PQW PQW PRH PRQ PRS PRS PTH PTI PTP PTR PTT PTU PUI PUQ PUQ PUQ PUS PUT PUU PUU PUV PVH PVH PVI PVP PVQ PVV PVW PWI PWP PWQ

12 Graphics

IPFI gustom hrwn nels F F F F F F F F IPFP jvFwtFqrphisPh F F F F F F F F F IPFPFI hpes F F F F F F F F F F F F F IPFPFP ettings F F F F F F F F F F F F IPFPFPFI int F F F F F F F F IPFPFPFP troke F F F F F F F F IPFPFPFQ pont F F F F F F F F F IPFPFPFR glip F F F F F F F F F IPFPFPFS rnsform F F F F F IPFPFQ e0ne rnsforms F F F F F F IPFQ smges F F F F F F F F F F F F F F F F F IPFQFI fu'eredsmge F F F F F F F F IPFQFP eding nd riting smges IPFQFQ houle fu'ering F F F F F F F IPFQFR evisiting extureint F F F IPFR yther ivents F F F F F F F F F F F F F IPFRFI wouse ivents F F F F F F F F F IPFRFP ueyord ivents F F F F F F F IPFS enimtion with imer F F F F F F F F IPFT utting it ogether F F F F F F F F F F IQFI fsi gomprison orts F F F F F F IQFIFI fule ort F F F F F F F F F IQFIFP eletion ort @winGwxA F IQFIFQ snsertion ort F F F F F F F F IQFIFR esting nd erifying orts F F F F F

260

13 Sorting and Searching

288

CONTENTS

V F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F PWS PWU PWW QHH QHH QHP QHR QHS QHU QHU QHU QHU QHW QIP QIQ QIU

IQFP

IQFQ IQFR IQFS IQFT IQFU IQFV

IQFIFS ort isuliztion F F F F F F F F F IQFIFT yrder enlysis F F F F F F F F F F F IQFIFU hell ort @himinishing qp ortA erhing F F F F F F F F F F F F F F F F F F IQFPFI equentil erh @viner erhA IQFPFP finry erh F F F F F F F F F F F F IQFPFQ viner finry erh @edvnedA F IQFPFR erhing for houles @edvnedA elternte orts @edvnedA F F F F F F F F IQFQFI fuket ort F F F F F F F F F F F F F IQFQFP dix ort F F F F F F F F F F F F F erformne nd iming F F F F F F F F F F glssifying fugs F F F F F F F F F F F F F F wemory vyout F F F F F F F F F F F F F F F ortingGerhing with gse glsses F F F utting it ogether F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

14 XML and Patterns

IRFI wv F F F F F F F F F F F F F F F F F F F IRFIFI hesription of wv F F F F F F IRFIFIFI gs F F F F F F F F F F IRFIFIFP ilements F F F F F F F IRFIFIFQ ettriutes F F F F F F IRFIFIFR gontent F F F F F F F F IRFIFIFS peil ghrters F F IRFIFIFT gomments F F F F F F IRFIFIFU yverll pormt F F F F IRFIFP gomprison to plt pile F F F F IRFIFPFI plexiility in wv F F IRFIFQ wv in l F F F F F F F F F F IRFIFQFI voding wv F F F F IRFIFQFP rsing wv F F F F F IRFIFQFQ fuilding wv F F F F IRFIFQFR riting wv to pile IRFIFR hhs @edvnedA F F F F F F F IRFP tterns F F F F F F F F F F F F F F F F F IRFPFI rile finding F F F F F F F F IRFPFP gse glss tterns F F F F F F IRFPFQ wv tterns F F F F F F F F F IRFPFR tterns iverywhere F F F F F F IRFQ rimlity esting F F F F F F F F F F F F

321

QPI QPP QPP QPQ QPQ QPQ QPQ QPR QPR QPR QPR QPS QPT QPT QPW QQH QQH QQH QQH QQH QQH QQH QQI

CONTENTS

15 Sets, Maps, and Buers

ISFI ets F F F F F F F F F F F F F F F ISFIFI unning hrough ets F ISFIFP wutle vsF smmutle ISFIFQ sing et F F F F F F F ISFP wps F F F F F F F F F F F F F F F ISFPFI vooping hrough wp ISFPFP sing wps F F F F F F F ISFQ fu'ers F F F F F F F F F F F F F F ITFI ITFP ITFQ ITFR ITFS ITFT ower of eursion pioni xumers ermuttions F F F owers of rnoi F wzes F F F F F F F orts F F F F F F F F ITFTFI uik ort ITFTFP werge ort ITFU heme snterpreter F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F

333

QQQ QQR QQS QQU QQV QQW QRI QRQ

16 Recursion

348
QRV QRW QSI QSR QSR QSU QSV QSV QSW

II Object-Orientation, Abstraction, and Data Structures 362


17 Object-Orientation
IUFI fsis of yjetEyrienttion F F F F F F F F F F F F F F IUFIFI wethods nd wemers F F F F F F F F F F F F F IUFIFIFI erguments s wemers F F F F F F F IUFIFIFP isiility F F F F F F F F F F F F F F F IUFIFP peil wethods F F F F F F F F F F F F F F F F IUFIFPFI ypertor wethods F F F F F F F F F F IUFIFPFP nry ypertors F F F F F F F F F F F IUFIFPFQ roperty essignment wethods F F F IUFIFPFR he pply wethod F F F F F F F F F F IUFIFPFS he updte wethod F F F F F F F F F IUFIFPFT etor ixmple F F F F F F F F F F F IUFIFQ yjets F F F F F F F F F F F F F F F F F F F F F IUFIFQFI epplitions F F F F F F F F F F F F F IUFIFQFP sntrodution to gompnion yjets IUFIFR yjet heomposition F F F F F F F F F F F F F IUFP evisiting the es F F F F F F F F F F F F F F F F F F F IUFQ wening of gse glsses F F F F F F F F F F F F F F F F IUFR smport yptions F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

363

QTQ QTR QTS QTT QTW QTW QUP QUP QUQ QUR QUS QUT QUU QUV QUV QUW QUW QVI

CONTENTS

IH

18 Bigger Programs/New Tools

IVFI ilipse shi F F F F F F F F F F F F F F F F IVFP gonurrent ersions ystem @gA F F F IVFPFI wking the epository F F F F F F IVFPFP etEup in ilipse F F F F F F F F F IVFPFQ qetting eess on yther ystems IVFPFR epository sge nd ules F F F IWFI IWFP IWFQ IWFR IWFS IWFT oftwre hevelopment tges enlysis F F F F F F F F F F F F hesign F F F F F F F F F F F F F wking kges F F F F F F F isiility yptions F F F F F F F smplementing the qs F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F

F F F F F F F F F F F F

F F F F F F F F F F F F

F F F F F F F F F F F F

F F F F F F F F F F F F

F F F F F F F F F F F F

F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

387

QVU QWS QWS QWT QWU QWU

19 A Project (Drawing Program)

399

QWW RHH RHH RHI RHI RHI RHP RHP RHQ RHQ RHQ RHQ RHQ RHQ RHQ RHQ RHQ RHQ RHQ

20 Abstraction and Polymorphism

PHFI olymorphism F F F F F F F F F F F F F F F F F F F F F F PHFP snlusion olymorphism @snheritne nd utypingA PHFPFI roteted isiility F F F F F F F F F F F F F F F PHFPFP enonymous glsses F F F F F F F F F F F F F F PHFPFQ rits F F F F F F F F F F F F F F F F F F F F F F PHFPFR snheriting from puntion ypes F F F F F F F F PHFQ snheritne in the rojet F F F F F F F F F F F F F F F PHFR rmetri olymorphism F F F F F F F F F F F F F F F PHFRFI rmetri ypes F F F F F F F F F F F F F F F PHFRFP rmetri puntions F F F F F F F F F F F F F PHFRFQ ype founds F F F F F F F F F F F F F F F F F F PHFRFR rmetri righerEyrder puntions F F F F F F PHFS trutured ypes F F F F F F F F F F F F F F F F F F F F PIFI he wultiore puture F F F F F F F F F F PIFP fsi hreds F F F F F F F F F F F F F F F PIFPFI rolems with hreds F F F F F PIFPFIFI e gonditions F F F F PIFPFIFP hedlok F F F F F F F F PIFPFP ynhroniztion F F F F F F F F F PIFPFQ itGxotify F F F F F F F F F F F F PIFPFR yther hred wethods F F F F F PIFQ gonurreny virry F F F F F F F F F F F PIFQFI ixeutors nd ixeutor ervies PIFQFP gllle nd putures F F F F F F F PIFQFQ rllel ht trutures F F F F F PIFQFR etomi F F F F F F F F F F F F F F PIFQFS voks F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

402

21 Multithreading and Concurrency

404

RHS RHS RHS RHS RHS RHS RHS RHS RHS RHS RHS RHS RHS RHS

CONTENTS

II

PIFR wultithreding in qss F F F F F F F F F F F F F F F F F F F F F F F RHS PIFS wultithreded wndelrot F F F F F F F F F F F F F F F F F F F F F F RHS PIFT enimted founing flls F F F F F F F F F F F F F F F F F F F F F F RHS

22 Stream I/O

PPFI trems for piles F F PPFP ixeptions F F F F F PPFQ heorting trems F PPFQFI fu'ering F F PPFQFP finry ht PPFQFQ eriliztion F PPFR ving hrwings F F

F F F F F F F

F F F F F F F

F F F F F F F

F F F F F F F

F F F F F F F

F F F F F F F F F F F F

F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

407

RHU RHU RHU RHU RHU RHU RHU RHV RHV RHV RHV RHV

23 Networking

PQFI g nd h F F F F F F F F PQFP okets F F F F F F F F F F F F PQFPFI trems from okets PQFQ ghtting F F F F F F F F F F F F PQFR gollortive hrwing F F F F PRFI PRFP PRFQ PRFR PRFS PRFT PRFU PSFI PSFP PSFQ PSFR PSFS PSFT PSFU

408

24 Stacks and Queues

estrt ht ypes @ehsA F F ypertions on tks nd ueues el wening of y F F F F F F F F y@nA equirement F F F F F F F F erry fsed tk F F F F F F F F erry fsed ueue F F F F F F F F g glultor F F F F F F F F F F xture of vinked vists F F ingly vinked vist F F F F houly vinked vist F F F F stertors F F F F F F F F F F vinked vist fsed tk F vinked vist fsed ueue rle F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

409
RHW RHW RHW RHW RHW RHW RHW

25 Linked Lists

410

RIH RIH RIH RIH RIH RIH RIH RII RII RII RII RII

26 Priority Queues

PTFI wo epprohes F F F F F F F PTFIFI orted vinked vist F F PTFIFP erhing y riority F PTFP qrvity sntegrtion F F F F F F PTFQ rile imestep qrvity F F

411

CONTENTS

IP

27 Refactoring

PUFI mells F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F RIP PUFP eftorings F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F RIP PVFI efresher F F F F F F F F F F F F F F F F PVFP e wze in the hrwer F F F F F F F F F PVFPFI evisiting the fsi epproh PVFPFP enimting the olution F F F F PVFPFQ yptimizing the wze F F F F F F PVFPFR pormul rser F F F F F F F F F PWFI qenerl rees F F F F F F PWFIFI smplementtions PWFIFP rversls F F F F PWFP finry rees s wps F PWFPFI yrder enlysis F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

412

28 Recursion

413
RIQ RIQ RIQ RIQ RIQ RIQ

29 Trees

414

RIR RIR RIR RIR RIR

30 Regular Expressions and Context-Free Parsers


QHFI ghomsky qrmmrs F F F F F F F F F F F F QHFIFI egulr qrmmrs F F F F F F F F F QHFIFP gontextEpree qrmmrs F F F F F F QHFIFQ gontextEensitive qrmmrs F F F QHFIFR eursively inumerle qrmmrs QHFP egulr ixpressions F F F F F F F F F F F F QHFPFI ghrters nd ghrter glsses QHFPFP vogil ypertors F F F F F F F F F QHFPFQ foundry equirements F F F F F F QHFPFR qreedy unti(ers F F F F F F F F F QHFPFS qroups F F F F F F F F F F F F F F F QHFQ gontextEpree rsers F F F F F F F F F F F F QIFI udtrees nd ytrees F QIFP khErees F F F F F F F F F QIFQ i0ient founing flls QIFQFI sing qrid F F QIFQFP sing ree F F QIFR i0ient qrvity F F F F QPFI QPFP QPFQ QPFR F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

415

RIS RIS RIS RIS RIS RIS RIS RIS RIS RIS RIS RIS RIU RIU RIU RIU RIU RIU

31 Spatial Trees

F F F F F F F F F F

F F F F F F F F F F

417

32 Binary Heaps

xture of reps F F F F F F F F F F F reps s riority ueues F F F F F F repsort F F F F F F F F F F F F F F F F i0ient rile imestep qrvity F

418

RIV RIV RIV RIV

CONTENTS

IQ

33 Binary Files

QQFI ndom eess piles F F F F QQFIFI pixed eord vength QQFIFP sndexed F F F F F F F QQFP ikling F F F F F F F F F F F

F F F F

F F F F

F F F F

F F F F

F F F F

F F F F

F F F F

F F F F

F F F F

F F F F

F F F F

F F F F

F F F F

F F F F

F F F F

F F F F

F F F F

F F F F

F F F F

F F F F

F F F F

419
RIW RIW RIW RIW

34 Actors 35 Balanced Binary Trees

420 421

QSFI ekness of finry rees F F F F F F F F F F F F F F F F F F F F F F RPI QSFP evErees F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F RPI

36 Wrapping Up

QTFI ht ou rve verned F F F F F F F F F F F F F F F F F F F F F F F RPP QTFP he ossiilities F F F F F F F F F F F F F F F F F F F F F F F F F F F RPP QTFQ e et rojet F F F F F F F F F F F F F F F F F F F F F F F F F F F F F RPP

422

III Appendix Material


37 Quick Preview of Java 38 Advanced Scala Concepts

423
424 425

QVFI smpliits F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F RPS QVFP govrintD gontrvrintD nd snvrint F F F F F F F F F F F F F F RPS

39 Scala Syntax 40 Appendix B - Glossary

426 427

List of Figures
IFI wost si view of the von xeumnn shred memory rhitetureF e g nd the memory re onneted y usF he memory stores oth dt nd the progrms themselvesF he g n request informtion from memory or write to memory over the usF PI en exmple of vinux terminl with ommnd promptF F F F F sllustrtion of the onversion from deiml to inry using suE trtion methodF his method works from the top downF o get the numer in inry just red down the list of digitsF F F F F F F sllustrtion of the onversion from deiml to inry using the repeted division methodF his method works from the ottom up so you get the its in the result strting with the smllestF F higrm of generl sutype reltionships in lF his (gure hs een dpted from similr (gure in Programming in Scala y yderskyD poonD nd ennersF hile erry isn9t tully sutype of eqD it n e used s suh euse of impliit onverE sionD topi for lter in the ookF F F F F F F F F F F F F F F F F F F imple imge of memory lyout for few vrilesF he ojets on the right side re overly simpli(edD espeilly the listD ut this portrys su0ient detil for understnding wht is hppening t this pointF F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F wodi(ed view of the memory fter two vriles hve een sE signed di'erent vluesF F F F F F F F F F F F F F F F F F F F F F F F F ht the memory looks like fter the introdution of lP nd PF F he memory lyout from the getendgler sriptF he rguments pssed into the funtion eome lises for the ojets reted t the top level of the sriptF F F F F F F F F F F F F F F F F F F F F F F he on(gurtion of memory fter getendgler hs exeutedF F F QI

PFI QFI QFP

SV SW

UFI

UFP

IRU

UFQ UFR UFS UFT

ISI ISP ISQ ISR ISS

IIFI his is smple window rought up y simple sriptF he window is SHHxSHH pixels nd hs the title pirst qsF hen you lose the windowD the sript will exitF F F F F F F F F F F F F F PPT IR

LIST OF FIGURES

IS

IIFP his shows possile lyout for the qs tht we wnt to uild for editing reipesF F F F F F F F F F F F F F F F F F F F F F F F F F F PQI IIFQ his is the window produed y the ode to do the initil lyout of the reipe ookF F F F F F F F F F F F F F F F F F F F F F F F F F F PQR IPFI he result of doing simple drwet inside of pintF F F F F F F PTQ IPFP e smple drwing showing retngleD ellipseD rD nd qudrti urve mde with lls to (ll nd drwF F F F F F F F F F F F F F F F PTS IPFQ his (gure shows wht we get when we dd some pint settings to the drwing of shpes tht we hd eforeF F F F F F F F F F F F PTV IPFR his is wht the drwing looks like fter we hve dded some stroke settings for the two elements tht re drwn insted of (lledFPUH IPFS e simple exmple of writing string to grphisF F F F F F F F F F PUP IPFT his (gure shows wht hppens when we do rottion efore drwing our stringF F F F F F F F F F F F F F F F F F F F F F F F F F F PUS IPFU his imge displys the use of extureintF he ellipse is (lled with tiling of n imge tht is loded from diskF F F F F F F F F PUW ITFI his shows the ll stk for the funtion ount whih prints the numers ounting upF hen you ll the funtion with SD it lls itself with R without doing nything elseF his lls itself with Q nd so on down to HF he ll with H does nothing ut returnF st returns k into the ll to ount@IA tht does the print nd ontinues on k up the stkF F F F F F F F F F F F F F F F F F F F QSH ITFP his (gure shows ll tree for (@RAF foxes represent stk frmesF tright rrows point in the diretion of funtion llsF gurved rrows show returns nd re leled with return vluesF F QSP IUFI his is prt of the right pnel tht you see when you (rst enter the esF he little irles with the letters D oD nd t indite whether it is lssD ojetD or tritF F F F F F F F F F F F F F F F F QVH IVFI he welome sreen for ilipse tht you will see when you run it for the (rst timeF F F F F F F F F F F F F F F F F F F F F F F F F F F F IVFP e lnk ilipse workspeF his is wht you will strt with when you re redy to egin progrmming in ilipseF F F F F F F F F F F IVFQ his (gure shows the workspe with the perspetive swithing menuF F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F IVFR hilog for mking new l projetF F F F F F F F F F F F F F F F IVFS his (gure shows wht the workspe will look like fter you hve seleted to rete your (rst pplitionF F F F F F F F F F F F F F F IVFT his shows the pplition with single println nd the result of running it with output in the gonsoleF F F F F F F F F F F F F F F F IVFU his (gure shows the ilipse g epository ixploring perspeE tiveF F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F QVV QVW QWH QWI QWQ QWR QWT

List of Tables
QFI QFP QFQ SFI SFP snteger types with their sizes nd rngesF F F F F F F F F F F F F F ploting point types with sizes nd rngesF F F F F F F F F F F F F le of speil hrter espe sequenes in lF F F F F F F F le of opertor preedene in lF F F F F F F F F F F F F F F F pood item ostsF F F F F F F F F F F F F F F F F F F F F F F F F F F F TP TR TT WW WW

IQFI le of pproximte vlues of log2 n s funtion of nF e use the pproximtion tht 210 103 F he relity is tht 210 = 1024D ut this pproximtion is rther lose nd is good one to keep in your hed for quik pproximtions in mny prts of omputer sieneF F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F QHR IUFI his tle shows the preedene rules for opertors in lF he preendene is sed on the (rst hrter in the opertorF F F F QUH

IT

Part I

Introductory Concepts

IU

Chapter 1

Basics of Computers, Computing, and Programming


sn ll things it is good to understnd some foundtionl mteril efore going into detilF his helps to ground you nd give you some ontextF snevitlyD you lredy hve some experiene with omputers nd tht does give you it of ontext to work inF roweverD it is quite possile tht your experiene is limited to rther reent tehnologyF yne of the ftors tht shpes the world of omputer siene is tht it is fst moving nd ever hngingF unowing how we got to where we re n perhps help us see where we will e goingF

1.1 History
yne might think tht gomputer iene is (eld with rther short historyF efter llD omputers hve not existed ll tht long nd hve een stndrd (xture for even less timeF roweverD the history of gomputer iene hs deep roots in mth tht extend fr k in timeF yne ould mke strong rguE ment tht the mjority of gomputer iene isn9t even relly out omputersF snstedD it is out algorithmsF en lgorithm is forml spei(tion for stting method to solve prolemF he term itself is distortion of the nme lEuhw rizm %F re ws ersin mthemtiin who lived in the IIth entury nd wrote Treatise on Demonstration of Problems of AlgebraD the most signi(nt tretise on lger written efore modern timesF re lso wrote On the Calculation with Hindu NumeralsD whih presented systemti methods of pplying rithmeti to lgerF yne n go even further k in time depending on how )exily we use the term omputtionF hevies for filitting rithmeti ould e onsideredF ht would push things k to round PRHH fgiF wehnil utomt for IV

CHAPTER 1. BASICS OF COMPUTERS, COMPUTING, AND PROGRAMMINGIW

use in stronomy hve lso existed for mny enturiesF roweverD we will fous our ttention on more omplete omputtionl deviesD those tht n e proE grmmed to perform rod rnge of di'erent types of omputtionF sn tht seD the (rst rel mehnil omputer design would hve een the enlytil ingine whih ws designed y ghrles fge nd (rst desried in IVQUF ed vovele is often referred to s the (rst progrmmer euse her notes on the enlyti ingine inluded wht would hve een progrm for the mhineF por vrious resonsD this devie ws never uilt nd s suhD the (rst omplete omputers did not ome into existene for nother IHH yersF st ws in the IWRHs tht omputers in form tht we would reognize them tody me into existeneF his egn with the use Q whih ws uilt in qermny in IWRIF fy the end of the IWRHs there were quite few digitl omE puters in opertion round the world inluding the ixsegD uilt in the in IWRTF he onstrution of these mhines ws in)uened in lrge prt y more theoretil work tht hd een done dede erlierF yne ould rgue tht the foundtions of the theoretil spets of gomputer iene egn in IWQI when uurt qo del pulished his inompleteness theoremF his theoremD whih proved tht in ny forml system of su0ient omplexityD inluding stndrd set theory of mthemtisD would hve sttements in it tht ould not e proved or disprovedF he nture of the proof itself rought in elements of omputtion s logil expressions were represented s numers nd opertions were trnsformtions on those numersF pive yers lterD eln uring nd elonzo ghurh reted independent models of wht we now onsider to e omputtionF sn mny wysD the work they did in IWQT ws the true irth of gomputer iene s (eld nd it enled tht (rst round of digitl omputersF uring reted model of omputtion lled uring mhineF he uring mhine is remrkly simpleF st hs n in(nite tpe of symols nd hed tht n red or write on the tpeF he mhine keeps trk of urrent stte whih is nothing more thn numerF he instrutions for the mhine re kept in tleF here is one row in the tle for eh llowed stteF here is one olumn for eh llowed symolF he entries in the tle give symol to write to the tpeD diretion to move the tpeD nd new stte for the mhine to e inF he tpe n only e moved one symol over to the left or right or sty were it is t eh stepF gells in the tle n lso sy stop in whih se the mhine is supposed to stop runningF he wy the mhine works is tht you look up the entry in the tle for the urrent stte of the mhine nd symol on the tpe under the hedF ou then write the symol from the tle onto the tpeD repling wht hd een there eforeD move the tpe in the spei(ed diretionD nd hnge the stte to the spei(ed stteF his repets until the stop stte is rehedF et roughly the sme time tht uring ws working on the ide of the uring mhineD ghurh developed the lmd lulusF his ws formlD mth sed wy of expressing the ides of omputtionF hile it looks very di'erent from the uring mhineD it ws quikly proved tht the two re equivlentF ht is to sy tht ny prolem you n solve with uring mhine n e solved with the lmd lulus nd the other wy roundF his led to the soElled

CHAPTER 1. BASICS OF COMPUTERS, COMPUTING, AND PROGRAMMINGPH

ghurhEuring thesis stting tht nything omputle n e omputed y uring mhine or the lmd lulusD or ny other system tht n e shown to e equivlent to theseF

1.2 Hardware
hen we tlk out omputers it is typil to rek the topi into two prtsD hrdwre nd softwreF sndeedD the split goes k s fr s the work of fE ge nd voveleF fge designed the hrdwre nd foused on the si omputtion ilities tht it ould doF vovele worked on putting together groups of instrutions for the mhine to mke it do something interestingF rer notes indite tht she sw the further potentil of suh devie nd how it ould e used for more thn just doing lultionsF his split still exists nd is signi(nt euse most of this ook fouses exlusively on one hlf of the splitD softwreF o understnd the softwre thoughD it is helpful to hve t lest some grsp of the hrdwreF sf you ontinue to study gomputer ieneD hopefully you willD t some pointD hve full ourse tht fouses on the nture of hrdwre nd the detils of how it worksF por nowD our gol is muh simplerF e wnt you to hve si mentl imge of how the tngile elements of omputer work to mke the instrutions tht we type in exeute to give us the nswers tht we wntF wodern omputers work y regulting the )ow of eletriity through wiresF wost of those wires re tiny elements tht hve een ethed into silion nd re only tens of nnometers rossF he voltge on the wires is used to indite the stte of itD single element of storge with only two possile vluesD on or o'F he wires onnet up trnsistors tht re lid out in wy tht llow logil proessingF hile modern omputer proessor will inlude literlly hundreds of millions of trnsistorsD we n look t things t muh higher level nd generlly ignore tht existene of those individul wires nd trnsistorsF sn generlD modern omputers re uilt on the von xeumnn rhiteture with minor modi(tionsF his n e desried quite well with the help of the si digrm in (gure IFIF here is single memory tht stores oth the progrms nd the dt used y the progrmF st is onneted to gentrl roessing nit @gA y usF he gD whih n e more generlly lled proessorD hs the ility to exeute simple instrutionsD red from memoryD nd write to memoryF hen the omputer is running the g lods n instrution from memoryD exeutes tht instrutionD then lods notherF his hppens repetedly until the omputer stopsF his simple omintion of lod nd exeute is lled yleF yne of the things the g does is to keep trk of the lotion in memory of the next instrution to e exeutedF e ll lotion in memory nd addressF fy defult this moves forwrd eh time y the pproprite mount to get to the next instrutionF hi'erent types of omputers n hve di'erent instrutionsF ell omputers will hve instrutions to red vlues from memoryD store vlues to memoryD do si mth opertionsD nd hnge the vlue of the exeution

CHAPTER 1. BASICS OF COMPUTERS, COMPUTING, AND PROGRAMMINGPI

CPU Bus Memory

pigure IFIX wost si view of the von xeumnn shred memory rhitetureF e g nd the memory re onneted y usF he memory stores oth dt nd the progrms themselvesF he g n request informtion from memory or write to memory over the usF ddress to jump to di'erent prt of the progrmF he individul instrutions tht omputers n do re typilly very simpleF gomputers get their speed from the ft tht they perform yles very quiklyF wost omputers operte t few gighertzF his mens tht they n run through few illion instrutions every seondF here re lot of omplexities to rel modern omputers tht re needed to mke tht possile whih ren9t enompssed y this simple imge of omputerF sn mny wysD these re detils tht we don9t hve to worry out too muh t the eginningD ut they re importnt in professionl progrmming euse they n hve profound impt on the performne of progrmF e9ll spend just few prgrphs tlking out two of the omplexities in modern proessors s they re proly the most signi(ntF yne of them will even impt mteril lter in this ookF he (rst is the rrngement of memoryF hile the simple model shows single lok of memory onneted to the gD modern proessors hve n entire memory hierrhyF his hierrhy llows mhines to e'etively hve ess to very lrge mounts of storge while giving very fst ess to wht is relly neededF hen you tlk out memory on omputerD there re two things tht mke it into the norml mhine spei(tions tht re dvertised most of the timeF hose re the mount of ew @ndom eess wemoryA nd the mount of disk speF he ltter is generlly muh lrger thn the formerF ypilly speed goes inversely with size for memory nd this is true of disks nd ewF hisk drives re signi(ntly slower to ess thn ewD though wht is written to them stys there even when the mhine is turned o'F ew is fster thn

CHAPTER 1. BASICS OF COMPUTERS, COMPUTING, AND PROGRAMMINGPP

the diskD ut it still isn9t fst enough to respond t the rte tht modern proessor n use itF por this resonD proessors generlly hve smller mounts of memory on them lled heF he he is signi(ntly fster thn the ew when it omes to how fst the proessor n red or write vluesF iven tht isn9t enough nymore though nd modern proessors will inlude multiple levels of he referred to s vID vPD vQD etF ih level up is iggerD ut lso slowerF ome pplitions hve to onern themselves with these detils euse the progrm runs fster if it will (t inside of ertin heF sf progrm uses smll enough mount of memory tht it will (t inside of the vP heD it will run signi(ntly fster thn if it doesn9tF e won9t generlly worry out this type of issueD ut there re mny professionl developers who doF he other signi(nt di'erene is tht modern proessors hve multiple oresF ht tht mens in our simple piture is tht the g isn9t doing one instrution t timeD it is doing severlF his is wht we ll prllel proessing nd when it hppens inside of single progrm it is referred to s multiEthredingF his is huge issue for progrmmers euse progrms hven9t historilly inluded multiEthreding nd new omputers require tht in order to fully utilize their powerF nfortuntelyD mking progrm wultithreding n e di0ultF hi'erent lnguges o'er di'erent wys to pproh thisF his is one of the strengths of l nd we will disuss it t multiple points through the ookF

1.3 Software
he progrms tht re run on hrdwre re typilly lled softwreF he softwre isn9t physil entityF roweverD without some type of softwreD the hrdwre is rther uselessF st is the running of progrm tht mkes hrdwre useful to peopleF es with the hrdwreD softwre n e seen s hving multiple prtsF st lso hs lyering or hierrhy to itF et the se is lyer tht gives the omputer the initil instrutions for wht to do when it is turned onF his is often lled the fsy @fsi snputGyutput ystemAF he fsy is generlly loted on hip in the mhine insted of on the more norml forms of memory like the diskF snstrutions stored in this wy re often lled (rmwreF his term implies tht it is etween the softwre nd the hrdwreF he (rmwre relly is instrutionsD just like ny other softwreF sn sense it is less soft euse it is stored in wy tht might e impossile to write to or whih is hrder to write toF he fsy is responsile for getting ll the si funtionlity strted up on the mhineF itting on top of the fsy is the yperting ystem @yAF he yperting ystem is fundmentlly responsile for ontrolling the opertions of the mhine nd how it interts with the userF he y is lso responsile for writing (les to disk nd reding (les from diskF sn dditionD it hs the jo of loding other progrms into memory nd getting them strtedF yver timeD the mount of funtionlity in operting systems hs grown so tht they re lso expeted to present nie interfes nd hve ll types of other si

CHAPTER 1. BASICS OF COMPUTERS, COMPUTING, AND PROGRAMMINGPQ

funtionlity tht relly isn9t so siF et the top level re the progrms tht the user runsF hen the user inE struts the operting system to run progrmD the operting system lods tht progrm into memory nd sets the exeution ddress so tht the omputer will strt running the progrmF he redth of wht progrms n do is e'etively unlimitedF iverything tht runs on every digitl devie in the world is proE grmF ou use them to type your ppers nd do your eEmilF hey likely lso run the fuel injetion system in your r nd ontrol the lights t intersetionsF rogrms regulte the )ow of eletriity through the grid nd the )ow of wter to your indoor plumingF rogrms don9t just give you the pps on your phoneD they re running when you tlk on the phone to ompress your speeh into digitl form nd send it out to lol tower where nother progrm exmines it nd sends it on towrd the destintionF yn the wy it likely psses through multiple lotions nd gets hndled y one or more progrms t eh stopF et some point on the other end nother progrm tkes the digitl ompressed form nd expnds it k out to nlog tht n e sent to speker so the perE son you re tlking to n her itF omeone wrote eh of those progrms nd over time more progrms re eing written tht serve more nd more di'erent purposes in our livesF sn the lst setion we mentioned tht newer proessors hve multiple ores on themF he vilility of multiple ores @nd perhps multiple proessorsA is signi(nt for softwre s wellF pirstD they give the y the ility to hve multiple things hppening t one timeF ell ut the simplest of operting systems perform multitskingF his llows them to hve multiple progrms or proesses running t one timeF his n e done on single ore y giving eh proess short it of time nd then swithing etween themF hen there re multiple ores presentD it simply llows the progrms to truly run ll t oneF ih proess n lso exploit its own prllelism y reting multiple thredsF he y is still generlly responsile for sheduling wht threds re tive t ny given timeF his llows single progrm to utilize more of the resoures of mhine thn wht is present on single oreF hile this doesn9t mtter for some speilized pplitionsD the use of multiple ores hs eome more nd more ommonple nd the ore ount on lrge mhines s well s smller devies seems to e liming t n exponentil rteF es resultD the need to multiEthred progrms eomes ever more vitlF his inresing numer of ores in mhines hs led to nother interesting development in the re of serversF ervers re more powerful omputers tht re used y ompnies to store lrge mounts of dt nd do lots of proessing on tht dtF iverything you do on the we is pulling dt from serversF sf you re t niversityD odds re tht they hve t lest one room full of servers tht t s ontrol nd dt storge enter for the mpusF he nture of the work tht servers do is often quite di'erent from norml gF e lrge frtion of their jo is typilly just pssing informtion round nd the worklod for tht n e very unevenly distriutedF he omintion of this nd multiple ores hs led to n inrese in the use of virtuliztionF e virtul mhine is progrm tht ts like omputerF st hs fsy nd lods

CHAPTER 1. BASICS OF COMPUTERS, COMPUTING, AND PROGRAMMINGPR

n yF he y n shedule nd run progrmsF his whole proess hppens inside of progrm running potentilly on di'erent y on rel mhineF sing virtuliztionD you n strt multiple instnes of one or more operting systems running on single mhineF es long s the mhine hs enough ores nd memoryD it n support the work of ll of these virtul mhinesF hoing this uts down on the numer of rel mhines tht hve to e ought nd run reduing osts in oth mterils nd power onsumptionF

1.4 Nature of Programming


ivery piee of softwreD from the fsy of eh devie to the y nd the multiE tude of pplitions they run is progrm tht ws written y progrmmerF o wht is this thing we ll progrmming nd how to we do itc row do we give omputer instrutions tht will mke it do things for usc sn one senseD proE grmming is just the t of giving the omputer instrutions in formt tht it n work withF et fundmentl levelD omputers do nothing more thn work with numersF ememer the model in (gure IFIF ih yle the omputer lods n instrution nd exeutes itF here ws time when progrmming ws done y writing the instrutions tht the mhine exeutesF e refer to the lnguge of these instrutions s mhine lngugeF hile mhine lnguge is relly the only lnguge tht the omputer understndsD it is not very good lnguge for humns to work inF he numers of mhine lnguge don9t hold inherent mening for humns nd it is very esy to mke mistkesF por this resonD people hve developed etter wys to progrm omputers thn to write out mhine lnguge instrutionsF he (rst step up from mhine lnguge is ssemly lngugeF essemly lnguge is silly the sme s mhine lnguge in tht there is n ssemE ly instrution for eh mhine lnguge instrutionF roweverD the ssemly instrutions re entered s words tht desrie wht they doF he ssemly lnguge lso helps to keep trk of how things re lid out in memory so tht progrmmers don9t hve to tively onsider suh issues the wy they do with mhine lngugeF o get the omputer to understnd ssemly lnguge we employ progrm tht does trnsltion from ssemly lnguge to mhine lngugeF his progrm is lled n ssemlerF iven ssemly lnguge is less thn idel for expressing the ides tht we wnt to put into progrmsF por this resonD other lnguges hve een retedF hese higher level lnguges use more omplete words nd llow more omplex orgniztion of ides so tht more powerful progrms n e written more esilyF he omputer doesn9t understnd these lnguges eitherF es suhD they either employ ompilers tht trnslte the higher level lnguges into ssemly then down to mhine lnguge or interpreters tht exeute the instrutions one t time without ever turning them into mhine lngugeF here re literlly hundreds of di'erent progrmming lngugesF ih one ws reted to ddress some de(ieny tht ws seen in other lnguges or to ddress spei( needF his ook uses the l lngugeF st is hrd to fully

CHAPTER 1. BASICS OF COMPUTERS, COMPUTING, AND PROGRAMMINGPS

explin the ene(ts of lD or ny other progrmming lngugeD to someone who hsn9t progrmmed eforeF e will just sy tht l is very high level lnguge tht llows you to ommunite ides to the omputer in rther onise wy nd gives you ess to lrge numer of existing lirries to help you write progrms tht re fun or interestingF irly on in your proess of lerning how to progrm you will likely struggle with (guring out how to express your ides in progrmming lnguge insted of the nturl lnguge tht you re used toF rt of this is euse progrmming lnguges re fundmentlly di'erent thn nturl lnguges in tht they don9t llow miguityF sn dditionD they typilly require you to express ides t lower level thn you re used to with nturl lngugeF foth of these re tully ig prt of the reson why everyone should lern how to progrmF he true ene(ts of progrmming ren9t seen in the ility to tell omputer how to do somethingF he rel ene(ts ome from lerning how to rek prolems down yourselfF et very fundmentl levelD the omputer is stupid mhineF st doesn9t understnd or nlyze things1 F he omputer just does wht it is toldF his is oth lessing nd urse for the progrmmerF emiguity is fundmentlly d when you re desriing how to do things nd is prtiulrly prolemti when the reeiver of the instrutions doesn9t hve the ility to evlute the di'erent possile menings nd pik the one tht mkes the most senseF ht mens tht progrms hve to e rigorous nd tke into ount smll detilsF yn the other hndD you n tell omputers to do things tht humns would (nd inredily tedious nd the omputer will do it repetedly for s long s you sk it doF his is ig prt of wht mkes omputers so usefulF hey n sift through huge mounts of dt nd do mnyD mny lultions quikly nd without the hne of ftigue indued errorsF sn the endD you will (nd tht onverting your thoughts into lnguge the omputer n understnd is the esy prtF esD it will tke time to lern your new lnguge nd to get used to the nunes of itD ut the rel hllenge is in (guring out extly wht steps re required to solve prolemF es humnsD we tend to overlook mny of the detils in the proesses we go through when we re solving prolemsF e desrie things t very high level nd ignore the lower levelsD ssuming tht they will e impliitly understoodF rogrmming fores us to lrify those impliit steps nd in doing soD fores us to think more lerly out how we solve prolemsF his skill eomes very importnt s prolems get igger nd the things we might wnt to hve impliitly ssumed eome su0iently omplex tht they relly need to e spelled outF o one of the min skills tht you will develop when you lern how to progrm is the ility to rek prolems down into pieesF ell prolems n e roken into smller piees nd it is often helpful to do so until you get down to level where the solution is truly oviousF his pproh to solving prolems is lled topEdown pproh euse you strt t the top with lrge prolem nd
1 At
least they don't yet. This is the real goal of the eld of Articial Intelligence (AI). If the dreams of AI researchers are realized, the computers of the future will analyze the world around them and understand what is going on.

CHAPTER 1. BASICS OF COMPUTERS, COMPUTING, AND PROGRAMMINGPT

rek it down into smller nd smller piees until t the ottom you hve elements tht re simple to ddressF he solutions you get there re then put k together to produe the totl solutionF enother thing tht you will lern from progrmming is tht while there re mny wys to rek down lmost ny prolemD not ll of them re eqully goodF ome wys of reking the prolem down simply mke more senseF qrntedD tht is something of judgment ll nd might di'er from one person to the nextF e more qunti(le metri of the qulity of how prolem is roken down is how muh the piees n e reusedF sf you hve solved prtiulr prolem oneD you don9t wnt to hve to solve it ginF ou would rther use the solution you me up with eforeF ome wys of reking up prolem will result in piees tht re very )exile nd re likely to e useful in other ontextsF yther wys will give you elements tht re very spei( to given prolem nd s suh won9t e useful to you ever ginF here re mny spets of progrmming for whih there re no hrd nd fst rules on how things should e doneF sn this respetD progrmming is muh more n rt thn sieneF vike ny rtD in order to relly get good t it you hve to prtieF rogrmming shres other resemlnes to the retive rtsF rogrmming itself is retive tskF hen you re progrmming you re tkE ing n ide tht exists in your hed nd giving it mnifesttion tht is visile to othersF st isn9t tully physil mnifesttionF rogrms ren9t tngiE leF sndeedD tht is one of the philosophilly interesting spets of softwreF st is retion tht other people n experieneD ut they n9t touhF st is ompletely virtulF feing virtul hs ene(tsF hysil medi hve limittions on them imposed y the lws of physisF hether you re pintingD sulptingD or engineering devieD there re limittions to wht n tully e reted in physil speF rogrmming doesn9t relly su'er from thisF he ility of expression in progrmming is virtully oundlessF sf you go fr enough in omE puter siene you will lern where there re oundsD ut even there the results re interesting euse it is possile tht the ounds on omputtion re ounds on humn thinking s wellF his ility for ner in(nite expression is the root of the powerD eutyD nd joy of progrmmingF st is lso the root of the iggest hllengeF rogrms n eome ritrrily omplexF hey n eome too omplex for humns to understnd wht they re doingF por this resonD mjor prt of the (eld of gomputer iene is trying to (nd wys to tme the omplexity nd mke it so tht lrge nd omplex ides n e expressed in wys tht re lso esy for humns to follow nd determine the orretness ofF

1.5 Programming Paradigms


he ft tht there re mny wys to rek up prolems or work with prolems hs not only led to mny di'erent progrmming lngugesD it hs led to whole fmilies of di'erent pprohes tht re lled prdigmsF here re four min prdigms of progrmmingF st is possile others ould ome into existene

CHAPTER 1. BASICS OF COMPUTERS, COMPUTING, AND PROGRAMMINGPU

in the futureD ut wht ppers to e hppening now is tht lnguges re merging the existing prdigmsF l is one of the lnguges tht is lurring the lines etween prdigmsF o help you understnd this we will run through the di'erent prdigmsF

1.5.1 Imperative Programming


he originl progrmming prdigm ws the impertive prdigmF ht is euse this is the prdigm of mhine lngugeF o ll the initil progrms written in mhine lnguge were impertiveF smpertive progrmming involves giving the omputer set of instrutions tht it is to performF hose tions hnge the stte of the mhineF his is extly wht you get when you write mhine lnguge progrmsF he two keys to impertive progrmming re tht the progrmmer speifE illy sttes how to do things nd tht the vlues stored y the omputer re redily ltered during the omputtionF he onverse of impertive progrmE ming would e delrtive progrmming where the progrmmer sttes wht is to e doneD ut generlly isn9t very spei( out howF he l lnguge lE lows impertive style progrmming nd mny of the elements of this ook will tlk out how to use the impertive progrmming style in solving prolemsF

1.5.2 Functional Programming


puntionl progrmming ws orn out of the mthemtil underpinnings of gomputer ieneF he (rst funtionl lnguges were tully sed very hevily on ghurh9s lmd lulusF sn wy this is in ontrst to impertive progrmming whih res stronger resemlne to the ides in the uring mhineD though progrmming uring mhine is very muh like writing mhine lngugeF till the generl ides of mutle stte nd hving omE mnds tht re tken one fter the other re present on the uring mhineF vike the lmd lulusD funtionl lnguges re fundmentlly sed on the ide of funtions in mthemtisF e will see lot more of the signi(ne of mthemtil funtions on progrmmti thinking in ghpter RF puntionl lnguges re typilly more delrtive thn impertive lnE gugesF ht is to sy tht you typilly put more e'ort into desriing wht is to e done nd lot less in desriing how it is to e doneF por lnguge to e onsidered purely funtionl the key is tht it not hve mutle stteD t lest not t level tht the progrmmer notiesc ht does tht menc st mens tht you hve funtions tht tke vlues nd return vluesD ut don9t hnge nything else long the wyF he only thing they tell you k is the resultF sn n impertive lngugeD little reminders n e dropped ll over the pleF gertinlyD funtionl progrms hve to e le to hnge memoryD ut they lwys len up fter themselves so tht there is nothing left ehind to show wht they did other thn the (nl nswerF smpertive progrms n leve ltertions wherever they wntF here is no stipultion tht they set things k the wy they found itF upporters of funtionl progrmming often like to

CHAPTER 1. BASICS OF COMPUTERS, COMPUTING, AND PROGRAMMINGPV

sy tht funtionl progrms re lenerF sf you think of progrm s eing person this sttement mkes for n interesting nlogyF ere to enter your room looking for somethingD you would never know it euse the funtionl progrm would leve no tre of its pssingF et the endD everything would e s it hd strted exept tht the funtion would hve the result it ws looking forF en impertive progrm entering your room might not hnge nythingD ut more thn likely it would move the ooks round nd leve your pillow in di'erent lotionF he impertive progrm would hnge the stte of your roomF he funtionl one wouldn9tF l supports funtionl style of progrmmingD ut doesn9t ompletely enfore itF e l progrm n ome into your room nd it is esy to set it up so tht it doesn9t leve ny tre ehindD ut if you wnt to leve tres ehind you nF he purpose of this omintion is to give you )exiility in how you do thingsF hen funtionl implementtion is len nd esy you n feel free to use itF roweverD there re situtions where the funtionl style hs drwks nd in those ses you n use n impertive styleF

1.5.3 Object-Oriented Programming


yjetEoriented progrmming is reltive newomer to the list of progrmming prdigmsF he si ide of ojetEoriented progrmming (rst ppered in the swveTU progrmming lngugeF es the nme impliesD this dtes it k to the IWTHsF roweverD it didn9t gin muh momentum until the IWVHs when the mlltlk lnguge took the ides furtherF sn the IWWHsD ojetEorienttion relly hit it ig nd now virtully ny new lnguge tht is reted nd expets to see wide use will inlude ojetEoriented feturesF he si ide of ojetEorienttion is quite simpleF st is tht dt nd the funtions tht operte on the dt should e undled together into things lled ojetsF his ide is lled enpsultion nd we will hit on it fir it lter in this ookF his might seem like relly simple ideD ut it enles lot of signi(nt extrs tht don9t eome pprent until you hve worked with it whileF yjetEorienttion isn9t relly independent of the impertive nd funtionl prdigmsF snstedD ojetEoriented progrms n e done in either funtionl or n impertive styleF he erly ojetEoriented lnguges tended to e imE pertive nd most of the ones in wide use tody still reF roweverD there re numer of funtionl lnguges now tht inlude ojetEoriented feturesF l hppens to e purely ojetEoriented lngugeD sttement tht isn9t true of mny lngugesF ht this mens nd the implitions of it re disussed in detil in lter hptersF por most of the (rst hlf of this ookD the ft tht l is ojetEoriented won9t even e tht signi(nt to usD ut it will lwys e there under the surfeF

CHAPTER 1. BASICS OF COMPUTERS, COMPUTING, AND PROGRAMMINGPW

1.5.4 Logic Programming


he fourth progrmming prdigm is logi progrmmingF he prime exmple lnguge is the rolog lngugeF vogi progrmming is ompletely delrtiveF es the nme impliesD progrms re written y writing logil sttementsF st is then up to the lngugeGomputer to (gure out solutionF his is the lest used of the prdigmsF his is in lrge prt euse of signi(nt performne prolemsF he min use is in rti(il intelligene pplitionsF here is some indition tht logi progrmming ould repper in lnguges where it is omE ined with other prdigmsD ut these e'orts re still in the erly stgesF

1.5.5 Nature of Scala


es ws indited in the setions oveD l provides mix of di'erent prdigmsF st is truly hyrid lngugeF his gives youD s the progrmmerD the ility to solve prolems in the wy tht mkes the most sense to you or tht est suites the prolem t hndF he l lnguge diretly inludes impertiveD funtionlD nd ojetEoriented elementsF he nme l stnds for lle vnguge so it is not ompletely out of the question for them to dd lirry in the future tht ould support logi progrmming to some extent if ene(t to doing so ws foundF

Exercises
IF ho knowsc ossily short nswerF PF ho some reserh on topiF

Chapter 2

Getting to Know the Tools


iverything you do on omputer involves the running of softwreF et the most si levelD your omputer hs some operting system on it tht ontrols everything tht hppensD orgnizes dtD nd lets you exeute other progrms inside of itF ht operting system nd tools set you hoose to use hs signi(nt impt on how you go out doing thingsF his hpter wlks you through some tools tht you might use nd might not e fmilir withF st then moves on to look t some of the tools tht re prt of stndrd l distriution tht we will use through the rest of the ookF

2.1 Unix/Linux Command Line


our hoie of tools egins with your hoie of operting systemF tudents re expeted to e fmilir with ommon grphil environments on indows g or wintosh environmentF por tht resonD we ren9t going to tke time to introdue themF sf your lss is going to e run exlusively in suh n enviE ronmentD you n skip the rest of this setion though there is ene(t to hving exposure to this mterilF ome instrutors might hoose to hve you work more in ommnd line environmentF uh n environment will e new to most students so little spe is dedited to disussing it hereF he disussion will pply well to nixGvinux environments s well the ommnd prompt on w y F indows lso hs ommnd prompt tht you might use though the ommnds re often di'erentF wost people these dys re used to the point nd lik interfes of qrphiE l ser snterfeD qsF his isn9t how people hve lwys interted with omE putersF sndeedD qs tkes signi(nt mount of proessing power to runF por mny yersD omputers hd to hve simpler interfeF iven todyD there re times when you will need to intert with omputer without qsF his n hppen when something goes wrong with the omputer or if you need to use omputer fr wyF here re lso situtions where people will hoose to not run qs on omputer simply euse they don9t wnt to wste the QH

CHAPTER 2.

GETTING TO KNOW THE TOOLS

QI

pigure PFIX en exmple of vinux terminl with ommnd promptF proessing powerF iven when omputer is running qsD you n hoose to intert using ommnd promptF he qs n give you the ility to keep multiple ommnd prompts open t one nd using the ommnd prompt itself provides you with ilities tht ren9t esily omplished with qsF he reson why mny people hoose not to use the ommnd prompt is tht it does hve it of lerning urveF ou hve to know some si ommnds to e le to do nythingF sf you re going to spend muh time working on omputers it is worth putting in the smll mount of e'ort to lern the si ommnds for the ommnd prompt interfe on your yF ydds re tht you will (nd tht not only does it speed things up on regulr sisD there will e times when it llows you to do things tht you simply ouldn9t do otherwiseF PFIshows terminl window under vinux tht gives us ommnd promptF our ommnd prompt might look di'erent thn thisF sn generl they disply some useful informtion followed y hrter tht signi(es the end of the promptF sn this (gure the prompt shows the user nme nd omputer nme followed y the urrent diretory nd $F st is the $ tht signi(es the end of the promptF gommnds tht you enter pper fter the $ enything tht they disply will e printed out elow the promptF efter ll the output of one ommndD nother prompt will e givenF

CHAPTER 2.

GETTING TO KNOW THE TOOLS

QP

2.1.1 Files and Directories


sn qs you re used to orgnizing your (les in foldersF ou hve ions tht represent di'erent (le types or folders nd you n ple (lesGfolders inside of folders to orgnize themF hese onepts me from the systems lredy in ple on the ommnd lineF he only hnge is terminologyF he term folder worked well from grphil stndpointF yn the ommnd line they hve long een lled diretoriesF he (rst set of ommnds we will lern out llow us to work with (les nd diretories so tht we n nvigte round nd do the types of things tht you re used to doing y likingD douleElikingD or drg nd droppingF rere is list of ommnds with rief desription of ehF ou will notie tht in generl they re revitions for wht they doF

t ! hisply the ontents of one or more (lesF d ! ghnge diretoryF p ! gopy one (le to nother nme or lotionF less ! hisply out the ontents of one or more (les with the ility to move forwrd nd kwrdD serhD etF @vess is more thn moreFA ls ! vist the ontents of diretoryF mkdir ! wke diretoryF more ! hisply the ontents of one of more (les with the ility to pge through or serhF mv ! wove (le to new nme or lotionF pwd ! tnds for resent orking hiretoryF his prints out the diretory tht you re urrently working inF rm ! emove (leF rmdir ! emove diretory if it is emptyF
he ig dvntge of ommnd line is tht eh ommnd n e followed y rgumentsF tust entering ommnd is like doule liking on progrm ionF st is the rguments tht let you speify dditionl informtionF wost of these ommnds don9t do nything unless you give them one or more (leGdiretory nmes to work onF o how would you go out using these ommndsc e9ll egin with pwdF st is silly the simplest ommnd nd n ome in hndy when you re strting o' or if you hve lost trk of where you re in the diretory strutureF et the ommnd prompt simply type in pwd nd hit interF ixtly wht you get will depend on mny thingsD ut it should print out one line of output showing you the urrent diretoryF st ould look something like thisF

CHAPTER 2.

GETTING TO KNOW THE TOOLS

QQ

mlewis@mlewis-laptop:~$ pwd /home/mlewis mlewis@mlewis-laptop:~$


sn this seD the diretory is GhomeGmlewisF sn nix nd vinux systemsD the se of the entire (le system is GF ht is why it ppers t the eginning of this diretoryF e diretory tht egins with G is n solute diretoryF efter printing the output we get new prompt to enter the next ommndF he next ommnd we wnt to enter is the ls ommndF ype in lsD followed y n enter nd you will get listing of ll of the (les in your urrent diretoryF his is the most si usge of the ommndF ou n lso use it to see the ontents of some other diretory y following the ls ommnd with diretory nmeF rere we see listing of the ontents of the root diretoryF

mlewis@mlewis-laptop:~$ ls / bin dev initrd lib lost+found opt sbin tmp vmlinuz boot etc initrd.img lib32 media proc srv usr vmlinuz.old cdrom home initrd.img.old lib64 mnt root sys var
sf you list diretory nd it doesn9t strt with G then it will e reltive diretoryF o wht you list will e ppended to the end of the urrent diretoryF ou might hve diretory lled hesktop in the urrent diretoryF yping in ls hesktop will list the ontents of the hesktop diretory under the urrent diretoryF

mlewis@mlewis-laptop:~$ ls Desktop AdobeReader.desktop QtCreator.desktop


ou n lso speify multiple (les or diretories nd they will ll e listed s seen hereF

mlewis@mlewis-laptop:~$ ls Desktop / /: bin dev initrd lib lost+found opt sbin tmp vmlinuz boot etc initrd.img lib32 media proc srv usr vmlinuz.old cdrom home initrd.img.old lib64 mnt root sys var Desktop: AdobeReader.desktop QtCreator.desktop
ou might not think tht you would normlly wnt to list multiple things t oneD ut it is feture people use ll the time with wild rd hrtersF sf you put B into nmeD the system will reple it with ll the (les or diretories tht mth if the B is repled with zero of more hrtersF rere is n exmple of tht usgeF

mlewis@mlewis-laptop:~$ ls /vmlinuz* /vmlinuz /vmlinuz.old

CHAPTER 2.

GETTING TO KNOW THE TOOLS

QR

por the (rst (leD the B is repled with nothingF por the seond it is repled with FoldF ou n lso use c to represent ny one hrterF hese wild rds ren9t ever seen y the ls ommnd of other ommndsF he ommnd shell reples them with ll of the mthing (les nd it is the multiple (le nmes or diretory nmes tht get pssed to the ommndF he ls ommnd hs lot of other possile options s wellF he options re ll preeded y hyphenF he most ommonly used option is ElD whih tells ls to use long disply formtF he following is n exmple of thtF

mlewis@mlewis-laptop:~$ ls -l Desktop total 8 -rwxrwxrwx 1 root root 1261 2008-11-28 12:21 AdobeReader.desktop -rw-r--r-- 1 mlewis mlewis 250 2009-12-22 11:03 QtCreator.desktop
he long formt puts eh (le or diretory on seprte lineF sn ddition to the (le nmes it shows numer of other piees of informtionF he (rst ten hrters show permissions on the (lesF ermissions re disussed lter in this hpterF efter tht is numer showing how mny links there re to this (leF efter tht re the user nme of the owner of the (le nd the group tht the (le elongs toF he lst two piees of informtion re the size of the (leD mesured in ytesD nd the dte nd time of the lst modi(tion of tht (leF he next most ommonly used option is EF his tells ls to list ll the (lesD inluding the hidden (lesF ridden (les in nix nd vinux re (les whose nmes egin with periodF e see here usge of this omined with the long optionF

mlewis@mlewis-laptop:~$ ls -al Desktop total 16 drwxr-xr-x 2 mlewis mlewis 4096 2010-02-27 20:02 . drwxr-xr-x 106 mlewis mlewis 4096 2010-08-09 16:57 .. -rwxrwxrwx 1 root root 1261 2008-11-28 12:21 AdobeReader.desktop -rw-r--r-- 1 mlewis mlewis 250 2009-12-22 11:03 QtCreator.desktop
his dds two dditionl linesF he letter d t the fr left edge tells us tht these re tully diretoriesF he F diretory is nother nme for the urrent diretoryF he FF diretory is the nme of the diretory in whih the urrent diretory sitsF fy defultD ommnds work on the things in the urrent diretoryF por this resonD one of the ommnds you will use the most is the ommnd tht hnges the urrent diretoryD dF he d ommnd is followed y single diretory nmeF he diretory will e the new urrent diretoryF es we just swD eh diretory hs F nd FF s diretory nmes inside of itF sf you wnt to move up level in the diretory strutureD simply do d FFF ou n lso enter d without diretory t ny time to hnge k to your home diretoryF yther tsks tht you do frequently when you re mnipulting (les in qs re to opyD moveD or deleteF he ommnds for these re pD mvD nd rmF he p nd mv ommnds re used in roughly the sme wyF yne wy to use them is to enter two (le nmes in whih se the (rst (le will e opied to the

CHAPTER 2.

GETTING TO KNOW THE TOOLS

QS

seond nme or renmed to the seond nmeF e seond usge is to enter one or more (le nmes nd then end with diretory nmeF sn tht usge ll of the (les listed re either opied or moved to the diretory listed t the endF sf you inlude nme tht hs wild rd in itD it will e expnded to ll the (le nmesF e n see these long with d in use hereF

mlewis@mlewis-laptop:~$ cd Desktop mlewis@mlewis-laptop:~/Desktop$ mv ../*.txt . mlewis@mlewis-laptop:~/Desktop$ cp test.txt test2.txt


e strt y hnging to the hesktop diretoryF xote tht the prompt used in this exmple hnges so tht we n see we re in this new diretoryF e then move ll the (les from our home diretory tht end with Ftxt into the urrent diretoryF his line with mv uses oth FF to refer to the diretory ove the urrent oneD nd F to refer to the urrent diretoryF sn this seD one of those (les ws nmed testFtxtF he lst ommnd mkes opy of tht (le nd gives the opy the nme testPFtxtF sf you wnt to remove (leD use the rm ommndF he rm ommnd n e followed y one or more (lesF eginD wild rds n e used to mth multiple (lesF rere we re getting rid of ll of the (les tht end with FtxtG

mlewis@mlewis-laptop:~/Desktop$ rm *.txt
here is word of wrning out removing (les on most vinux sed systems with the ommnd lineD it is not forgivingF his is true whether you re using rm or if you hppen to mv or p to (le nme when you lredy hd (le of tht nmeF hile most of the qss tht you hve used proly move (les you delete to some form of trsh nD relly just di'erent diretoryD nd then llow you to ler tht out lterD doing rm on (le relly deletes it thenF ou n9t go digging in the trsh to (nd itF sn generl when you delete (le with rm on these systemsD it is gone nd your only hne of getting it k is if you hve kupF his n e espeilly dngerous with the wy tht the ommnd line dels with wild rdsF ke the rm ommnd oveF sf you identlly insert spe etween the sterisk nd the dotD you will delete every (le in the urrent diretoryF ht is euse the B lone mthes everythingF y e reful when you re using rm nd look over the ommnd efore you hit enter to mke sure you didn9t mistype nything or insert ny unwnted spesF hiretories exist to keep (les orgnizedF por this resonD you should proly mke diretories for eh di'erent mjor grouping of work tht you hveF ou might lso nest these the further re(ne the orgniztion shemeF ou n mke new diretory with the mkdir ommndF imply follow the ommnd with the nmes of one or more diretories tht you wnt to reteF por exmpleD it is proly good ide to mke diretory to store ll of the work for this ourseF ou might mke suEdiretories in there for di'erent ssignments or the ode you write in lssF

CHAPTER 2.

GETTING TO KNOW THE TOOLS

QT

fy defultD rm does not remove diretoriesF o remove diretory use the rmdir ommndF vike mkdirD you follow it with the nme of one or more diretories you wnt to removeF rmdir will only remove diretory if it is emptyF o you would need to remove the ontents to the diretory (rst efore you n remove itF sf you relly wnt to delete n entire diretory nd ll of its ontentsD inluding potentilly other diretoriesD there is n option for rm tht will do thtF he Er option tells rm or p to reursively1 run down into diretory nd either remove or opy ll of its ontentsF his is very helpful if you wnt to opy diretory tht hs lot of things in itF st n lso e of gret help if you wnt to remove suh diretoryF ememer to tred refully thoughF sing rm with the Er )g hs the possiility to wipe out lot of (les tht you might hve wnted to keep roundF he ommnd elow uses Er with opy to opy over n entire diretory nd ll of its ontents into the urrent diretoryF

mlewis@mlewis-laptop:~/Desktop$ cp -r ../Music/ .
he lst thing tht you might wnt to do with your (les is tully look t wht is in themF here re mny wys to do thisF sndeedD ig prt of most of the progrms you hve on your omputer is the ility to let you view the ontents of spei( types of (lesF hese ommnds work est with plin text (lesF e will e deling with lot of thoseF he most si wy to look t suh (le is with the t ommnd whih simply prints the ontents of one or more (les to stndrd outputF e step ove tht is the more ommnd whih will disply one sreen t time nd let you move down one line y hitting enter or whole sreen y hitting speF ou n lso serh for things y typing wht you wnt to serh for fter pressing GF et nother step up is the less ommnd whih llows you to move round freely using rrow keys or pgeEup nd pgeEdown s well s serh s you ould with moreF

2.1.2 Helpful Tips


wny people who ren9t fmilir with the ommnd line re initilly turned o' it y the mount of typing they hve to doF eople who use ommnd line ll the time don9t neessrily like typing moreD they know more triks to do things with the keyord tht don9t require lot of typingF rere re some hndy triks to help you use the ommnd line more e0ientlyF yping in omplete (le nmes n e tedious nd worseD is often error proneF sf you mistype something it won9t work nd you hve to enter the whole thing ginF orseD it might work nd do something you didn9t relly wnt to doF feuse of thisD t ompletion is proly the most helpful feture you will (nd in your ommnd line environmentF sf you type in the (rst few letters of (le or diretory then hit tD the shell will (ll in s mny hrters s it nF sf there is only one (le tht strts tht wyD it will give you the whole (leF sf there is more thn oneD it will (ll in s muh s it n until it gets to point
1 Recursion
is a topic that you probably aren't familiar with yet, but which we will hit on several times during this book.

CHAPTER 2.

GETTING TO KNOW THE TOOLS

QU

where you hve to mke hoieF sf you doule t it will print out the di'erent options tht (tF ou should try this y going k to your home diretory @rememer tht you n do this t ny time y typing in d nd hitting enter without giving it diretoryA nd then typing d he nd hitting tF ydds re good tht the work hesktop will ompleted for you with G t the end euse it is diretoryF se ls to see if there re two (lesGdiretories tht strt with the sme (rst few lettersF ype in t followed y the (rst two letters nd hit tF he shell will omplete s muh s it n then stopF rit t twie quikly nd it will show you the di'erent optionsF st might look something like thisF

mlewis@mlewis-laptop:~$ cd Do Documents/ Downloads/


xot only does t ompletion sve you from typing lot of extr hrtersD it never misspells (le or diretory nmeF se t often nd will will sve you lot of key strokes nd lot of little mistkesF st is not unommon to wnt to enter the sme ommnd or very similr ommnd more thn oneF he esiest wy to do this if it is ommnd you entered reently is to use the up nd down rrow keys to nvigte kwrd nd forwrd through the ommnd historyF hen you get to ommnd you n edit it if you wnt to mke hngesF sing the rrow keys isn9t ll tht onvenient if the ommnd ws something you entered long time goF he simplest wy to repet n old ommnd extly is to strt the line with n exlmtion point @often red ngA nd follow it y some of the ommndF his will go k through the history nd (nd the most reent ommnd tht strted with those hrtersF ht ommnd will e exeuted without the hne to edit itF he limittion tht you n9t edit it or see extly wht the ommnd is you will exeute efore you exeute it mens tht 3 is most useful for ommnds tht strt in rther unique wyF ou n lso press gtrlEr to get the ility to serh through historyF efter pressing gtrlErD strt typing in hrters tht our onseutively in the omE mnd you wntF st will ring up the most reent ommnd tht inludes wht you hve typed in nd you n edit itF enother ommnd tht is very useful in generl is the mn ommndF his is short for mnul nd silly funtions s help pges for ommnds or instlled progrms on the systemsF he most si usge is to type in mn followed y the ommnd tht you wnt informtion onF ou n lso put in Ek option to do serh for something in the mn pgesF

2.1.3 Permissions
ell modern operting systems hve permissions tht ontrol who n get ess to di'erent types of (lesF ht (les you n ess depends on who you re nd wht permissions you hveF hen you log into mhine tht determines who you reF ou n use the ommnd whomi to see who you re logged onto the mhine sF

CHAPTER 2.

GETTING TO KNOW THE TOOLS

QV

mlewis@mlewis-laptop:~$ whoami mlewis


sn this se the prompt lso displys the user nmeD ut tht won9t lwys e the seF ih user n lso e memer of vrious groupsF ou n use the groups ommnd to see wht groups you re memer ofF

mlewis@mlewis-laptop:~$ groups mlewis adm dialout cdrom floppy audio dip video plugdev fuse lpadmin admin
he omintion of who you re nd the groups tht you re in will determine wht you hve ess to on mhineF yn nix nd vinux every (le hs redD writeD nd exeute permissions for their ownerD their groupD nd othersF hoseD long with the owner nd the group of (le re displyed y ls when you use the El optionF vet9s go k to the hesktop diretory nd look t the long listing of the (les ginF

mlewis@mlewis-laptop:~/Desktop$ ls -l total 8 -rwxrwxrwx 1 root root 1261 2008-11-28 12:21 AdobeReader.desktop -rw-r--r-- 1 mlewis mlewis 250 2009-12-22 11:03 QtCreator.desktop
here re two (les hereF he (rst ten hrters tell us the permissions on the (leF he (rst one is either d or EF he d would tell us it is diretoryF xeither is diretory so oth of these egin with EF efter tht re three groups of rwx where ny of those n e repled y EF he letters stnd for red permissionD write permissionD nd exeute permission with E when tht permission is not grntedF he (rst set of rwx is the permissions of the user the (le elongs toF he seond set is for the group the (le elongs toF he third is for othersF he (rst (le listed here gives full permissions to ll threeF he seond gives red nd write to the user nd only red to the group nd othersF hortly fter the permissions pper two nmesF por the (rst (le they re oth rootF por the seond they re oth mlewisF hese re the user nd group nmes for the (leF he nme root is the superuser on nix nd vinux mhinesF o mke this more interestingD let9s use the mkdir ommnd to mke new diretory here nd then list the ontents of the diretory ginF

mlewis@mlewis-laptop:~/Desktop$ mkdir NewDir mlewis@mlewis-laptop:~/Desktop$ ls -l total 12 -rwxrwxrwx 1 root root 1261 2008-11-28 12:21 AdobeReader.desktop drwxr-xr-x 2 mlewis mlewis 4096 2010-08-11 19:59 NewDir -rw-r--r-- 1 mlewis mlewis 250 2009-12-22 11:03 QtCreator.desktop
his new diretory is lso owned y mlewis nd is prt of the group mlewisF xote the letter d (rst thing on the line telling us tht this is diretoryF he ownerD mlewisD hs full redD writeD nd exeute permissionsF enyone in group

CHAPTER 2.

GETTING TO KNOW THE TOOLS

QW

mlewis will hve red nd exeute permissions s do other users on the mhineF sf you try to use (leGdiretory in wy you don9t hve permissions for you will get n error messgeF o go into diretory nd see wht is inside of it you need oth red nd exeute permissionsF o now tht you know how to tell wht permissions (le hs the next question is how do you hnge themF he hmod ommnd is used to hnge permissions on (leF here re quite few di'erent wys to use hmodF e9ll just introdue one of them hereF efter hmod you speify how you wnt to hnge or set permissions then give list of the (les you wnt to mke the hnges toF he simplest wy to speify hnges is to use hrter odes for whih set of permissions nd the permissions nd seprte them with CD ED or a to sy if you wnt to dd themD remove themD or set themF he di'erent permission sets re spei(ed y u for the userD g for the groupD o for othersD nd for llF he rights re spei(ed y the letters rD wD nd x s we hve lredy seenF vet9s sy tht we re going to put things in this new diretory tht we don9t wnt nyone ut the user to hve the ility to seeF sn tht se we would wnt to remove the red nd exeute permissions from the group nd othersF e n see tht eing done nd the result hereF

mlewis@mlewis-laptop:~/Desktop$ chmod go-rx NewDir/ mlewis@mlewis-laptop:~/Desktop$ ls -l total 12 -rwxrwxrwx 1 root root 1261 2008-11-28 12:21 AdobeReader.desktop drwx------ 2 mlewis mlewis 4096 2010-08-11 19:59 NewDir -rw-r--r-- 1 mlewis mlewis 250 2009-12-22 11:03 QtCreator.desktop
rd we wnted to give everyone full permissions we ould hve used Crwx s the optionsF vess ommon thn hnging permissions is hnging ownership of the (leF sf you own the (le you n hnge the user nd the group of the (le with the hown ommndF he most likely senrio for this is if you wnt to hnge the group to shred group so tht selet set of users n hve ess to somethingF sf the group were lled projet then you would type in hown Xprojet (lesF es with the p nd rm ommndsD there re times when you will wnt to hnge the permissions of lrge numer of (les in n entire diretoryF foth hmod nd hown ept the E option so tht they will do thisF

2.1.4 Compression/Archiving
sf you spend muh time on systemD you will likely need to intert with ompressed or rhived (les t some pointF foth of these ply the role of tking mny seprte (les nd turning them into one lrge (leF sf it is ompressedD tht lrge (le should e smller thn the sum of the (les tht went into itF wny progrms tht you might wnt to put on your omputer ome in the form of ompressed (lesF sf you hve ssignments or projets tht spn multiple (lesD

CHAPTER 2.

GETTING TO KNOW THE TOOLS

RH

your instrutor might wnt you to omine them into single (le to turn them inF here re mny di'erent ompression nd rhiving utilitiesF e9ll just tlk out the min ones hereF

tr ! erhive (les to single trllF gzipGgunzip ! gompress one or more individul (les to the gzip formtF zipGunzip ! ompress multiple (les to single zip (leF he zip formt is used extensively on mny formtsF
he (rst two re used through the nixGvinux worldF hey do rhiving nd ompression seprtelyD ut re often used together to do othF he rhiving progrm is lled trF st ws originlly reted for rhiving (les from disk to tpeF st simply ollets multiple (les together into single (le lled trllF st n lso extrt (les from trllF es with our other progrmsD tr is ontrolled y pssing it rgumentsF ou n use the mn pges to see the mny di'erent options for trF e will only disuss the si onesF he three min wys you will intert with trll re to rete oneD view the ontents of oneD or extrt (les from oneF hese di'erent options re given with the hrters D vD nd xF wost of the time you will wnt to intert with (le nd for tht you will give the f optionF he next thing fter the f option should e the (le nme of the trll you re retingD viewingD or extrtingF rll (les should typilly end with the extension FtrF sf you re reting trllD tht will e followed y the (le nd diretory nmes of the things you wnt to put into the trllF rere re some smple invotionsF

tar cf assign1.tar header.txt Assign1/ tar tf assign1.tar tar xf assign1.tar


he (rst ommnd is wht you might exeute to rete trll lled sE signIFtr whih ontins heder (le nd ll the ontents of the diretory esE signIF he seond ommnd might e used y you to verify tht everything you wnt is in the (le or y the instrutor to hek wht is there efore it is extrtedF he lst ommnd would extrt the ontentsF he ounterprt to tr is gzipF his ommnd with ompress one or more (lesF imply follow the gzip ommnd with set of (les nmes to ompressF ht will rete new set of ompressed (les tht end with the extension FgzF he gunzip ommnd will unzip ny (le to give you k the originl (leF ou n use the Er option to reursively desend into diretoryF he omintion of tr nd gzip is so ommon tht you n get tr to utomtilly zip or unzip (les using gzipF imply put the z )g in the options to tr nd either gzip or gunzip will e invokedF piles reted tht wy re typilly given the Ftgz extensionF foth tr nd gzip re rther spei( to the nixGvinux worldF sf you hve to del with ompressed (les going to or from other systemsD you might wnt to use the more rodly used zip formtF he zip ommnd n e followed

CHAPTER 2.

GETTING TO KNOW THE TOOLS

RI

y the nme of zip (le nd the set of (le nmes to zip up ll the (les into the spei(ed zip (leF sf you wnt it to zip up whole diretory struture you will need to use the Er optionF here is n unzip ommnd tht will extrt the ontents of zip (leF es you might expetD ll of these progrms hve mny more optionsF ou n use the mn ommnd nd red through the mn pges to see ll the vrious other pilities tht they hveF

2.1.5 Remote
yne of the gret strengths of nixGvinux is the true multiEuser pilities tht they hveF sn indows you re proly used to only hving one person t time logged into omputerF ht person will e sitting in front of the omputer nd if no one is t omputerD it isn9t eing usedF his isn9t true with nixGvinuxF hese systems will llow multiple people to e logged in t oneF e omputer ould e in full use even if no one is sitting t itF sn ftD this is ig prt of why you should e fmilir with the ommnd lineF unning grphil interfes on mhines ross long distne snternet onnetions n e very unplesntF roweverD the plin text form of ommnd line will e quite responsive even ross rther slow networksF o how do you log into one omputer from nother onec sf you re on nixGvinux ox nd you wnt to log into nother there re severl ommnds tht you ould use to mke onnetionF he most siD nd likely lest usefulD is telnetF imply type in telnet followed y the nme or s ddress of the mhine tht you wnt to onnet toF his opens very simple network onnetion etween the mhinesF feuse telnet onnetions ren9t seure nd reD in wyD too )exileD you9ll proly (nd this pproh loked y the seurity setting on most mhinesF xext up the sle is rshF his stnds for remote shell nd n e invokes in the sme wy s telnetF he rsh onnetion is lso not seure nd s suhD is loked on mny systemsF roweverD for vrious resonsD it might e llowed on your system if you re logged into trusted mhine inside of the lol (rewllF he onnetion type tht you proly should use y defult is sshF his stnds for seure shell nd s the nme impliesD ll ommunition ross n ssh onnetion is enrypted using puli key ryptogrphyF es suhD if sysE tem is going to let you log in remotelyD this is the method tht most system dministrtors re likely to leve open for youF hen you onnet remotely to mhine you will e sked for you pssword nd ssuming you get it rightD you will e dropped t ommnd prompt on tht mhineF iverything tht is disussed in this setion will work on the remote mhine just s well s the lol oneD no mtter how fr wy the mhine isF hen you re done entering ommnds nd you wnt to ome k to the urrent mhineD type logout or exit to terminte the remote sessionF ht if you re on indows mhinec row n you onnet thenc our windows mhine should likely hve telnet on it if you were to ring up the ommnd promptF roweverD tht relly isn9t good wy to onnet these dysF

CHAPTER 2.

GETTING TO KNOW THE TOOLS

RP

hnkfullyD there re free ssh progrms tht you n get for indowsF yne of these is lled putty nd it will llow you to ssh into remote mhine nd use it from indows oxF sf you deide you like the nixGvinux ommnd prompt you n lso instll gygwin under indows nd get rshD sshD nd ll the other ommnds we will tlk out on your indows mhineF elnetD rshD nd ssh ll give you wys to log into remote mhine nd exeute ommnds on tht mhineF ometimes wht you need is to move (les from one mhine to notherF por this you should proly use sp or sftp2 F he sp ommnd stnds for seure opyF ou use it muh like you would the norml p ommndF he only di'erene is tht your (le nmes n e prepended with mhine nme nd olon to sy tht they ome from or re going to di'erent mhineF e smple invotion is shown hereF

scp cs.trinity.edu:Desktop/fileINeed.txt .
his opies the (le (lesxeedFtxt from the hesktop diretory on the mhine sFtrinityFedu to the urrent diretory on the urrent mhineF sf the seond rgument hs mhine nme with olon then the (le will go to tht remote lotionF es with pD the Er option n e used to opy n entire diretory strutureF he sftp ommnd is seure version of the lssi ftp progrmF ftp stnds for pile rnsfer rotoolF st llows you to nvigte lol nd remote diretory struturesD see wht (les re on the remote mhineD nd then move them rossF he full usge of sftp is eyond the sope of wht we wnt to over hereD ut you should e wre it exists in se you need to move (les round nd ren9t ertin wht you wnt to move or where it should e moved to of fromF

2.1.6 Other
here re mny other ommnds tht re ville to you on the nixGvinux ommnd lineF inough so tht people hve written multiple ooks on the topiF ou don9t hve to e fmilir with ll of them to get things done with the ommnd lineF sn ftD fter this hpter you should hve enough to get through the tsks tht you will need to for this ourse nd going forwrdF here re just few more ommnds tht you might (nd helpful tht we will list here efore we move on to the next topiF

ler ! glers the terminl so you get fresh sreenF his is only osmetiD ut it n e helpful t timesF df ! tnds for disk freeF his will list ll of the di'erent volumes on the urrent disk system nd show you informtion on their usgeF du ! tnds for disk usgeF his will give you rundown of how muh disk spe is eing used in the urrent diretory nd its suEdiretoriesF
2 There
are also rcp and ftp programs, but just like rsh and telnet, secure systems likely won't let these through.

CHAPTER 2.

GETTING TO KNOW THE TOOLS

RQ

eho ! rints whtever follows the ommnd k to the terminlF (nd ! pind (les tht hve di'erent properties spei(ed on the ommnd lineF grep ! erhes for text inside of the spei(ed (lesF hed ! rint the (rst lines of (leF ps E how informtion out proesses running on the mhineF til ! print the lst lines of (leF touh ! pdtes the edit time on the spei(ed (le to the urrent timeF top ! vists the top resoure onsuming progrms urrently running on the mhineF w ! ells you you who is logged onto your mhineD where they re oming fromD nd wht they re runningF wget E ou give this ommnd v nd it will downlod the (le t tht v to the urrent diretoryF
es (nl tipD you n follow ny ommnd with 8 to mke it run in the kgroundF

2.2 I/O Redirection


o fr we hve een tlking out the di'erent ommnds we n run from ommnd lineF e hve typed input into the onsole when it ws needed nd the ommnds hve output to the terminl so we ould see itF he nixGvinux ommnd line gins signi(nt mount of power from the ft tht you n rediret input nd outputF he simple forms of rediretion hve the output of progrm go to (le or hve the input ome from (leF hese will e of use to you in mny of your ssignments even if you don9t see the ene(t right nowF o send the output of progrm to (le you put greter thn followed y (le nme fter the full ommndF he output of the ommnd will go into tht (leF rere is n exmpleF

mlewis@mlewis-laptop:~/Desktop$ ls -l > list.txt mlewis@mlewis-laptop:~/Desktop$ ls -l total 16 -rwxrwxrwx 1 root root 1261 2008-11-28 12:21 AdobeReader.desktop -rw-r--r-- 1 mlewis mlewis 259 2010-08-12 22:32 list.txt drwx------ 2 mlewis mlewis 4096 2010-08-11 19:59 NewDir -rw-r--r-- 1 mlewis mlewis 250 2009-12-22 11:03 QtCreator.desktop mlewis@mlewis-laptop:~/Desktop$ cat list.txt total 12

CHAPTER 2.

GETTING TO KNOW THE TOOLS

RR

-rwxrwxrwx -rw-r--r-drwx------rw-r--r--

1 1 2 1

root root 1261 2008-11-28 12:21 AdobeReader.desktop mlewis mlewis 0 2010-08-12 22:32 list.txt mlewis mlewis 4096 2010-08-11 19:59 NewDir mlewis mlewis 250 2009-12-22 11:03 QtCreator.desktop

he (rst ll to ls doesn9t print to sreenF snstedD it sends it to the (le listFtxt euse of the greter thn followed y tht (le nmeF e n then do nother ls nd let it print to sreen to verify tht the new (les is thereF sndeedD we hve new (le tht is PSW ytes in lengthF e n lso use t to view the ontents of the (le nd you see the output you expet from lsF here is one interesting spet to itF he (le we re outputting to is thereD ut it hs size of zeroF ht is euse the (le is reted s soon s we exeute the ommndD ut it doesn9t get ontents written to it immeditelyF ht hppens over time s prts of the output get ig enough tht they hve to e moved from u'er to the (leF sing b for redireting output will rete new (le if none is there nd will wipe out ny existing (le if one is thereF sf you wnt ommnd to dd onto n existing (leD use b#b instedF his will rediret the outputD ut ppend to ny existing (leF e n lso tell ommnd to tke it9s input from (le insted of from stndrd input using the less thn symolF xone of the ommnds we hve looked t require dditionl input from stndrd input unless it requires pssE word whih you don9t wnt to put in n unenrypted (leF wny of the progrms tht you write will need to hve you type inputs into themF ou will often hve to run these progrms multiple times nd it n get very tedious to input the sme vlues over nd over while you try to get the progrm to workF rving it tke the input from the (le n sve you time s you only hve to enter it into the (le one nd then use the (le when you re testing the progrmF he rel power tht you n gin omes from the the ility to send the output of one ommnd into the next ommnd s the inputF his is often lled piping nd it is done with the vertil rD |D symol tht is often red s pipeF erhps the most ommon usge of the pipe is to send n output tht is long into grep to sort for something in itF his exmple here will (nd ny (les in the urrent diretory tht were lst edited in heemer of PHHWF por the diretory listings we hve done so fr this type of thing wouldn9t e of muh useD ut it is more helpful in lrge diretories like the one this exmple ws exeuted onF

mlewis@mlewis-laptop:~$ ls drwxr-xr-x 6 mlewis mlewis drwxr-xr-x 4 mlewis mlewis -rwx------ 1 mlewis mlewis

-l | grep 2009-12 4096 2009-12-22 11:03 qtsdk-2009.05 4096 2009-12-23 17:33 QtWorkspace 2291366 2009-12-28 12:21 SwiftVis-0.3.0.jar

enother exmple is when some progrms tht re long running produe very long output (lesF iven if you use grep so ut the output down to just lines tht hve wht you re interested inD tht might still e mny pges of mterilF ou ould pipe tht output to progrms like hedD tilD or less to llow you to look tht them in mnner tht is esier to hndleF

CHAPTER 2.

GETTING TO KNOW THE TOOLS

RS

2.3 Text Editors (vi)


wost progrmming lnguges hve progrms tht re written in plin textF es result of thisD you n use ny simple text editor tht you wnt to edit your progrmsF ord proessorsD suh s wirosoft ord or ypen y0e re not plin text editorsF ou should not use them to edit your progrmsF ord proessors store ll types of dditionl informtion suh s the font nd formt of text in ddition to the text itselfF rogrms need only the stright textF yn indows mhineD xotepd is n exmple of text editorF ou ould use xotepd to edit l progrmsF xot ll text editors re eqully useful for progrmming thoughF sndeedD xotepd is prtiulrly poor hoieF hue to the ft tht progrmming is firly ommon usge for plin text editorsD mny text editors hve fetures in them tht re spei(lly imed t progrmmingF yn nixGvinux primry exmple of this is the vi editorF hile there re lots of di'erent editors tht one n hoose from on nixGvinuxD we will work with vi euse it is lightEweight nd is instlled on virtully ll suh mhinesF wny other editors will ring up seprte windows or ren9t prt of defult instlltionF ou re more thn welome to use whtever editor you wnt in going through this ookD we just wnt to introdue you to one possiility hereF o strt running viD simply type in vi followed y the nme of the (le you wnt to editF sf the (le existsD you will see its ontents on your sreenF sf notD you will get lnk plette redy for you to write onF yn most reent systems the instlltion of vi is tehnilly vimD n improved form of viF he things tht we will disuss will generlly pply to either oneF e ren9t going to get into dvned fetures tht will require vim though most students will (nd some of the dditions in vim to onform more to their likingF he (rst thing to know out vi is tht is hs two min modesF hen you (rst strt it upD you re in ommnd modeF o type things you need to e in n editing modeF hen you re in n editing mode you n type just like you would in xotepdF he prolem isD in n editing mode vi silly is xotepdF ht gives vi the extr power tht is helpful for progrmmers is the ility to use the ommnd modeF o get from ommnd mode into edit modeD type one of the followingF

i ! snsert efore the urrent hrterF s ! snsert t the eginning of the urrent lineF ! eppend fter the urrent hrterF e ! eppend t the end of the urrent lineF ! trt repling hrters from the urrent positionF
wost of the time you will proly just use iD ut there re osions when the others n e helpfulF he line t the ottom of your terminl should hnge to show you tht you re now in n edit modeF efter you get into edit mode you

CHAPTER 2.

GETTING TO KNOW THE TOOLS

RT

strt typingF sn vim you n lso use the rrow keys long with romeD indD ge pD nd ge hown to move roundF sf you re in true vi instll tht won9t work nd you will hve to return to ommnd mode to move the ursor roundF o get k into ommnd modeD simply hit espe @isAF he ottom line will let you know tht you re k in ommnd modeF sn ommnd mode you n move the ursor roundF sn vim the speil keys will still work for thisF sf you re in true vi instllD you will need to use the following norml keys to move roundF

h ! wove leftF j ! wove downF k ! wove upF l ! wove rightF gtrlEd ! ge downF gtrlEu ! ge upF
ou n do other edits while you re in ommnd modeF rere re some of the other keys tht do things for you in ommnd modeF

x ! helete hrterF dd ! helete line nd ple on the lipordF @reede with numer for multiple linesFA yy or ! nk lineF his opies to the lipordF @reede with numer for multiple linesFA p ! ste the lipord fter the urrent lineF ! ste the lipord efore the urrent lineF r ! eple single hrterF t ! toin linesF G ! erh for somethingF inter the serh string fter the GF n ! epet the lst serhF w ! ghnge the urrent wordF his removes up to the next white spe nd goes into insert modeF F ! repet the lst ommndF u ! ndo the lst ommndF gtrlEr ! edo the lst undone ommndF

CHAPTER 2.

GETTING TO KNOW THE TOOLS

RU

sf you type in numer efore ny ommnd in viD tht ommnd will e repeted tht numer of timesF his inludes going into n edit modeF o if you type IHH nd eD ny text you dd in will e dded IHH timesF sf tht isn9t wht you wntedD you will proly (nd tht the u ommnd omes in hndyF ome ommnds work well in ptternsF por exmpleD if you wnt to do (nd nd reple where you look t eh instne efore doing the repleD you might use G to serh for the (rst instneD then use w to reple the word in question nd hit isF efter tht you use n to move to the next instne of the string nd F to repet the w ommnd if you wnt to repet tht instneF he F ommnd is something tht would only hve miniml vlue in writing term pperD ut omes in hndy lot more with progrmming tsksF here re lso whole set of ommnds tht you invoke y typing olonF por exmpleD you might hve wondered how you sve (les or how you get out of vi ll togetherF rere re just few of the olon ommnds tht you might (nd helpfulF

Xn ! tump to the nth line of the (le where n is numerF Xw ! ve the (le s it isF Xq ! fe quit of viF on9t work if you hve mde hnges sine the lst sveF Xq3 ! nsfe quite of viF his will quit nd throw wy ny unsved hngesF Xwq ! ve the (le nd quit viF
ou should spend some time getting used to these ommndsF sf you relly wnt to see wht vi n doD red the mn pgeF wny students who re new to vi fll into the pit of hitting i s soon s they strt up nd then using it like xotepd until they re redy to sveF his pproh ignores ll the powerful fetures of vi nd in the long run slows you downF ry to get used to hitting is whenever you puse in your typingF sf nothing elseD it will llow you to lso hit Xw so you sve your hnges frequentlyF

2.4 Scala Tools


hen you instll l on your mhine there re severl di'erent progrms tht get instlled in the in diretoryF o egin withD we will only onern ourselves with two of theseX sl nd slF he sl ommnd tully runs sl progrmsF he sl ommnd is used to ompile sl lss (les into yteode tht is omptile with either the tv or Fxi pltformF st will e while efore we egin writing our own lsses nd using sl to ompile lrger progrmsF roweverD we will egin using the sl ommnd immeditelyF here re three wys in whih the sl ommnd n e usedF sf you just type in the sl ommnd nd press enter you will e dropped into the l

CHAPTER 2.

GETTING TO KNOW THE TOOLS

RV

iv @edEixeuteErint voopAF his is n environment where you n type in single l ommnds nd immeditely see their vluesF his is how we will strt o' interting with l nd it is something tht we will ome k to throughout the ook euse it llows us to esily experiment nd ply round with the lngugeF he ft tht it gives us immedite feedk is lso quite helpfulF o see how this worksD exeute slF st should print out some informtion for youD inluding telling you tht you n get help y typing in XhelpF st will then give you prompt of the form slbF sf you type in Xhelp you will see numer of other ommnds you ould give tht egin with olonF et this time the only one tht is signi(nt to us is Xquit whih we will use when we re done with the iv nd wnt to go k to the norml ommnd promptF st is ustomry for the (rst progrm in lnguge to e rello orldF o s not to rek with trditionD we n strt y doing this nowF ype the following fter the slb promptF

println(Hello World!);
sf you do this you will see tht the next line prints out rello orld3F his exerise is less thn exiting in the iv euse it lwys prints out the vlues of thingsD ut it is resonle thing to strt withF st is worth sking wht this relly didF rintln is funtion in l tht tells it to print something to stndrd output nd follow tht something with newlineF sn this seD the thing tht ws printed ws the string rello orld3F ou n mke it print other thingsD if you wishF yne of the dvntges of the iv is tht it is esy to ply round inF qo hed nd test printing some other things to see wht hppensF e will ome k nd do lot more with this in the next hpterF he seond usge of the sl ommnd is to run smll l progrms s sriptsF he term sript is generlly used in regrds to short progrms tht perform spei( tsksF here re lnguges tht re designed to work well in this type of usge nd they re often lled sripting lngugesF he design of l mkes it quite usle s sripting lngugeF nlike most sripting lngugesD howeverD l lso hs mny fetures tht mke it idel for developing lrge softwre projets s wellF o use l for sriptingD simply type in little l progrm into text (le tht ends with Fsl nd run it y putting the (le nme fter the sl ommnd on the ommnd lineF

Exercises
IF wke diretory for your lss in your user diretoryF PF inter the rello orldF progrm in tht diretory nd run it using lF QF se wget to downlod the (le FFF gopy the (le to the nme FFF

Chapter 3

Scala Basics
xow tht we hve explored the tools tht we will e using someD it is time to put them to use nd egin our journey lerning how to progrm with the l lngugeF e will spend most of this hpter working in the iv environment nd lerning some of the sis of l nd progrmming in generlF owrd the end we9ll write our (rst little sript to solve prolem nd run tht s well to see how si progrms funtionF

3.1 Expressions, Types, and Basic Math


ell progrmming lnguges re uilt from ertin fundmentl prtsF sn inglish you put together words into phrses nd then omine phrses into sentenesF hese sentenes n e put together to mke prgrphsF o help you unE derstnd progrmmingD we will mke nlogies etween stndrd inglish nd progrmming lngugesF hese nlogies ren9t perfetF ou n9t push them too frF roweverD they should help you to orgnize your thinking erly in the proessF vter onD when your understnding of progrmming is more mtureD you n dispense with these nlogies s you will e le to think out proE grmming lnguges in their own termsF he most smllest piee of progrmming lnguge tht hs mening is lled tokenF e token is like word or puntution in inglishF hey re the smllest piees with ny meningF sf you rek up tokenD you hnge the mening of tht piee just like reking up word is likely to result in something tht is no longer word nd doesn9t hve ny mening t llF sndeedD mny of the tokens in l re wordsF yther tokens re symols like puntutionF et the end of the lst hpter we looked t the following line of odeF

println(Hello World!);
his line ontins numer of tokensX printlnD @D rello orld3D AD nd YF hen you think of putting words togetherD you proly think of uilding sentenes with themF e sentene is grouping of words tht stnds on its own RW

CHAPTER 3.

SCALA BASICS

SH

in written inglishF he equivlent of sentene in lD nd most progrmE ming lngugesD is the statementF e sttement is omplete nd oherent instrution tht we n give the omputerF hen you re entering ommnds into the ivD they re proessed s full sttementsF sf you enter something tht isn9t omplete sttement in the ivD insted of the norml promptD you will get vertil r on the next line telling you tht you need to ontinue the sttementF he print from ove is omplete sttement whih is why it worked the wy it didF xote tht this sttement ends with semiolonF sn inglish you re used to ending sentenes with periodD question mrkD or exlmtion pointF l follows mny other progrmming lnguges in tht semiolons denote the end of sttementF l lso does something lled semiolon infereneF ut simplyD if line ends in suh wy tht semiolon mkes senseD l will put one there for youF es result of thisD our print sttement will work just s well without the semiolonF

println(Hello World!)
ou should try entering this into the iv to verify tht it worksF hnks to the semiolon inferene in lD we will very rrely hve to put semiolons in our odeF he only time they will relly e needed is when we wnt to put two sttements on single line for formtting resonsF hile you proly think of uilding sentenes from words in inglishD the relity is tht you put words together into phrses nd then join phrses into sentenesF he equivlent of phrse in l is the expressions. ixpressions hve fr more signi(nt impt on progrmming lnguges thn phrses hve in inglishD or t the lest progrmmers need to e more ognizent of expressions thn inglish writers hve to e of phrsesF en expression is group of tokens in the lnguge tht hs vlue nd typeF tust like some phrses re mde from single wordD some tokens represent things tht hve vlues on their own nd s suhD they re expressions themselvesF he most si of these re wht re lled literalsF yur smple line ws not only sttementD without the semiolon it ws lso n expressionF sn lD ny vlid expression n e used s sttementD ut some sttements re not expressionsF he rello orld3 prt of our full sttement ws lso n expressionF st is something lled string literl whih we will lern more out lter in this hpterF vet9s tke it of time to explore these onepts in the ivF un the sl ommnd without ny rgumentsF his will put you in the iv with prompt of slbF sn the lst hpter we typed in line tht told l to print somethingF his ws mde from more thn one token so we wnt to strt simpler hereF ype in whole numerD like SD followed y semiolon nd hit enterF ou should see something like thisX

scala> 5; res0: Int = 5

CHAPTER 3.

SCALA BASICS

SI

he (rst line is wht you typed in t the promptF he seond line is wht the l iv printed out s responseF ell tht iv stnds for edE ivluteErint voopF hen you type something inD the iv reds wht you typedD then evlutes it nd prints the resultF he term loop implies tht this hppens over nd overF efter printing the resultD you should hve een given new promptF o wht does this seond line menc he iv evluted the sttement tht you inputF sn this seD the sttement is just n expression followed y semiolon nd the iv ws printing out the vlue of the expression you enteredF es ws mentioned oveD the iv needs you to type in full sttements so tht it n evlute itF sn this seD we typed in very simple sttement tht hs n expression lled numeric literal followed y semiolonF his semiolon will e inferred if you don9t dd it inF e will tke dvntge of tht nd leve them out of sttements elowF he end of the output line gives us the vlue of the expression whih isD unsurprisinglyD SF ht out the stu' efore thtc ht does resHX snt menc he resH prt is nmeF st is short for resultHF hen you type in n expression s sttement in the l iv s we did hereD it doesn9t just evlute itD it gives it nme so tht you n refer k to it lterF he nme resH is now ssoited with the vlue S in this run of the ivF e9ll ome k to this lterF por now we wnt to fous on the other prt of the line X sntF golons re used in l to seprte things from their typesF e9ll see lot more of this through the whole ookD ut wht mtters most to us now is the typeD sntF his is the type nme tht l uses for si numeri integersF ou n try typing in few other integer vlues to see wht hppens with themF wost of the time the results won9t e ll tht interestingD ut if you push things fr enough you might get surprise or twoF ht hppens if you type in numer tht isn9t n integerc por exmpleD wht if you type in SFTc ry it nd you should get something like thisX

scala> 5.6 res1: Double = 5.6


e hve di'erent nme now euse this is new resultF e lso get di'erent typeF snsted of sntD l now tells us tht the type is houleF sn shortD houle is the type tht l uses y defult for ny nonEinteger numeri vluesF iven if vlue tehnilly is n integerD if it inludes deiml pointD l will interpret it to e houleF ou n type in SFH to see this in tionF ry typing in some other numeri vlues tht should hve houle s the typeF ee wht hppensF yne ginD the results should e firly mundne unless you push fr enoughF o fr ll of the expressions we hve typed in hve een single tokensF xow we will uild some more omplex expressionsF e will egin y doing si mthemtil opertionsF ry typing in SCTF

scala> 5+6 res2: Int = 11

CHAPTER 3.

SCALA BASICS

SP

his line involves three topisF ih hrter in this se is seprte tokenF sf you spe things outD it won9t hnge the resultF roweverD if you use numer with multiple digitsD ll the digits together re single token nd inserting spes does hnge the meningF here shouldn9t e nything too surprising out the result of SCTF e get k vlue of II nd it hs type of sntF ry the other si rithmeti opertions of ED BD nd GF ou9ll notie tht you keep getting k vlues of type sntF his mkes sense for dditionD sutrtionD nd multiplitionF roweverD the result of SGP might surprise you little itF ou normlly think of this expression hs hving the vlue of PFS whih would e houleF roweverD if you sk lD SGP is the snt PF hy is this nd wht hppened to the HFSc hen oth opernds re of type sntD l keeps everything s sntsF sn the se of divisionD the deiml nswer you might expet is trunted nd the frtionl prt is thrown wyF xote tht it isn9t roundedD ut truntedF hy is thisc st is euse in integer rithmetiD the vlue of SGP isn9t PFSF st is PrIF ht is to sy tht when you divide (ve y twoD you get two groups of two with one reminderF et some point in your elementry edutionD when you (rst lerned out divisionD this is how you were tully told to think out itF et tht time you only hd integers to work with so this is wht mde senseF l is just doing wht you did when you (rst lerned divisionF st is giving you the whole numer prt of the quotient with the frtionl prt removedF his frtionl prt is normlly expressed s reminderF row n we sk l to give us thtc here is nother opertion lled modulo tht is represented y the perent sign tht gives us the reminder fter divisionF rere we n see it in tionF

scala> 5%2 res3: Int = 1


he modulo opertor is used quite it in omputing euse it is rther hndy for expressing ertin idesF ou should tke some time to reEfmilirize yourself with itF ou might e temped to sy tht this would e your (rst time deling with itD ut in relityD this is extly how you did division yourself efore you lerned out deiml nottion for frtionsF ht if you relly wnted PFS for the divisionc ellD PFS in l is houleF e n get this y doing division on houlesF

scala> 5.0/2.0 res4: Double = 2.5


ell of our si numeril opertions work for houles s wellF ly round with them some nd see how they workF ou n lso uild lrger expressionsF ut in multiple opertorsD nd use some prenthesesF yne lst thing efore we move on to other types is to see wht hppens when you omine houle nd n snt in n expressionF gonsider this exmpleX

scala> 5.0/2 res5: Double = 2.5

CHAPTER 3.

SCALA BASICS

SQ

rere we hve houle divided y n sntF he resultD s you n seeD is houleF hen you omine numeri vlues in expressionsD l will hnge one to mth the otherF he hoie of whih one to hnge is firly simpleF st hnges the one tht is more restritive to the one tht is less restritiveF sn this seD nything tht is n snt is lso houleD ut not ll vlues tht re houles re lso sntsF o the logil pth is to mke the snt into houle nd do the opertion tht wyF

3.2 Objects and Methods


yne of the fetures of the l lnguge is tht ll the vlues in l re objectsF he term ojet in referene to progrmming mens something tht omines dt nd the funtionlity on tht dtF sn l we refer to the things tht n ojet knows how to do s methodsF he norml syntx for lling method on n ojet is to follow the ojet y period @whih we normlly red s dotA nd the nme of the methodF ome methods need extr informtionD whih we lled rgumentsF sf method needs arguments then those re put fter the method nme in prenthesesF sn mny progrmming lngugesD numeri literls like the ones we hve used so fr wouldn9t e ojetsF hey would e simple vluesD lled primitivesD tht we ouldn9t ll methods onF sn l thoughD even the most si literls re treted s ojets in our progrm nd we n therefore ll methods on themF en exmple of when we might do this is when we need to onvert one type to notherF sn the smple elow we onvert the houle vlue SFT into n snt y lling the tosnt methodF sn this simple ontext we would generlly just use n snt literlD ut there will e situtions we enounter lter on where we re given vlues tht re houles nd we need to onvert them to sntsF e will e le to do tht with the tosnt methodF

scala> 5.6.toInt res2: Int = 5


yne thing you should note out this exmple is tht onverting houle to n snt does not roundF snstedD this opertion performs truntionF ht is to sy tht ny frtionl prt of the numer of ut ll nd only the whole integer is leftF e sw t the eginning of this hpter tht l is )exile when it omes to the requirement of putting semiolons t the end of sttementsF l will infer semiolon t the end of line if one mkes senseF his type of ehvior mkes ode esier to write nd llows it to )ow etterF sn lD the dot etween n ojet nd method is lso optionlF o we n write the following instedX

scala> 5.6 toInt res3: Int = 5


iven the prentheses on the rguments to method re optionl ssuming tht there is only one rgumentF his type of )exiility mkes ertin prts of l

CHAPTER 3.

SCALA BASICS

SR

more oherent nd provides the progrmmer with signi(nt )exiilityF hough you didn9t relize itD you were using this ft in the lst setionF o see thisD go into l nd type SF then press tF l hs t ompletion just like vinux doesF o wht you see is list of ll the methods tht ould e lled on the sntF st should look something like the followingF

scala> 5. != + <= >>> isInstanceOf toInt unary_-

## == ^ toByte toLong unary_~

% / > asInstanceOf toChar toShort |

& < >= equals toDouble toString

* << >> hashCode toFloat unary_+

e won9t go into ny detil on most of these hereD ut some you hve lredy seen nd usedF e just (nished using tosnt on houleF e n ll tohoule on n snt s wellF he things tht might stnd out though re the si mth opertions tht were used in the previous setionF he CD ED BD GD nd 7 we used ove re nothing more thn methods on the snt typeF he expression SCT is relly S FC @TA to lF sn ftD you n type this into l nd see tht you get the sme resultF

scala> 5 .+ (6) res1: Int = 11


he spe etween the S nd the F is requires only euse without it l thinks you wnt houleF snsted of sping this outD you n put the S in prenthesesF o when you type in SCTD l sees ll to the method C with one rguE ment of TF e get to use the short form simply euse l llows oth the dot nd the prentheses to e optionl in ses like thisF

3.3 Other Basic Types


xot everything in l is numerF here re other nonEnumeri types in l whih lso hve literlsF e9ll strt simple nd move up in omplexityF erhps the simplest type in l is the foolen typeF yjets of the foolen type re either true or flse nd those re lso vlid literls for foolensF

scala> true res6: Boolean = true scala> false res7: Boolean = false
e will see lot more on foolens nd wht we n do with them in hpter S when we introdue foolen logiF

CHAPTER 3.

SCALA BASICS

SS

enother type tht isn9t expliitly numeri is the ghr typeF his type is used to represent single hrtersF e n mke hrter literls y pling the hrter inside of single quotes like we see hereX

scala> 'a' res8: Char = a


he wy tht omputers workD ll hrter dt is relly numers nd di'erent numers orrespond to di'erent hrtersF e n (nd out wht numeri vlue is ssoited with given hrter y using the tosnt methodF es you n see from the line elowD the lowerse  hs numeri vlue of WUF

scala> 'a'.toInt res0: Int = 97


feuse hrters hve numeri vlues ssoited with themD we n lso do mth with themF hen we do thisD l will onvert the hrter to its numeri vlue s n snt nd then do the mth with the sntF he result will e n sntD s seen in this exmpleF

scala> 'a'+1 res1: Int = 98


sn the lst setion you might hve notied tht the snt type hs method lled toghrF e n use tht to get k from n integer vlue to hrterF ou n see from the following exmple tht when you dd I to 99 you get the logil result of 99F

scala> ('a'+1).toChar res0: Char = b


he ghr type n only e single hrterF sf you try to put more thn one hrter inside of single quotes you will get n errorF st is lso n error to try to mke ghr with empty single quotesF roweverD there re lots of situtions when you wnt to e le to represent mny hrtersF his inludes wordsD sentenesD nd mny other thingsF por this there is di'erent type lled tringF tring literls re formed y putting zero or more hrters inside of doule quotes like we see in this exmpleF

scala> "Scala is a programming language" res3: java.lang.String = Scala is a programming language


ou will notie tht the type is listed s jvFlngFtringF l integrtes losely with tv nd uses some of the tv lirry elements in stndrd odeF st lso llows you to freely ll ode from the tv lirriesF he type tring hs full nme of jvFlngFtringD ut l will utomtilly provide the jvFlng prt so we will generlly leve it outF gertin opertions tht look like mthemtil opertions re supported for tringsF por exmpleD when you use C with stringsD it does string ontentionF st simply gives us k new string tht is the omined hrters of the two tht re eing put together s shown hereX

CHAPTER 3.

SCALA BASICS

ST

scala> "abc"+"def" res8: java.lang.String = abcdef


his type of opertion works with other types s wellF his exmple shows wht hppens when we ontente tring with n sntF he snt is onverted to tring nd norml string ontention is performedF

scala> "abc"+123 res9: java.lang.String = abc123


his works whether the string is the (rst or seond rgument of the CF

scala> 123+"abc" res10: java.lang.String = 123abc


sn ddition to ontentionD you n multiply string y n integer nd you will get k new string tht hs the originl string repeted the spei(ed numer of timesF

scala> "abc"*6 res11: String = abcabcabcabcabcabc


his n e helpful for things suh s pdding vlues with the proper numer of spes to mke string spei( lengthF ou n do this y multiplying the string   y the numer of spes you needF here re other types tht re worth noting efore we move onF yne is the type nitF he nit type in l silly represents nothingF he equivlent in mny other lnguges is lled voidF e hve tully seen n exmple of ode tht uses nitF he (rst progrm we sw in hpter P used funtion lled printlnF hen we lled println l did somethingD ut didn9t give us k vlueF his is wht hppens when we type in n expression tht gives us k vlue of nit in the ivF he lst type in l tht we will del with here is something of olletion of di'erent types lled tupleF e tuple is olletion of spei(ed numer of spei( typesF fsillyD olletion of vlues tht is strit out how mny nd wht type of vlues it hsF e n mke tuples in l y simply putting vlues in prentheses nd seprting them with omms s seen in the following exmplesF

scala> (5,6,7) res5: (Int, Int, Int) = (5,6,7) scala> ("book",200) res6: (java.lang.String, Int) = (book,200) scala> (5.7,8,'f',"a string") res7: (Double, Int, Char, java.lang.String) = (5.7,8,f,a string)
he tuples in l provide simple wy of deling with multiple vlues in single pkge nd they will ome up osionllyF xote tht the wy we express

CHAPTER 3.

SCALA BASICS

SU

tuple type in l is to put the types of the vlues of the tuple in prentheses with omms etween themD just like we do with the vlues to mke tuple ojetF uples with only two elements n hve speil menings in some prts of lF por tht resonD there is n lternte syntx you n use to de(ne theseF sf you put the token Eb etween two vluesD it will produe PEtuple with those vluesF gonsider the following exmpleF

scala> 3 -> "three" res3: (Int, java.lang.String) = (3,three)


he Eb will only produe tuples with two elements thoughF sf you try using it with more thn two elements you n get interesting resultsF

scala> 4 -> 5 -> 6 res4: ((Int, Int), Int) = ((4,5),6)


o if you wnt tuples with more thn two elementsD stik with the prentheses nd omm nottionF

3.4 Back to the Numbers


hepending on how muh you plyed round with the elements in setion QFI you might or might not hve found some interesting surprises where things ehved in wys tht you weren9t expetingF gonsider the followingX

scala> 1500000000+1500000000 res9: Int = -1294967296


wthemtiins would onsider this to e n errorF st is tully re)etion of the wy tht numers re implemented on omputersF feuse the detils of this implementtion n impt how your progrms workD it is worth tking it of time to disuss itF et fundmentl levelD ll informtion on omputers is represented with numersF e sw this with the hrters eing numersF yn modern omputE ers ll these numers re represented in inryD or se twoF he eletronis in the omputer lternte etween two sttes tht represent I nd H or on nd o'F golletions of these represent numersF e single vlue of either H or I is lled itF st is single digit in inry numerF he term yte refers to grouping of V its whih n represent PST di'erent numersF sn l these will e etween EIPV nd IPUF o understnd thisD we need to do little review of how inry numers workF ou hve likely spent your life working with deiml numers or se tenF sn this systemD there re ten possile vlues for eh digitX HD ID PD QD RD SD TD UD VD nd WF higits in di'erent positions represent di'erent power of tenF o the numer QTS is relly 3 102 + 6 101 + 5 100 F here is nothing prtiulrly

CHAPTER 3.

SCALA BASICS

SV

Value 296 40 40 40 8 8 0 0 0

Power of 2 256 128 64 32 16 8 4 2 1

Digit 1 0 0 1 0 1 0 0 0

pigure QFIX sllustrtion of the onversion from deiml to inry using sutrE tion methodF his method works from the top downF o get the numer in inry just red down the list of digitsF unique out the se ten other thn perhps it reltes well to the numer of digits on humn hndsF ou n just s well use other ses in whih se you need n pproprite numer of symols for eh digit nd eh position represents power of tht seF finry uses se of twoF por this we only need two di'erent digitsX H nd IF his is onvenient on omputers where the eletronis n e0iently represent two sttesF he di'erent positions represent powers of twoX ID PD RD VD ITD QPD FFF o the numer IIHIHIaQPCITCRCIaSQF his exmple shows how you onvert from inry to deimlF imply dd together the powers of two for whih the its re oneF e yte stores eight its tht would represent powers of two from IPV down to IF he word would is used here euse there is signi(nt nune to this deling with negtive numers tht we will disuss shortlyF row n we go from deiml to inryc here re two si pprohes to thisF yne involves repeted sutrtion of powers of two while the other involves repeted division y twoF e will strt with the (rst one nd use the vlue PWT in deiml for the onversionF e strt y (nding the lrgest power of P tht is smller our vlueF sn this se it is 256 = 28 F o we will hve one in the 28 position or the Wth digit1 F xow we sutrt nd get 296 256 = 40 nd repetF he lrgest power of P smller thn RH is 32 = 25 F o the digits for 27 nd 26 re HF utrt gin to get 40 32 = 8F e now hve 8 = 23 so the (nl numer in inry is IHHIHIHHHF his proedure is written out the wy you might tully do it in (gure QFIF he other pproh is it more lgorithmi in nture nd is proly less prone to errorF st works sed on the ft tht in inryD multiplying nd dividing y P moves the inry point the sme wy tht multiplying or dividing y IH moves the deiml point in the deiml numer systemF he wy it works is you look t the numer nd if it is odd you write I nd if it is even you write HF hen you divide the numer y PD throwing wy ny reminder
1 Remember
that the rst digit is

20 = 1

CHAPTER 3.

SCALA BASICS

SW

Value 1 2 4 9 18 37 74 148 296

Digit 1 0 0 1 0 1 0 0 0

pigure QFPX sllustrtion of the onversion from deiml to inry using the reE peted division methodF his method works from the ottom up so you get the its in the result strting with the smllestF or frtionl prtD nd repet with eh new digit written to the left of those efore itF ho this until you get to HF he numer PWT is even so we strt o' y writing H nd divide y P to get IRVF ht is lso even so write nother HF hivide to get URF his is lso even so write nother HF hivide to get QUF his is odd so write IF hivide to get IV whih is even so you write HF hivide to get W nd write IF hivide to get R nd write HF hivide to get P nd write HF hivide to get I nd write tht oneF he next division gives you zero so you stopF his proedure is illustrted in (gure QFPF xow tht you know how to go from inry to deiml nd deiml to inryD let9s tke minute to do little rithmeti with inry numersF st is ertinly possile to do this y onverting the inry to deimlD doing the rithmeti in deimlD then onvert k to inryF roweverD this is quite ine0ient nd it relly isn9t hrd to work in inryF sf nythingD it is esier to work in inry thn in deimlF vet9s egin with the opertion of dditionF s wnt to dd the numers IIHIHI nd IHIIIHF o do this we do extly wht you would do with long ddition in deimlF he di'erene is tht two in inry is IH so there is lot more rryingF

110101 + 101110 ------1100011


wultiplition in inry n lso e done just like in deiml nd you hve lot fewer multiplition fts to memorizeF ero times nything is zero nd one times nything is tht numerF ht is ll we hve to knowF vet9s do multiplition with the sme numers we just worked withF pirst we9ll get ll the numers tht need to e dded upF

110101

CHAPTER 3.

SCALA BASICS

TH

* 101110 ----------1101010 11010100 110101000 11010100000


edding these numers is est done in pirsF he reson is tht s soon s you dd together Q or more numers in inry you hve the pility to hve to do something you ren9t ustomed to doing in deimlX rry vlue up two digitsF sn deiml you would hve to hve olumn sum up to one hundred or more for this to hppenF roweverD in inry you only hve to get to four @whih is written s IHH in inryAF ht hppens in this prtiulr instne in the Tth digitF o redue the odds of n error it is etter to dd the vlues two t time s we hve shown hereF

1101010 + 11010100 ----------100111110 + 110101000 ----------1011100110 +11010100000 ----------100110000110


ou n do division in the sme wy tht you do long division with integersD ut we won9t over tht hereF e still hven9t ddressed the question of how we represent negtive numers on omputerF he desription tht we hve given so fr only dels with positive vluesF xumers tht re interpreted this wy re lled unsignedF ell the numeri types in l re signed so we should (gure out how tht works2 F o do thisD there re two things tht should e kept in mindF he (rst is tht our vlues hve limited preisionF ht is to sy tht they only store ertin numer of itsF enything eyond tht is lostF he seond is tht negtive numers re de(ned s the dditive inverses of their positive ounterprtsF sn other wordsD xC@ExAaH for ny xF o demonstrte how we n get negtive numersD lets work with the numer IIHIHI @SQ in deimlF nlike efore thoughD now we will limit ourselves to single yteF o we hve V digits to work with nd the top digits re zerosF yur numer stored in yte is relly HHIIHIHIF o the question of wht should e the negtive is nswered y (guring out wht vlue we would dd to this in order to get zeroF
2 The
Char is actually a 16 bit unsigned numeric value, but the normal numeric types are all signed.

CHAPTER 3.

SCALA BASICS

TI

00110101 + ???????? -------00000000


yf ourseD there is nothing tht we n put into the question mrks to mke this workF roweverD if we go k to our (rst ft we n see wht we must doF e don9t need zeroD we need eight digits of zeroF o in relityD wht we re looking for is the followingF

00110101 + ???????? -------100000000


his prolem is solvle nd the top I will e thrown wy euse we n only store V its in yteF o the nswer is given hereF

00110101 + 11001011 -------100000000


xote tht top top it is on in the negtive vlueF he top it isn9t extly sign itD ut if numer is signedD the top it will tell us quikly whether the numer is positive or negtiveF his style of mking negtives is lled 2s-complimentF sn the erly dys of digitl omputing other options were tried suh s dding sign it or method lled IsEompliment where the its re simply )ippedF roweverD PsEompliment is used in mhines tody euse it llows numeri opertions to e done with negtive numers using the sme iruitry s is used for positive numersF his proess gives us the orret nswer nd is sed on the proper de(nition of wht negtive numer isF pinding negtives using the de(nition of wht negtive vlue is works nd n e fllkD ut there is simpler methodF o get the PsEompliment negtive of inry numer of ny sizeD simply )ip ll the its nd dd oneF ou n verify tht this pproh works for our exmple oveF here re lrger groups of its eyond the eight in ytes tht hve mening in lF sn ftD if you go k to setion QFP nd you look t the di'erent methods on n sntD you will see tht tohoule nd toghr ren9t the only onversions we n doF l hs other integer types of fyteD hortD nd vongF e fyte in l is n eight it numerF e hort is IT it numerF he snt tht we hve een using is QP it numerF he vong type is TR it numerF he reson for the odd ehvior tht ws demonstrted t the eginning of this setion is tht we dded two numers together whose sum is igger thn wht n e stored in the lower QI its of n snt nd the overflowD s it is lledD

CHAPTER 3.

SCALA BASICS

TP wx IPU QPUTU PIRURVQTRU WPPQQUPHQTVSRUUSVHU

ype fyte hort snt vong

fits V IT QP TR

win EIPV EQPUTV EPIRURVQTRV EWPPQQUPHQTVSRUUSVHV

le QFIX snteger types with their sizes nd rngesF wrpped it round to negtive vlueF he tle elow shows the minimum nd mximum vlues for eh of the di'erent integer typesF ysionlly you will need to use literls tht re igger thn wht n snt n storeF ou n do this with vongF wking numeri literl into vong is done y simply dding n v to the endF ou n see this hereF

scala> 5000000000L res8: Long = 5000000000


he vlue (ve illion is not vlid integerF sf you leve o' the v here you get n errorF he v n e lower seD ut then it looks lot like the numer one so it is etter to use the upper seF e tlked out inry ove nd l hs method tht will let you see the inry form of numerF his method works on the four norml numeri types nd ghrF rere we use it to see the inry representtion for SQ nd ESQ for the vlues s oth snt nd vong typesF

scala> 53.toBinaryString res15: String = 110101 scala> (-53).toBinaryString res16: String = 11111111111111111111111111001011 scala> 53L.toBinaryString res17: String = 110101 scala> (-53L).toBinaryString res18: String = 1111111111111111111111111111111111111111111111111111111111001011
he tofinrytring method does not disply leding zerosD so the positive vlues only show six digits in oth formtsF roweverD the negtive form hs mny leding ones nd ll of these re printedF finry is wht the mhine usesD ut it relly isn9t ll the useful to humnsD in lrge prt euse the numer of digits in inry numer is often lrgeD even if the numer itself isn9t wht we onsider lrgeF here re two other ses tht re ommonly seen in progrmming nd deling with omputerF hey re se VD otlD nd se ITD hexdeiml or hexF vike deimlD these ses llow you to represent firly lrge numers with reltively few digitsF nlike deimlD onverting from otl or hex to inry nd k is trivilF he reson for this is tht eight nd IT re powers of twoF vet9s strt with otlF

CHAPTER 3.

SCALA BASICS

TQ

hen working in se VD the digits n e etween H nd U with eh suE sequent digit eing higher power of VF he ese of onverting to nd from inry omes from the ft tht eight is 23 F sn inry the vlues H to U re represented with three its etween HHH nd IIIF he fourth nd susequent its represent vlues tht re multiples of eightF feuse of thisD we n onvert inry numer to n otl numer y grouping the its into groups of three nd onverting those groupsF he only th is tht this grouping hs to strt with the ones digitF o our fvorite inry numer of IIHIHI is TS in otlF he lowest three itsD IHID onvert to S nd the next threeD IIHD onvert to TF e n use the toytltring method to on(rm thisF

scala> 53.toOctalString res21: String = 65


o go the other wyD from otl to inryD we simply onvert the otl digits to three digit inry numersF o the otl vlueD QUPT onverts to HIIIIIHIHIIHF e n emphsize the groupings of its y sping them outX HII III HIH IIHF orking in hexdeiml is similrly simpleF he only th is tht now single digit needs to hve IT possile vluesF o the HEW tht we re used to won9t su0eF st is typil to ugment the norml digits with the letters eEp where e is ten nd p is (fteenF feuse 16 = 24 D we use groups of R its when onverting etween hexdeiml nd inryF yne ginD you strt the proess with the lower its nd work upF o IIHIHI eomes QSF he lrge numer we got from otl oveD HIII IIHI HIIH eomes UhT in hexF eginD there is method lled torextring tht n e used on the numeri types to quikly get the hexdeiml representtion of numerF hile toytltring nd torextring give us otl nd hexdeiml repreE senttions of numeri vlues tht we hve in deimlD it is sometimes helpful to e le to enter vlues into progrms using otl or hexdeimlF st is possile to enter literls in l using these sesF o get n otl literl pre(x the numer with leding zeroF o get hexdeiml literl pre(x it with HxF he following uses of this on(rm the onversions tht we did for the lrger numer oveF

scala> res23: scala> res24:

03726.toBinaryString String = 11111010110 0x7D6.toBinaryString String = 11111010110

lues in hex or otl re prtiulrly signi(nt when you wnt to mke sure tht you know how mny its will e in the inry representtion of the numerF ou now hve rther omplete desription of the integer numer types nd how they re represented in the mhineF ht out nonEinteger numeri vlues thoughc e sw previously tht if we type in numeri vlue tht inludes deiml point l tells us tht it hs type houleF he houle literl formt is more powerful thn just inluding deiml points thoughF st lso llows you to use sienti( nottion to enter very lrge or very smll numersF

CHAPTER 3.

SCALA BASICS

TR win EQFRHPVPQSiQV EIFUWUTWQIQRVTPQISUiQHV wx QFRHPVPQSiQV IFUWUTWQIQRVTPQISUiQHV

ype plot houle

e fits V II

m fits PQ SP

is IPU IHPQ

le QFPX ploting point types with sizes nd rngesF imply follow numer y n e nd the power of ten it should e multiplied yF o ISHHHFH n lso e written s IFSeRF he nme houle is short for doule preision )oting point numerF he full nme inludes informtion out the wy tht these numers re stored in the memory of omputerF vike ll vlues in omputerD the houle is stored s olletion of itsF o e spei(D houle uses TR itsF his size is relted to the doule preision prtF here is nother type lled plot tht is single preision )oting point numer nd only uses QP itsF sn oth sesD the internl representtion uses )oting point formtF sn mny wysD this is similr to sienti( nottionD ut in inry insted of deimlF he its in )oting point numer re grouped into three di'erent prtsF e will ll them sD eD nd m nd the vlue of the numer is given y (1)s (1 + m) 2(ebias) F he (rst it in the numer is the sign itD sF hen tht it is onD the numer is negtive nd when it is o' it is positiveF efter the sign it is group of its for the exponentD eF snsted of using PsEompliment for determining if the exponent is negtiveD the exponent is ised y vlue tht is piked to mth with the numer of its in the exponentF sing is insted of PsEompliment mens tht omprisons etween )oting point vlues n e done with the sme logi used for integer vlues of tht sizeF ell remining its re used to store mntissD mF he stored mntiss is the frtionl prt of the numer in normlized inryF o the highest vlue it is IGPD the next is IGRD nd so onF he tle elow gives the numer of its used for e nd mD the isD nd the rnge of numers they n represent in the houle nd plot typesF he i nottion is short for multiplition y IH to tht powerF es we hve seenD )oting point literls re y defult onsidered to e of type houleF sf you spei(lly need plot you n ppend n f to the end of the literlF here re mny other detils ssoited with )oting point vlues tht one might go intoF here is only one min point tht will e stressed here thoughF ht is the ft tht )oting point vluesD whether houle or plotD re not el numers in the sense you re used to in mth with ritrry preisionF ploting point numers hve limited preisionF vike the integersD they n e over)owedF nlike the integersD they re fundmentlly impreise euse they represent frtionl vlues with (nite numer of itsF o understnd thisD let9s look t sitution where you should hve seen this eforeF gonsider the simple frtionD IGQF xow onsider the representtion of this vlue s deimlF he deiml representtion is HFQQQQQFFF sn order to write this frtion urtely in deimlD you need n in(nite numer of digitsF sn mth we n denote things like this y putting in three dots or putting line over the digits tht re repetedF por )oting point vlues thoughD the digits

CHAPTER 3.

SCALA BASICS

TS

simply ut o' when you get to the end of the mntissF es suhD they ren9t ext nd the iruitry in the omputer employs rounding sheme to del with thisF his impreision isn9t visile most of the timeD ut one immedite implition of it is tht you n9t trust two )oting point numers to e equl if they were lulted using rithmetiF st lso mens tht you shouldn9t use )oting point numers for progrms tht involve moneyF he deiml vlue HFI is repeting frtion in inry nd s suhD isn9t perfetly representedF ht is generlly onsidered d thing when deling with people9s moneyF snsted you should use n integer type nd store ents insted of dollrsF

3.5 The math Object


hile on the topi of numersD there re quite few stndrd funtions tht you might wnt to do with numers eyond dditionD sutrtionD multiplitionD nd divisionF here re few other things you n get from opertors tht we will disuss lterD other things like squre rootD logrithmsD nd trigonometri funtions re not opertorsF ou n ertinly do them in l thoughF hey re found s methods in the mth ojetF ou n use t ompletion in the iv to see ll the di'erent methods tht you n ll on mthF

scala> math. BigDecimal E Fractional Integral Numeric Ordering PartiallyOrdered ScalaNumber abs asin atan2 ceil cosh expm1 hypot log10 max package random round sin sqrt tanh toRadians

BigInt Equiv IEEEremainder LowPriorityOrderingImplicits Ordered PartialOrdering Pi ScalaNumericConversions acos atan cbrt cos exp floor log log1p min pow rint signum sinh tan toDegrees ulp

CHAPTER 3.

SCALA BASICS

TT

viterl f n r t  9

wening kspe form feed line feed rrige return t doule quote single quote kslsh

niode rex inoding uHHHV uHHHg uHHHe uHHHh uHHHW uHHPP uHHPU uHHSg

le QFQX le of speil hrter espe sequenes in lF wny of these won9t mke sense nd you shouldn9t worry out themF roweverD mny of them should e identi(le y the nmeF o if we wnted to tke squre root of numerD we ould do the followingF

scala> math.sqrt(9) res15: Double = 3.0


ou would use similr syntx for tking osines nd sinesF he funtions provided in the mth ojet should e su0ient for the needs of most peopleF ynly two of the ontents of mth tht strt with pitl letters re worth noting t this pointF i nd i re numeri onstnts for nd eF

scala> math.Pi res16: Double = 3.141592653589793

3.6 Details of Char and String


here is lot more to ghr nd tring thn we overed in the setion QFQF ome of whih you relly should know efore we go furtherF e sw how we n mke hrter literls or string literls tht ontin keys tht pper on the keyord nd tht go niely into text (leF ht out things tht we n9t type s niely or tht hve other meningsc por exmpleD how do you put doule quotes in stringc yping the doule quote loses o' the string insted of putting one inF row would you mke hrter of single quotec row do you get new linec ou ren9t llowed to hve norml string rek ross linesF e n do ll of these things nd more with escape charactersF hese re denoted y kslsh in front of one or more hrtersF por exmpleD if you wnt to put doule quote in stringD simply put kslsh in front of doule quoteF me thing goes for single quote in hrterF ou n insert newline with nF ht if you wnt to insert kslsh itselfc imply put in two kslshesF he tle elow shows other ommonly used espe hrtersF

CHAPTER 3.

SCALA BASICS

TU

sn ddition to espe hrtersD the kslsh n e used to put ny type of speil hrter into stringF sf you know the niode vlue for speil hrterD you n put u followed y four hexdeiml digitl in string to speify tht hrterF por hrters from the lower PST hrters tht re represented in egss you n follow the kslsh y n otl numer etween H nd QUUF here re some times when using the espe hrters eomes pinF por exmpleD there re times when you need to uild strings tht hve numer of kslshesF ih one you wnt requires you to put in twoF his n get unwieldyF sn dditionD if you hve longD multiEline stringD it n e di0ult to formt the string the wy you wntF por these types of situtionsD l inludes speil form of string tht egins nd ends with three doule quotesF enything you type etween the set of three doule quotes is tken to e literlly prt of the string without ltertionF he following shows n exmple of using this to enter long string in the ivF

scala> """This is a long string. | It spans multiple lines. | If I put in \n and \\ or \" they are taken literally.""" res8: java.lang.String = This is a long string. It spans multiple lines. If I put in \n and \\ or \" they are taken literally.

3.7 Naming Values and Variables


e hve seen enough tht you n solve some simple prolemsF por exmpleD if you were given numer of di'erent grdes nd sked to (nd the vergeD you ould type in n expression to dd them ll up nd divide y the numer of them to get the vergeF e silly hve the ility to use l now to solve nything we ould solve with lultorF e will develop lot more over timeD ut we hve to strt somewhereF es it stnds we ren9t just limited to solving prolems we ould do with lultorD we re solving them the wy we would with lultorF e type in mthemtil expressions the wy we would write them on pper nd get k n nswerF el progrmming involves tying together multiple lines of instrutions to solve lrger prolemsF sn order to do thisD we need to hve wy to give nmes to the work we hve done nd refer k to themF here re three keywords in l tht give nmes to vluesF e will see the (rst two hereX vl nd vrF o egin withD let us look t the full syntx of vl nd vr in two smpleF hen we n pull them prtD tlk out wht they doD see how they re di'erentD nd disuss wht prts of them re optionlF

scala> val age:Int=5 age: Int = 5 scala> var average:Int=(2+3+4+5)/4

CHAPTER 3.

SCALA BASICS

TV

average: Int = 3
ynttilly the only di'erene etween these two is tht one sys vl nd the other sys vrF ht is followed y nme with olon nd type fter itF he rules for nmes in l re tht they need to strt with letter or n undersore followed y zero or more lettersD numersD nd undersoresF l is lso se sensitiveF o the nmes eqiD geD egeD nd gi re ll di'erentF sn generl it is onsidered very poor style to use nmes tht di'er only in pitliztionF sndeedD l orrows stndrd nming onvention from tv lled the mel nming styleF he nmes of vlues egin with lower se letter nd the (rst letter of susequent words re pitlizedF por exmpleD theglsseverge is nme tht follows this onventionF ype nmes use the sme onvention exept tht the (rst letter is pitlizedF his is lled mel style euse the pitl letters look like humpsF he types in oth of these exmples re followed y n equls sign nd n expressionF nlike mny other progrmming lngugesD this is not optionl in lF sn lD when you delre vl or vrD you must give it n initil vlue t tht pointF hile the initil vlue is not optionlD the type generlly isF his too is unlike most progrmming lngugesF es we hve lredy seenD l is le to (gure out the types of things for us in mny situtionsF sf we leve o' the olon nd the typeD l will simply use whtever type it determines is pproprite for the expression in the initil vlueF wost of the timeD the type tht it gives us will e extly wht we wntF sing this we ould insted hve the following shorter forms of these delrtionsF

scala> val age=5 age: Int = 5 scala> var average=(2+3+4+5)/4 average: Int = 3
he reson for using vl or vr delrtion is tht they give nme to the vlue tht we n refer k to lterF por exmpleD we ould now type in geCIH nd l would give us ISF he nmes serve two purposesF hey prevent us from typing in expressions over nd over ginF hey lso help give mening to wht we re doingF ou should try to pik nmes tht help you or other reders (gure out wht is going on with piee of odeF o fr we hve disussed ll the similrities etween vl nd vr nd you might e wondering in wht wy they re di'erentF he delrtions themselves re silly identilF he di'erene isn9t in the syntxD ut in the mening or semntisF e vl delrtion gives nme to referene to vlueF ht referene n9t e hngedF st will refer to the thing it ws originlly set to foreverF sn the ivD you n delre nother vl with the sme nmeD ut it doesn9t do nything to hnge the originlF e vr delrtionD on the other hndD llows the referene to hngeF sn oth ses we ren9t nming the vlueD we re nming ox tht stores referene the vlueF he signi(ne of this will e seen in setion UFVF

CHAPTER 3.

SCALA BASICS

TW

he t of hnging the referene stored in one of these oxes we ll vriles is referred to s n ssignmentF essignment in l is done with the sme equl sign tht ws used to set the initil vlueF sn n ssignment though there is no vr keywordF sf you identlly inlude either vr or vl you will e mking new vrileD not hnging the old oneF

scala> average=8 average: Int = 8 scala> average=2*average average: Int = 16


he (rst ssignment uses the ox nmed verge to hnge from referring to the ojet Q to the ojet VF he seond one uses the previously referred to vlue nd multiplies it y two then stores referene tht new vlue k into the vrileF here is it more to the initiliztion of vl nd vr delrtions thn ws mentioned oveF ehnillyD the ssignment is le to do something lled pttern mthing tht we will eventully get to in detilF por now though the only spet we will re out it tht we n put tuples on the left hnd side of the equls sign where we would normlly put just vrile nmeF pirstD let9s see wht hppens if we do vl delrtion with tuple on the right hnd sideF

scala> val t=(100,5.7) t: (Int, Double) = (100,5.7)


xote tht t refers to the tuple nd hs type @sntDhouleAF his is extly wht we would expetF he new power tht pttern mthing provides is tht if you put multiple nmes inside of prentheses on the left of the equlsD muh like tupleD ll the nmes will e oundF ht type of ehvior is shown hereF

scala> val (price,weight)=(100,5.7) price: Int = 100 weight: Double = 5.7


he sme n e done with vr nd then ll the nmes will e vriles tht n e ressignedF vet9s use the ility to nme vlues to do little prolem solvingF e re given totl time in seonds nd we wnt to know wht tht is in hoursD minutesD nd seondsF e then wnt to print tht out in resonle formt of hhXmmXssF he (rst step in solving this prolem is to (gure out how to go from just seonds to hoursD minutesD nd seondsF yne we hve thtD we n worry out formtting it to get the right stringF row do we get from seonds to hoursD minutesD nd seondsc pirstD how do you get from seonds to minutesc ht is firly esyD you simply divide y THF hnks to the ft tht integer division truntesD you will even get the proper numer of whole minutesF rere re two lines tht de(ne numer of totl seonds s well s numer of totl minutesF

CHAPTER 3.

SCALA BASICS

UH

scala> val totalSeconds=123456 totalSeconds: Int = 123456 scala> val totalMinutes=totalSeconds/60 totalMinutes: Int = 2057
ht numer of minutes isn9t extly the mount of time we wnt thoughF here re seonds left overF row do we (gure out how mny seonds we should displyc e ould do totleondsE@THBtotlwinutesAD ut simpler expression is used hereF

scala> val displaySeconds=totalSeconds%60 displaySeconds: Int = 36


he modulo gives us the reminder fter we hve gotten ll the full groups of THF ht is extly wht we wntF xow how do we get the numer of hours nd the numer of minutes to displyc he mth is the sme euse there re TH minutes in eh hourF

scala> val displayMinutes=totalMinutes%60 displayMinutes: Int = 17 scala> val displayHours=totalMinutes/60 displayHours: Int = 34
ht we see from this is tht IPQRST seonds is QR hoursD IU minutesD nd QT seondsF e ould repet this sme proess for di'erent numer of seonds if we used di'erent vlue for totleondsF xow tht we hve these vluesD we wnt to (gure out how to get them into string with the formt hhXmmXssF e (rst ttempt t tht might look like the followingF

scala> val finalString=displayHours+":"+displayMinutes+":"+ | displaySeconds finalString: java.lang.String = 34:17:36


por this prtiulr numer of seondsD this works just (neF roweverD if you ply round with this t llD you will (nd tht it hs signi(nt shortomingF sf the numer of minutes or seonds is less thn IHD only one digit is displyed when we wnt twoF o we need to ome up with wy to get leding zero on numers tht only hve one digitF o do thisD we will rek the prolem into two stepsF he (rst step will e to get the numer of minutes nd seonds s tringsF

scala> val min=displayMinutes.toString min: java.lang.String = 17 scala> val sec=displaySeconds.toString sec: java.lang.String = 36

CHAPTER 3.

SCALA BASICS

UI

his might seem oddD ut the string version hs something tht the numer itself doesn9tD n esy wy to tell how mny digitsGhrters re in itF hen there is only one digitD we wnt to dd n extr zeroF hen there isn9tD we don9tF qet n get this e'et y using the B method on the tring nd little mthF he short nmes were seleted to keep our expression shorter for formttingD ut tht isn9t requiredF

scala> val finalString=displayHours+":"+("0"*(2-min.length))+min+":"+( | "0"*(2-sec.length))+sec finalString: java.lang.String = 34:17:36


he result for these vlues is the smeD ut we ould fore some di'erent vlue into min nd se to see tht this does wht we wntF

scala> val min="5" min: java.lang.String = 5 scala> val sec="2" sec: java.lang.String = 2 scala> val finalString=displayHours+":"+("0"*(2-min.length))+min+":"+( | "0"*(2-sec.length))+sec finalString: java.lang.String = 34:05:02

3.8 Sequential Execution


orking in the iv is gret for ertin tsksD ut wht if you hve sequene of things you wnt to doD nd you wnt to do it multiple timesF rving to type in the sme set of instrutions repetedly isn9t very good optionF ht we just did is perfet exmple of thtF sf we wnt to do this for di'erent numer of seondsD we hve to repet ll the ommnds we just performedF sndeedD you n9t relly sy tht you hve progrmmed until you put in (xed set of instrutions for solving prolem tht you n esily run multiple timesF ht is wht progrm relly isF o now it is time to write our (rst progrmF e hve used the iv to enter ommnds one t timeF his is gret wy to test things out in l nd see wht few ommnds doF e seond wy of giving ommnds to l is to write little progrms s sriptsF he term sript is used to desrie smll progrms tht perform spei( tsksF here re lngugesD lled sripting lngugesD tht re reted spei(lly to mke the tsk of writing suh smll progrms esierF l isn9t tehnilly sripting lngugeD ut it n e used s suhF he syntx ws reted to mirror lot of the things tht re ommonly put into sripting lnguges nd if you run the sl ommnd nd give it the nme of (le tht ends in lD tht (le will e run s sript where the sttements in it re exeuted in order3 F e will use
3 We
will see later that the statements aren't always executed in order because there are Since we haven't gotten to statements that alter the ow of control through the program.

those yet though, execution is completely sequential at this point.

CHAPTER 3.

SCALA BASICS

UP

l s sripting lnguge until hpter IV when we move up to di'erent style tht helps us to orgnize lrger piees of odeF he sript for our time onversion looks like thisF

val totalSeconds=123456 val displaySeconds=totalSeconds%60 val totalMinutes=totalSeconds/60 val displayMinutes=totalMinutes%60 val displayHours=totalMinutes/60 val sec=displaySeconds.toString val min=displayMinutes.toString val finalString=displayHours+":"+("0"*(2-min.length))+min+ ":"+("0"*(2-sec.length))+sec println(finalString)
sf you put this into (le lled imeriptFsl nd then run sl imeE riptFslD you will get the output QRXIUXQT F he println sttement is required for the sript euse unlike the ivD the sript doesn9t print out vlues of ll sttementsF ou n run through this ode in the iv using the Xlod ommndF sf you do Xlod imeriptFsl you will see it print out ll of the intermedite vlues s well s the result of the printlnF his sript llows us to run the ommnds repetedly without retypingF fy editing the vlue of totleondsD we n test other totl times firly quiklyF roweverD the idel would e to llow user to tell us how mny seonds to use every time we run the sriptF e n esily get this ehvior y repling the top line of the sript we hd with these two linesF

print("Enter the number of seconds. ") val totalSeconds=readInt()


he (rst line does nothing more thn print prompt to let the user know tht we re witing for something to e inputF efter tht we hve ltered the initiliztion of totleonds so tht insted of giving it (xed numerD it is initilized to the vlue returned y redsntF his lls funtion tht reds in single integer from the userF sf you mke this hnge nd run the sriptD you will e le to enter ny numer of seondsD ssuming it is vlid sntD nd see it onverted to hoursD minutesD nd seondsF ou hve now een introdued to l nd progrmmingF his ide of giving spei( instrutions in the order tht we need them to hppen to solve prolem underpins everything we will do in this ookF roweverD this is only strtF here is lot more to explore nd we egin to open the door to these possiilities in the next hpterF

3.9 A Tip for Learning to Program


sn mny wysD lerning to progrmD whether in l or ny other progrmming lngugeD is very muh like lerning new nturl lngugeF he est wy to

CHAPTER 3.

SCALA BASICS

UQ

lern nturl lnguge is through immersionF ou need to prtie it nd e surrounded y itF he key is to not simply memorize the rules nd voulryD ut to put them into use nd lern them through regulr usgeF ou should strongly onsider pprohing progrmming in the sme wyF o wht does it men to immerse yourself in progrmming lngugec glerly you ren9t going to hve onverstions in it or enjoy television or rdio rodsts in itF he wy to immerse yourself in progrmming lnguge like l is to tke few minutes every dy to write it inF ou should onsider trying to spend ISEQH minutes eh dy writing odeF he iv in l is n exellent tool for you to enter in sttements to see wht they doF ry to ply round with the lngugeF snsted fo pprohing it s memorizing keywords nd rulesD try to put things into useF he things tht you use frequently will stik nd eome nturlF hose things tht you don9t use regulrly you will hve to look upD ut tht is normlF rogrmmersD even professionl progrmmers with mny yers of experiene in lngugeD still keep referenes hndyF yver timeD the numer of lines of ode tht you write in these short time intervls eh dy will grow s the sis eome seond nture nd you egin to prtie more dvned oneptsF fy the end of this ook you might (nd yourself writing hundred lines or so of funtionl ode on ertin dys during tht time spnF fy tht time you will hopefully lso pik up pet projetD something tht you re truly interested in progrmming nd tht you will think out the struture nd logi of muh more frquentlyF ispeilly erly onD you might (nd it hrd to think of nything tht you n writeF o help you with thisD mny of the hpters in this ook ontin elfE hireted tudy setionD like the one elowF se these s jumping o' point for the mteril in eh hpterF efter tht will ome set of exerises nd often set of lrger prolems lled projetsF ememer tht one of the signi(nt gols of lerning to progrm is improving your prolem solving skillsF hile the elfEhireted tudy setion will help you to fmilirize yourself with the detils presented in hpterD the exerises nd projets re tul prolems tht you re supposed to solve in forml wy using lF ou should use these to help provide you with the immersion you need to lern the lngugeF

Self-Directed Study
inter the following sttements into the iv nd see wht they doF ry some vritions to mke sure you understnd wht is going onF xot ll of these will e vlidF ou should try to (gure out whyF

scala> scala> scala> scala> scala> scala>

val a=5 val b=7+8 var c=b-a a=b+c c=c*c b=a/c

333 hi'erent things with numeri types

CHAPTER 3.

SCALA BASICS

UR

333 hrters nd strings 333 hrters s numeri types 333 ll some methods

Exercises
IF finry mth y hnd PF uples s vetors QF uples s omplex numers RF rite sript tht FFF

Chapter 4

Functions
irlier in the ook we mde the sttement tht progrmming ws ll out prolem solvingF st is silly the rt of giving omputer set of instrutions to solve prolem in terms tht the omputer n understndF yne of the key foundtionl elements of good prolem solving is prolem deompositionF he ide of prolem deomposition is tht good solutions of lrgeD omplex prolems re uilt out of solutions to smllerD more mngele prolemsF his is espeilly importnt in progrmming euse the prolems n e ritrrily omplex nd t the se we hve to rek them down to the level where we n ommunite them to the omputer whih is fundmentlly quite simplistiF yne of the key elements of prolem deomposition in progrmming is the functionF e funtion is olletion of sttements tht ommunite lrger ide nd tht we n llF he sripts we uilt t the end of lst hpter shred some hrteristis with funtionsF hey were olletions of sttements we put together to do something repetedly without retyping itF puntions give us tht nd muh moreF e9ll even put funtions in our sripts in this hpterF

4.1 Function Refresher


puntions re things tht you will e fmilir with from mny di'erent mth lssesD going k to lgerF he simplest exmple of funtion from mth might e something like f (x) = x2 F his sys tht f is funtion tht tkes numerD given the nme xD nd it hs the vlue of tht numer squredF xote tht in this expressionD the forml prmeterD xD hs no vlueF por funtion like this it ws understood tht x ws rel numerD ut tht doesn9t hve to e the seF gomplex numers work s wellF por other funtions you might wnt to limit yourself to integersF he vlue of x is spei(ed when we use the funtionF por exmpleD if we sy f@QA then Q is the rgument to the funtion nd x tkes on the vlue of Q when we (gure out the funtion9s vlueF yf ourseD when we do this we (nd tht f@QAaWF US

CHAPTER 4.

FUNCTIONS

UT

ht ws n exmple of funtion of one vrileF e n lso hve funE tions of two or more vrilesF por exmpleD you might hve g (x, y ) = x + y 2 F hen this funtion is lledD we provide two vlues s rguments nd they re used s the vlue of x nd yF o g@QDSAaQCPSaPVF he vlue of x is Q nd the vlue of y is SF ou know this euse the order of the rguments mthes the order of the prmetersF sn generl senseD funtion is mpping tht ssoites input vlues with output vluesF sn your mth lsses you hve likely foused on funtions tht mp from numers into numersF e hve seen tht our progrms n work with numersD ut there re other types tht we n work with s wellF

4.2 Making and Using Functions


here re numer of wys to mke funtions in lF e will egin with the stndrd de(nition formtF sn the lst hpter we sw tht we n use the keywords vl nd vr to delre vrilesF sn similr wyD we use the keyword def to de(ne funtionF e9ll strt with the simple mthemtil exmples tht were used in the previous setion nd rete l funtions tht mth them in the ivF

scala> def square(x:Double):Double = x*x square: (x: Double)Double


sn mthD funtions re given nmes like f nd gF his works (ne for limited ontextD ut it doesn9t sle up well if you re using lot of di'erent funtionsF e use the nme squre here euse it desries wht the funtion doesF he nme is written fter the def nd fter tht we hve set of prentheses tht ontin nme nd type seprted y olonF his is like vl delrtion exept tht it doesn9t inlude n initil vlueF he vlue is spei(ed when this funtion is lledD just like for the mth funtionF he ontents of the prentheses re the forml prmeters of the funtionF efter the prentheses is nother olon nd the type tht this funtion gives us k or returnsF sn l we refer to this s the result typeF sn this seD euse we re mirroring the mthemtil funtionD the type is houleF efter the result type is n equl sign nd the expression xBxF efter we enter thisD the iv tells us tht we hve reted something lled squre with the type @xX houleAhouleF his is l9s wy of telling us tht we hve funtion tht tkes houle nd results in houleF xow tht we hve de(ned squreDwe n use itF sn the lst setion we used our funtion f y doing f@QAF he syntx in l is the smeF

scala> square(3) res0: Double = 9.0


e give the nme of the funtion followed y prentheses with the vlue we wnt to use for xF hen we do this with the vlue QD l gives us k vlue

CHAPTER 4.

FUNCTIONS

UU

of WFH s houleF his prtiulr vlue ould lso e represented s n sntD ut the funtion sys it works with type houle nd so the snt tht we pssed in ws onverted to houle nd the result is lso houleF vet9s tke seond to look t the seond exmple mth funtionF sn this se we will use the short nme g nd mke it work with the snt type insted for demonstrtion purposesF

scala> def g(x:Int,y:Int):Int = x+y*y g: (x: Int,y: Int)Int


xote tht oth of the prmeters re put in the prentheses nd seprted y ommF sn generlD you n hve n ritrry numer of prmetersF hey n ll hve di'erent typesD nd they will e seprted y ommsF he funtion is lled in the wy one would expet y giving the funtion nme with vlues seprted y ommsF

scala> g(3,5) res1: Int = 28


sn this exmple we used simple literls for the rguments to the funtionD ut the rguments n e ny expression with the proper typeF por exmpleD we ould do the followingX

scala> val a=5 a: Int = 5 scala> g(a+2,square(3).toInt) res2: Int = 88


rere we show tht the rguments to g n inlude referene to vl or ll to the squre funtionF he ll to squre needs to e followed y onversion to n snt euse g is delred to tke type sntF sf you leve tht outD you will get n error like thisX

scala> g(a+2,square(3)) <console>:9: error: type mismatch; found : Double required: Int g(a+2,square(3)) ^
ith the vl nd vr delrtionsD we sw tht we ould typilly leve o' the types nd l would (gure them out for usF ith funtionsD the types on the prmeters re requiredF ou hve to tell l the type of the rguments tht you re pssing inF he result type is not required s it n often e inferredD ut it is onsidered etter style to speify it1 F he reson this is preferred is tht if you tell l type nd mke mistke in the funtion tht uses it
1 The
exception to this is recursive functions where the return type is required.

CHAPTER 4.

FUNCTIONS

UV

to result in di'erent typeD l n tell you erlier tht something hs gone wrongF hese funtions were limited in sopeF e n write longer funtionsF o do thisD we need to employ ode loksF en ritrry numer of sttements n e put inside of urly res nd it funtions s single sttementF qoing k to the inglish nlogyD lok of ode proly resemles prgrphF his is wek nlogy euse lok is not only omposed of sttementsD it is sttement itself nd n e n expressionF hen used s n expressionD the vlue you get from it is the vlue of the lst sttementGexpression in the lokF o see how this worksD we n ould tke the sttements tht we hd in our sript t the end of the lst hpter nd put them in funtionF he funtion might look something like this if we type it into the ivF

scala> def secondsToTimeString(totalSeconds:Int):String = { | val displaySeconds=totalSeconds%60 | val totalMinutes=totalSeconds/60 | val displayMinutes=totalMinutes%60 | val displayHours=totalMinutes/60 | val sec=displaySeconds.toString | val min=displayMinutes.toString | displayHours+":"+("0"*(2-min.length))+min+":"+("0"*(2-sec.length))+sec | } secondsToTimeString: (totalSeconds: Int)String
his funtion tkes single snt of the numer of seondsF st results in tringF efter the equl sign is n open urly re tht opens lok of odeF his lok is losed t the end of the funtion fter n expression tht gives us the tring we wnt to returnF he dvntge of this pproh is we n esily ll the funtion using difE ferent numers of seondsD even in the ivF

scala> secondsToTimeString(123456) res0: String = 34:17:36 scala> secondsToTimeString(654321) res1: String = 181:45:21
sn this wyD funtions llow us to orgnize ode nd give useful nmes to things tht we might wnt to do frequentlyF his ode lso does something else tht we hve never seen eforeD it delres vriles inside of funtionF hen we do this the vriles re lled lol vriles nd they n only e essed inside of the funtionF sfD fter typing in this funtionD you try to use seD or ny of the other lol vrilesD outside the funtionD you will get n error messgeF

scala> sec <console>:6: error: not found: value sec

CHAPTER 4.

FUNCTIONS

UW

sec ^
he prt of the ode over whih nme n e essed is lled the sope of tht nmeF hen you delre vrile or funtion in sript outside ny lok of odeD it hs sope tht goes through the rest of the sriptF sf you delre it in lok of odeD it hs sope tht goes from the point of the delrtion to the end of the lok it is delred inF e lok is denoted with urly resD so you n use the nme until you get to the right urly re tht loses o' the pir the nme is delred inF es generl ruleD you wnt to minimize the sope of vriles so they n only e essed where they re neededF hese exmples utilize the mthemtil onept of funtion s something tht tkes input vlues nd mps them to outputs vluesF sn progrmming it is possile for funtions to do things other thn give k vlueF e hve lredy seen n exmple of suh funtionF yur (rst progrm lled printlnF ou might notie tht if you use println in the ivD vlue is printedD ut there isn9t result returnedF his is euse println gives us k vlue of type nit s ws disussed in the lst hpterF hen you write funtion tht results in nitD you n use the norml syntx nd put Xnit fter the prmeter listF en lternteD shorter syntx is to leve out the equls signD nd just hve lok of odeF he following is simple exmple of thisF

scala> def printMultiple(s:String,howMany:Int) { | println(s*howMany) | } printMultiple: (s: String,howMany: Int)Unit scala> printMultiple("hi ",3) hi hi hi
e9ll see more useful exmples lterF fefore moving onD we will do nother exmple of funtion tht is more interestingD like lulting n verge in ourseF he ourse verge is luE lted y omining the verge of numer of di'erent grdesF por exmpleD you might hve testsD ssignmentsD nd quizzesF ih of these might ontriute di'erent frtion of the totl grdeF he tests might e worth RH7D ssignE ments worth RH7D nd quizzes worth PH7F ou will lso hve di'erent numer of eh of these grdesF por exmpleD you might hve P testsD Q ssignmentsD nd R quizzesF sn mny oursesD prt of the ourse verge is omputed y dropping lowest grde nd tking the verge of wht reminsF sn this seD let9s ssume tht the lowest quiz grde is droppedF ht we wnt to do is write funtion tht tkes ll the grdesD nd returns the verge for the ourseF o strt withD it might look something like the followingX

def courseAverage(test1:Double,test2:Double,assn1:Double,

CHAPTER 4.

FUNCTIONS

VH

...

assn2:Double,assn3:Double,quiz1:Double,quiz2:Double, quiz3:Double,quiz4:Double):Double = {

his funtion tkes in W doules nd gives k n verge for the full lssF e wnt to lulte the verges for eh of the di'erent prts of the grde seprtelyD then omine them with the proper perentgesF pilling in it more gives the followingF

def courseAverage(test1:Double,test2:Double,assn1:Double, assn2:Double,assn3:Double,quiz1:Double,quiz2:Double, quiz3:Double,quiz4:Double):Double = { val testAve=(test1+test2)/2 val assnAve=(assn1+assn2+assn3)/3 val minQuiz=... val quizAve=(quiz1+quiz2+quiz3+quiz4-minQuiz)/3 testAve*0.4+assnAve*0.4+quizAve*0.2 }
ell tht is left to do is to (gure out the minimum quiz grdeF o omplish thisD we will use method lled min tht is de(ned on the snt typeF sf you hve two snt vluesD nd D then the expression min will give you the smller of the two vluesF his is ll to the min method on snt nd ould e written s Fmin@AF roweverD the opertor syntx where the dot nd prentheses re left o' is superior when we hve multiple vlues euse we n put the vlues in row to get the smllest of ll of themF his gives us omplete version of the funtion whih looks like the followingF

def courseAverage(test1:Double,test2:Double,assn1:Double, assn2:Double,assn3:Double,quiz1:Double,quiz2:Double, quiz3:Double,quiz4:Double):Double = { val testAve=(test1+test2)/2 val assnAve=(assn1+assn2+assn3)/3 val minQuiz=quiz1 min quiz2 min quiz3 min quiz4 val quizAve=(quiz1+quiz2+quiz3+quiz4-minQuiz)/3 testAve*0.4+assnAve*0.4+quizAve*0.2 }
sf you put this into the ivD you n ll it nd get output s shown hereF

scala> courseAverage(90,80,95,76,84,50,70,36,89) res4: Double = 81.93333333333334

CHAPTER 4.

FUNCTIONS

VI

4.3 Problem Decomposition


es we hve sidD progrmming is out prolem solvingF yne of the mjor spets of prolem solving isD we often wnt to rek prolems into smller piees to solve themF here re numer of resons to do thisF he most ovious reson is tht ig prolems re hrd to solveF sf you n rek ig prolem into smller pieesD it is often esier to solve the piees nd then uild n nswer to the full prolem from the nswers to the pieesF his n e repeted on eh suEprolem until you get to level where the prolems re simple to solveF e seond dvntge to reking prolems up is tht the solutions to the piees might e useful in themselvesF his llows you to potentilly reuse piees of odeF he ility to reuse existing ode is ritil in progrmmingF here re mny di'erent wys tht you n rek up prolemF e good wy to tell if one is etter thn nother is if one gives you funtions tht you re more likely to e le to reuseF e third dvntge to deomposing prolem is tht the resulting ode n e esier to understnd nd modifyF sf you give the funtions good nmesD then people n esily red nd understnd top level funtions nd hve etter ide of wht is going on in the low level funtionsF sn dditionD if you deide t some point tht you need to modify how something is doneD it is esier to (nd where the hnge needs to e mde nd to mke it if the prolem hs een roken down in logil wyF e looked t two di'erent prolems nd sw how they ould e progrmmed s set of instrutions tht we n put inside of funtionF he question now is how ould we rek these things upc sf you go k to the originl disussionsD the desriptions of how to solve the prolems ws done piee y piee in wy tht worked well for reking them prtF vet9s egin with the grding progrmF here re four si prts to this prolemF e (nd the verge of the testsD the ssignmentsD nd the quizzesF yne we hve thoseD we omine them using the proper perentgesF ih ould e roken out into seprte funtionF sf we write this into (le it might look like the followingF

def testAve(test1:Double,test2:Double):Double=(test1+test2)/2 def assnAve(assn1:Double,assn2:Double,assn3:Double):Double = (assn1+assn2+assn3)/3 def quizAve(quiz1:Double,quiz2:Double,quiz3:Double,quiz4:Double):Double = { val minQuiz=quiz1 min quiz2 min quiz3 min quiz4 (quiz1+quiz2+quiz3+quiz4-minQuiz)/3 } def fullAve(test:Double,assn:Double,quiz:Double):Double = test*0.4+assn*0.4+quiz*0.2 def courseAverage(test1:Double,test2:Double,assn1:Double, assn2:Double,assn3:Double,quiz1:Double,quiz2:Double,

CHAPTER 4.

FUNCTIONS

VP

quiz3:Double,quiz4:Double):Double = { val test=testAve(test1,test2) val assn=assnAve(assn1,assn2,assn3) val quiz=quizAve(quiz1,quiz2,quiz3,quiz4) fullAve(test,assn,quiz)

yne you hve this in (le you n either use this s prt of sript or use the Xlod ommnd in the iv to lod it in nd ll the funtions diretlyF xote tht this version requires lot more typing thn wht we hd eforeF ht won9t lwys e the seD ut it is for this exmple nd mny smll exmples where we n9t reuse funtionsF iven though this version requires more typingD it hs the dvntges of eing esier to understnd nd lter euse the funtionlity is roken out into pieesF his exmple is one where we ould potentilly hve some reuse if we just knew it more lF foth testeve nd ssneve do nothing more thn tke the verge of numersF feuse they tke the verge of di'erent numers of numersD we don9t yet know how to write single funtion to hndle oth sesF e will (x tht in hpter UF yur other exmple ws for onverting numer of seonds into properly formtted timeF hen we originlly disussed thisD we roke it into two proE lemsF pirstD we hd to (gure out how mny seondsD minutesD nd hours given numer of seonds wsF efter tht we hd to formt the string properlyF e will mintin tht seprtion of work with funtionsF sf we write this in (leD it might look like the followingF

def calcHMS(totalSeconds:Int):(Int,Int,Int) = { val displaySeconds=totalSeconds%60 val totalMinutes=totalSeconds/60 val displayMinutes=totalMinutes%60 val displayHours=totalMinutes/60 (displayHours,displayMinutes,displaySeconds) } def formatHMS(numHours:Int,numMinutes:Int,numSeconds:Int):String = { val sec=numSeconds.toString val min=numMinutes.toString numHours+":"+("0"*(2-min.length))+min+":"+ ("0"*(2-sec.length))+sec } def secondsToTimeString(totalSeconds:Int):String = { val (h,m,s)=calcHMS(totalSeconds) formatHMS(h,m,s) }
his ode does something tht we hven9t seen funtion do yetF he lrw funtion returns tupleF his funtion needs to give us k three vlues for the hoursD minutesD nd seondsF his type of proess is ommon in progrmmingF row do you get funtions to return multiple vluesc hi'erent lnguges hve

CHAPTER 4.

FUNCTIONS

VQ

di'erent solutions to this prolemF sn lD the most diret solution is to hve the funtion return tuple s we see hereF his pproh of tking igger prolem nd reking it down into piees is often lled topEdown pprohF he mentl imge is tht you hve the full prolem t the top nd in eh level elow it you hve smller piees tht re omined to mke solution to the level ove themF his struture stops t the ottom when you get to something tht n e solved reltively esilyF sn ontrst to topEdownD it is lso possile to pproh prolems from the ottomE upF his pproh works when you hve ertin fmilirity with solving prtiulr type of prolem nd you know wht types of piees you will need or when your top level prolem isn9t ompletely well de(ned nd you hve to try some di'erent pprohesF his n hppen when you re uilding softwre for ustomer s the ustomer my hve only vgue ide of wht they wnt their progrm to look likeF sn tht situtionD you n uild piees you know will e useful nd try putting them together in di'erent wys until you (nd something tht the ustomer is hppy withF he prolems tht we worked on here hd solutions suh tht the deomE posed solution required more text thn the originlD monolithi solutionF e hve expressed tht this isn9t suh d thing s the deomposed solutions hve ertin dvntgesF here is nother ftor tht you should keep in mind when deomposing prolemsF he disussion of topEdown pproh requires tht you keep reking the prolem down until you get to something tht is firly simple to solveF his isn9t just prtil for the prolem solvingD it turns out tht there re good resons to keep funtions shortF vong funtions re muh more likely to inlude errors thn smll funtions reF por this resonD it is generE lly dvised tht progrmmers keep their funtions reltively shortF row short n e mtter of style nd personl prefereneD ut there is good rule you n follow tht is ked up y reserhF he rule is tht funtions should e kept short enough tht they (t ompletely on your sreen t one timeF hen funtion gets long enough tht it doesn9t ll (t on the sreenD the progrmmer egins hving to rely upon hisGher memory of wht is in the prts tht re o' the sreenF rumn memory is not gret thing to rely uponD nd s resultD the rte of errors goes up signi(ntly when there re prts of the funtion tht you n9t see on the sreenF

4.4 Function Literals


vst hpter we sw tht the simplest form of expressions for sntD houleD tringD nd some other types ws the literl formF por exmpleD just the numer S is literl of type sntF viterls llow you to hve n expression of type tht you n write in short formt without delring nme for itF lD euse it inludes elements of funtionl progrmmingD llows you to express funtions s literls tooF he syntx for funtion literl strts with set of prentheses tht hve omm seprted list of rguments in them followed y n rrow mde from

CHAPTER 4.

FUNCTIONS

VR

n equls sign nd greter thn sign with the ody of the funtion fter thtF o if we go k to our (rst two funtions we might write them in this wyF

scala> (x:Double)=>x*x res9: (Double) => Double = <function1> scala> (x:Int,y:Int)=>x+y*y res10: (Int, Int) => Int = <function2>
sn this type of usgeD the type of the rguments is requiredF es we will see thoughD there re mny usges where it isn9t requiredF sf the funtion were longerD one ould use urly res to hold multiple sttementsF sn theory one n use funtion literls for funtions of ny lengthD in prtie this is style issue nd you won9t wnt to use funtion literls tht re too longF he funtion literls will e emedded in other funtions nd you don9t wnt those funtions to exeed sreen size in length so the literls shouldn9t e more thn few lines t mostF l hs n even shorter form for some speil se funtion literlsF his form uses undersores to represent prmeters nd skips the prmeter list nd rrow ompletelyF st n only e used when eh prmeter is used only oneD in the right orderD nd l n infer the types of the prmetersF sn this formD the funtion literl @xXsntDyXsntAabxCy ould e represented simply s @CAF xote tht this n9t e used for xP written s xBx euse we use the x twieF st hs signi(nt limittionsD ut we will see tht there re situtions where it is useful nd onvenient to use nd we will mke use of it in lter hptersF

4.5 Non-Functional Functions


he title of this setion might seem oddF row ould funtion not e funE tionlc sn purely funtionl progrmmingD funtion tkes inputs nd lultes vlueF he vlue it returns depends only on the rguments nd the funtion doesn9t do nything ut give k tht vlueF yften in progrmming funtions will do other things s well or might return di'erent vlues for the sme inputsF hese types of funtions ren9t tehnilly funtionlF hen they do other things we refer to tht s side e'etsF his terminology is like tht for mediE tionsF ou tke medition euse it hs ertin desired e'etF roweverD it might hve ertin other side e'etsF hile the side e'ets of medition typilly ren9t desiredD there re times when side e'ets of funtions re deE siredF he simplest exmple of this is printingF he print sttement doesn9t return nythingF snsted it sends informtion to outputF ht is side e'etF st is possile to hve funtions tht return vlue nd hve side e'etsF roweverD quite frequently you will (nd tht funtions with side e'ets don9t return ny dtF o l tht mens their return type is nitF rere is simple exmple of suh funtionF

scala> def introduce(name:String):Unit = { | println("Hi, my name is "+name+".")

CHAPTER 4.

FUNCTIONS

VS

| } introduce: (name: String)Unit scala> introduce("Mark") Hi, my name is Mark.


his is ommon in nonEfuntionl progrmmingF sndeedD some lnguges inlude speil onstrutD the proedureD for thisF l doesn9t hve seprte type of funtionD ut it does llow for shorter syntxF hen you write funtion tht return nitD you n leve o' the return type nd the equls signF ht mkes our erlier funtion look like this instedX

scala> def introduce(name:String) { | println("Hi, my name is "+name+".") | } introduce: (name: String)Unit


his shortut syntx is hndy nd you will likely (nd tht you use it quite oftenF sndeedD it looks more like the funtion syntx in mny other lngugesF roweverD it does introdue type of syntx error tht you should e wre of euse it n led to odd error messges nd e hrd to loteF he syntx error is to leve o' n equls sign from funtion delrtion tht should hve oneF his omission n led to one of two prolemsF sf you follow the reommendtion nd put return type on funtions tht do return vluesD l will e onfused y the lk of n equls sign nd give you n error messgeF sn some ses the error messge will sy tht you might e missing n equls signF roweverD in mny ses it will notF sf you don9t follow the style reommendtion nd llow l to (gure out return typesD then leving out the equls sign will give your funtion return type of nit euse no return type nd no equls sign is extly the shorthnd syntxF his prolem won9t e identi(ed t the funtion delrtion t llF st will only pop up when you try to ll the funtion nd do something with the returned vlueF

4.6 Higher Order Functions


puntion literls would e nothing more thn novelty in l or ny other progrmming lnguge if it weren9t for higher order funtionsF e higher order funtion is funtion tht opertes on other funtionsF his mens tht either we pss other funtions into itD or it returns funtion k to usF hese re funtionl progrmming onept nd they n e hllenging to get ones hed roundD ut we will see in two hpters how they n e usefulF es n exmple of higher order funtion hereD we will use the ide of omE positionF sf we hve two funtionsD f@xA nd g@xAD then the omposition of f with g is f@g@xAAF e n write l funtion tht does this like followsF

scala> def compose(f:Double=>Double,g:Double=>Double):Double=>Double =

CHAPTER 4.

FUNCTIONS

VT

| (x)=>f(g(x)) compose: (f: (Double) => Double,g: (Double) => Double)(Double) => Double
xote tht we write the funtion types themselves using rrowsF e ould ll this with either funtions we uild using def or funtion literlsF e will do it with the following two funtions tht hve een de(ned using defF

scala> def plus5(x:Double):Double = x+5 plus5: (x: Double)Double scala> def square(x:Double):Double = x*x square: (x: Double)Double
xow we wnt to use ompose to uild new funtions from these two using the ompose funtion nd then see our new funtions workingF

scala> val h=compose(plus5,square) h: (Double) => Double = <function1> scala> val j=compose(square,plus5) j: (Double) => Double = <function1> scala> h(3) res0: Double = 14.0 scala> j(3) res1: Double = 64.0
he funtion h@xAaxPCS while j@xAa@xCSAPF ou n see tht when we ll these with n rgument of QD we get vlues of IR nd TR respetivelyD just s would e expetedF yne limittion of our ompose funtionD s written hereD is tht it only works with norml mth style funtions tht tke doules nd return doulesF e will lern lter how we n mke this more generl so these funtions n return other typesF he only rel restrition on the types for omposite should e tht the output type of g mthes the input type of fF

4.7 Named and Default Arguments (Advanced)


e few options were dded to l in version PFV in regrds to funtion rguments nd lling funtionsF xormllyD l (gures out whih of the rguments pssed into funtion is whih y their orderF gonsider this funtionF

def evalQuadratic(a:Double,b:Double,c:Double,x:Double):Double = { val x2=x*x a*x2+b*x+c }


sf you lod this into the iv you n exeute it s followsF

CHAPTER 4.

FUNCTIONS

VU

scala> evalQuadratic(2,3,4,5) res0: Double = 69.0


sn this llD aPD aQD aRD nd xaSF his is euse tht is they order the rguments pper in oth the de(nition of the funtion nd the ll to itF por funtions where there re signi(nt numer of rguments tht re ll of the sme typeD this n led to onfusionF o get round thisD l hs nmed rgumentsF hen you ll the funtion you n speify the nmes you wnt the vlues ssoited withF o the ll ove would e like the followingX

scala> evalQuadratic(a=2,b=3,c=4,x=5) res2: Double = 69.0


sn this ll it is now expliit wht vlues re going to wht prmetersF yne dvntge of this is when you enter the rguments in di'erent orderD the mening will e wht you wntF por exmpleD you might think tht x ws the (rst rgument insted of the lstF ithout nmes rgumentsD this would led to n error with no error messgeF ou would simply get the wrong nswerF roweverD if you use nmed rguments everything is (ne euse the nmes superede the orderF

scala> evalQuadratic(x=5,a=2,b=3,c=4) res3: Double = 69.0


rere we see tht even though x is (rstD the vlue we get is orretF ou n use nmed prmeters without nming ll the prmetersF ou n strt the list with rguments tht re sed on position nd then use nmes for the lter onesF ell the rguments fter the (rst nmed one hve to e nmed nd they n9t duplite ny tht you gve using the positionF por some funtions there re some rguments tht will hve prtiulr vlue lot of the timeF sn tht situtionD it is nie to mke it so tht people lling the funtion don9t hve to provide them nd they will use defult vlueF hen you delre the funtion simply follow the type with n equls sign nd the vlue you wnt to hve for the defultF sf the ller is hppy with the defult vlueD then tht rgument n e left outF hefult rguments t the end of the list n e simply omittedF sf they re in the middle then you will hve to use nmed rguments to speify ny rguments fter them in the listF gonsider funtion to dd grde to studentF

def addGrade(name:String,grade:Int = 0):Int = ...


rere the defult grde is zeroF o this funtion n e lled in two wysF

addGrade(Jane,95) addGrade(Joe)
he (rst ll is like everything we hve seen to this pointF he seond one leves o' the grdeF es resultD toe gets H for whtever grde this wsF

CHAPTER 4.

FUNCTIONS

VV

Self-Directed Study
inter the following sttements into the iv nd see wht they doF ome will produe errorsF ou should (gure out whyF ry some vritions to mke sure you understnd wht is going onF

scala> def succ(n:Int):Int = n+1 scala> succ(1) scala> succ(succ(1)) scala> var cnt = 0 scala> def inc { cnt=cnt+1 } scala> cnt scala> inc scala> cnt scala> inc scala> inc scala> cnt scala> val f = (x:Double,y:Double)=>math.sqrt(x*x+y*y) scala> f(3,4) scala> def doThreeTimes(g:(Double)=>Double,x:Double) = g(g(g(x))) scala> doThreeTimes(y=>y+1,1) scala> doThreeTimes(y=>y*2,1) scala> doThreeTimes(a=>a-5,100) scala> def incChar(c:Char,offset:Int) = (c+offset).toChar scala> incChar('a',1) scala> incChar('a',2) scala> incChar('z',-3) scala> def tnp1(n:Int):(Int,Int) = { val odd = n%2 (n/2*(1-odd),(3*n-1)*odd) } scala> odd scala> var name =  scala> def introduction { println(What is your name?) name = readLine() println(Hello +name) } scala> name

Exercises
IF rite set of funtions to do the following opertions on PEtuples of snt s if they were the numertor nd denomintor of rtionl numersF @A eddition @A utrtion

CHAPTER 4.

FUNCTIONS

VW

@A wultiplition @dA hivision @eA edue to lowest terms PF rite set of funtions to do the following opertions on QEtuples of houles s if they were vetorsF @A @A @A @dA eddition utrtion hot produt gross produt

QF rite set of funtions to do the following opertions on PEtuples of houles s if they were omplex numersF @A @A @A @dA @eA eddition utrtion wultiplition hivision wgnitude

RF se your solution to exerise Q to mke funtion tht tkes two omplex numersD z nd c nd returns the vlue z 2 + cF SF rite funtion to solve the qudrti eqution for rel vluesF our solution should return @houleD houleA of the two rootsF TF inhne the solution to exerise S so tht it returns @@houleD houE leAD@houleD houleAAF his is PEtuple of PEtuplesF his represents the two roots nd eh root n e omplex numer expressed s @houleD houleAF UF sn this option you will write little sript tht does prt of IHRHE i @httpXGGwwwFirsFgovGpuGirsEpdfGfIHRHezFpdfAF e hven9t overed enough for you to do the whole thingD ut you n write enough to sk questions nd do most of the lultions for lines IEIQF ho wht you n nd use this s lerning exeriseF ou should rek setions up into funtionsF VF he hyperoli trigonometri funtionD sinhD oshD nd tnhD re ll de(ned in terms of power of eD the se of the nturl logrithmsF rere re si de(nitions of ehX 1 x sinh(x) = 2 (e ex ) 1 x cosh(x) = 2 (e + ex ) sinh(x) tanh(x) = cosh( x) rite funtions for eh of theseF ou n use mthFexp@xA to represent ex F

CHAPTER 4.

FUNCTIONS

WH

WF rite two funtions for onverting etween grtesin nd polr oordinte systemsF he (rst tkes xXhoule nd yXhoule nd returns @houleD houleA with r nd thetF he seond tkes rXhoule nd thetXhoule nd returns @houleD houleA with x nd yF ou n use the mthFtnP@yXhouleD xXhouleA funtion to get n ngleF his voids the prolem of using diE vision when x is zeroF IHF his option hs you doing sienti( lultionF e n9t do tht muh yetD ut we will work our wy upF e re going to ply with lulting the nonEgreenhouse tempertures for plnets with moderte to fst spin rtesF his might seem like omplex thing to doD ut it isn9t di0ultF ou need two piees of informtion nd little lgerF he (rst piee of informtion is the tefnEfoltzmnn vw for the mount of energy given o' in therml rdition y ny odyF he seond is the ft tht intensity of rdition drops o' s 1/r2 F o lulte the nonEgreenhouse temperture of plnet you need the following piees of informtionF ou should prompt the user for vlues to theseF o keep things simple use mks units nd keep tempertures in uelvinF E E E E dius of the strF urfe temperture of the strF yritl semimjor xis of the plnetF eledo of the plnetF

se the tefnEfoltzmnn lw @j = T 4 A to determine the energy outE put per squre meter on the strs surfeF wke tht into funtion tht tkes the needed vluesF sing the inverse squre reltionship you n lulte the intensity t the lotion of the plnet @use the rtio of the plnet9s orit distne to the stellr rdius for thisAF wke this nother funtionF he un light will over the plnet with n re of r2 where r is the plnets rdiusF e frtion of thtD determined y the ledoD is reE )etedF ht isn9t re)eted wrms the plnetF he plnet ools through 2 its own therml rdition from surfe of 4 3 r F etting the sored nd emitted vlues equl llows you to solve the tempertureF wke funtion tht tkes the inident power nd ledo nd gives you k tempertureF

Chapter 5

Conditionals
e hve een solving some si prolems so frD ut the tehniques tht we hve ess to re fundmentlly limited t this pointF he rel prolem is tht whether we hve sript or funtionD ll the lines exeute in the sme order every timeF sn most rel prolems we need to e le to do wht is lled onditionl exeution where something hppens only in ertin situtionsF sn this hpter we will lern some of the methods for doing onditionl exeution in l nd see how we n use them to solve more omplex prolemsF sn order to do this properlyD we need to develop formlized wy to express logi nd put it into our progrmsF his systemD lled foolen logiD will llow us to stte the onditions under whih vrious prts of our progrm will or will not hppenF

5.1 Motivating Example


ou hve een sked to write progrm tht will lulte hrges for people visiting lol musement prkF here re di'erent hrges for dults vsF hildrenD whether they re ringing in oolerD nd whether they wnt to lso get into the wter prkF e wnt to write funtion tht will tell us how muh the person pysF e will pss the needed informtion into this funtion suh s n snt for the persons geD foolen for whether they hve oolerD nd nother foolen for whether they wnt to get into the wter prkF his is something tht we ouldn9t do lst hpter euse we didn9t hve wy of performing logiF e ouldn9t sy tht we wnted to do something only in prtiulr situtionF his ility to do di'erent things in di'erent situtions is lled onditionl exeution nd it is very importnt onept in progrmming nd prolem solving in generlF st gives you the ility to express logi nd to solve muh more omplex prolems thn you ould do without itF

WI

CHAPTER 5.

CONDITIONALS

WP

5.2 The if Expression


irtully ll progrmming lnguges hve onstrut in them lled ifF he ide of this onstrut is tht you hve ondition where one thing should hppen if ondition is trueF sf tht ondition is flseD then either nothing or something di'erent will hppenF sn nonEfuntionl lngugesD the if onstrut is sttementF st hs no vlue nd simply determines wht ode will e exeutedF sn l nd other funtionl lngugesD the if is n expression tht gives k vlue though it n e used in n impertive style s wellF vet9s strt with n exmple then we n roden it to the more generl syntxF ke the tiket prie exmple nd onsider just the persons geF y tht we wnt to onsider person hild if they re under IQ nd tht hildren py 6PH while dults py 6QSF e ould mke vrile with the orret vlue with the following delrtion using n if expressionF

val cost = if(age<13) 20 else 35


his ssumes tht ge is n snt vrile tht is in sope t this pointF he new prt of this is the use of the if expression whih heks the ge nd gives k one of two vlues depending on itF his exmple uses the if s n expressionF o we re out the vlue it gives usF sn this type of usgeD we lwys need to inlude n else euse there hs to e vlue tht is used if the expression is flseF his sme type of ehvior n e omplished using vr nd using the if s sttementF

var cost=20 if(age>=13) cost=35


his ode retes vr nd gives it the initil vlue of PHF st then heks if the ge is greter thn or equl to IQ nd if soD it hnges the vlue to QSF xote tht with this usgeD the else luse isn9t requiredF rere we only wnt to do something if the ondition is trueF sn l you should generlly prefer the (rst pprohF st is shorter nd lenerD nd leves you with vl whih you n e ertin won9t e hnged fter it is retedF he (rst pproh is funtionl pproh while the seond is n impertive pprohF sn generlD the formt of the if is s followsX

if(condition ) expr1 [else expr2 ]


he squre rkets here denote tht the else nd the seond expression re optionlF hey re not prt of the syntxF he ondition n e repled y ny expression of type foolenD while exprI nd exprP n e ny expression you wntF sn the sitution where the expression is omplexD you n use urly res to rete lok of odeF e sw this syntx in the lst hpter with funtionsF ou n put ny ode inside of urly resF his lok is itself n expression nd the vlue of the expression is the vlue of the lst sttement in the urly resF

CHAPTER 5.

CONDITIONALS

WQ

ht out the other prts of our dmission prk entrne ostc e lso wnted to hek if the person hd ooler or if they wnted to get into the wter prkF hese should oth e vriles of type foolenF e might ll them ooler nd wterrkF vet us sy it osts n dditionl 6S to ring in ooler nd 6IH to go to the wter prkF sf we used the if s n expression we n type in the followingX

val cost = (if(age<13) 20 else 35) + (if(cooler) 5 else 0) + (if(waterPark) 10 else 0)


rere we re dding together the results of three di'erent if expressionsF his formt is somewht spei( to funtionl lngugesF st would e more ommon in most lnguges to see this instedX

var cost=20 if(age>=13) cost=35 if(cooler) cost=cost+5 if(waterPark) cost=cost+10


sn this seond formD we use if s sttement insted of n expression nd hve the ody of the if hnge or mutte the vlue of the vrile ostF sn the seond nd third if sttementsD the nme ost is repetedF his type of repetition is often voided in progrmming nd mny lngugesD inluding lD inlude opertions tht llow us to prevent itF hen the duplition is used like this with n ssignment nd vrile ppering on oth sides of the equls signD it is possile to use n revited syntx where the opertor is pled in front of the equls sign like thisX

var cost=20 if(age>=13) cost=35 if(cooler) cost+=5 if(waterPark) cost+=10

5.3 Comparisons
he (rst is sttement shown in the previous setion uses ba to do omprison etween two vluesF ou likely hd no prolem (guring out tht this n e red s greter thn or equl toF our keyord doesn9t hve key so insted we use two hrters in rowF ell of the norml omprisons tht you re used to exist in lD ut someD like the greter thn or equl toD di'er from how you re used to writing themF he simplest omprison you n do is to hek if two things re the sme or di'erentF ou red this s sying tht two things re equl or not equl to one notherF sn l we represent these with aa nd 3a respetivelyF xote tht the hek for equlity uses two equl signsF e single equl sign in l

CHAPTER 5.

CONDITIONALS

WR

stnds for ssignment whih we hve lredy seen stores vlue into vrileF he doule equl sign heks if two expressions hve the sme vlue nd gives us foolen vlue with the result of the omprisonF rere re few exmple of the use of this in the ivF

scala> 2==3 res1: Boolean = false scala> 7==7 res2: Boolean = true scala> 'a'=='a' res3: Boolean = true scala> "hi"=="there" res4: Boolean = false scala> "mom".length=="dad".length res5: Boolean = true
he 3a opertor is silly the opposite of aaF st tells us if two things re di'erent nd should e red s not equlF es we will seeD it is ustomry in l to red the exlmtion pointD often red s ngD s notF eny of the exmples ove ould use 3a insted of aa nd the result would hve een the opposite of wht is shownF sn ddition to equlity nd inequlityD there re lso omprisons of mgE nitude like the gebaIQ tht we used oveF he omprisons of mgnitude in l re done with `D bD `aD nd baF hese lso give us k vlue of the foolen type so it will e either true or flseF he order of `a nd ba is signi(ntF hey re in the sme order tht you sy themD less thn or equl to nd greter thn or equl toD so it won9t e hrd to rememerF sf you reverse the orderD l will not e le to (gure out wht you men nd will return n errorF

scala> 5=<9 <console>:6: error: value =< is not a member of Int 5=<9 ^
ou n use aa or 3a on ny of the di'erent types in lD oth those we hve tlked out nd everything tht we hven9t yet tlked outF his isn9t the se for the mgnitude omprisons thoughF hile you n use ` for ny of the types tht we hve seen so frD not every type hs n order where less thn omprison mkes senseF e will hve types for things like olorsD shpesD nd fruitsF wgnitude omprisons won9t mke sense with these nd they won9t work if you try to use themF

5.4 Equality vs. Identity (Advanced)


sf you hve experiene with tvD you might (nd the ehvior of aa onfusingF his is euse in lD aa does wht people expetD it heks for equlity

CHAPTER 5.

CONDITIONALS

WS

etween vluesF por nyone who hsn9t progrmmed in tv heGshe might wonder wht other options there reF e will see lter tht ojets with the sme vlue ren9t neessrily the sme ojetsF sf you go to store nd pik up two oxes of the sme type of itemD they re silly equl s fr s you n tellD ut they ren9t the sme ojetF ih one hs its own identityF here re times in progrmming when you don9t wnt to just hek if two things re equlD you wnt to tully know if they re the sme thingF his requires doing hek for identityF sn l we use eq to hek if two things re the sme thingF e n show n exmple of where eq nd aa return di'erent resultF

scala> "sssss" eq "s"*5 res8: Boolean = false scala> "sssss" == "s"*5 res9: Boolean = true

5.5 Boolean Logic


smgine if the theme prk hd poliy where seniors re hrged the sme mount s hildrenF o now nyone over TS or nyone under IQ should py the redued rteF e ould omplish this y hving seprte if sttements in either the funtionl or the impertive mnnerF

val cost = if(age<13) 20 else if(age>65) 20 else 35


or

var cost=20 if(age>=13) cost=35 if(age>65) cost=20


foth of these re veroseD potentilly ine0ientD nd prone to errorsF he errors our euse in oth we hd to enter the numer PH in two plesF ht we would relly like to sy is extly wht we sid in inglishF e wnt to sy tht we use the lower rte if the person is under IQ or over TS nd use the higher rte otherwiseF foolen logi gives us the ility to sy thisF here re four di'erent Boolean operators we n use to uild omplex foolen expressions from simple onesF hese re shown in the tle elowF hesription sge wening nd 88 rue if oth nd re trueF or || rue if or is trueF ellows oth eing trueF exlusive or @xorA rue if either or is trueD ut not othF not 3 rue if is flse nd flse if is trueF e n use the || opertor just like we used or in our inglish desription of wht we wnted oveF sf we do thisD our two wys of expressing ost n e simpli(ed to theseF

CHAPTER 5.

CONDITIONALS

WT

val cost = if(age<13 || age>65) 20 else 35


or we n use 88 to sy nd

var cost=20 if(age>=13 && age<=65) cost=35


he (rst one reprodues the inglish desription nd uses n or to give single foolen expression for when the lower rte is hrgedF he seond one is the onverse nd uses n nd to determine when the higher rte should e hrgedF he seond expression ould e written insted with n || nd 3 to mke it more expliit tht it is the onverse of the (rst oneF

var cost=20 if(!(age<13 || age>65)) cost=35


he extr set of prentheses is required here so tht the not is done for the whole expression insted of the prt efore the ||F enother exmple would e funtion tht tells us if two squres intersetF he inputs to this funtion would e the top left orner of eh of the squres s x nd y oordintes long with the length edges of the two squresF he funtion should return foolen telling us whether or not the squres intersetF fefore we n write funtion to do thisD we need to (gure out how we would do this independent of progrmF our (rst inlintion might e to sy tht given two squres it is ovious whether or not they intersetF sndeedD novie progrmmers re tempted to give tht type of desription to mny prolemsF his isn9t euse the solution relly is oviousD it is euse novie progrmmers hven9t developed their skills t nlyzing wht they do when they solve prolemF his is something tht you will develop over time nd it is requirement for ny rel progrmmerF o wht re you missing when you sy tht prolem like this is oviousc qiven set of six numers s will e the input to this funtionD most people would not (nd the solution oviousF o mke it ovious they would drw the squres nd look t themF his use of your visul proessing is silly heting nd impliitly rings into ply lrge mount of proessing tht your rin does utomtillyF por this resonD we will void ny type of solution where you would e tempted to sy you would look t somethingF iven if we did tke the pproh of drwing the squresD tht isn9t s strightforwrd s you might pitureF hen you piture drwing squresD you my piture squres of nerly the sme size tht re in esy to drw oordintesF lotting gets lot hrder if one of the squres is millions of times lrger thn the otherF sf your progrm is trying to see if n nt hs entered uildingD tht isn9t t ll out of the questionF o we n9t settle for just look t it or it is oviousF ht mens we hve to (gure out wht it relly mens for two squres to e interseting just using the numersF hile looking t it isn9t llowed s solutionD it n e helpful to (gure out wht we relly menF hrw numer of di'erent squres on pperF vel them

CHAPTER 5.

CONDITIONALS

WU

with the numers I nd PF ht re di'erent possile reltive positions for the squresc ht re ses when they don9t intersetc ht hs to hppen for them to intersetc hese ren9t rhetoril questionsF qo through this exerise nd ome up with something efore you red onF he ility to rek down prolem tht is ovious into the rel steps tht humns go through on suonsious level is ornerstone of progrmmingF st is useful for those who don9t intend to e progrmmers s it n help you to understnd your thinking on ll mnner of topisF hen you went through the proessing of drwing the squresD one of the things you might hve found ws tht squres n overlp in either x or yD ut they only interset if they overlp in oth x nd yF ht gives us something to work withF yur nswer ould sy something likeD overlp 88 overlpF ell we hve to do now is (gure out wht it mens to overlp in given diretionF iven this hs lots of di'erent possiilitiesD ut if you ply with them you9ll see tht ny sitution where there is n overlp stis(es the followingF he minimum of the (rst rnge hs to e less thn the mximum of the seond rnge nd the mximum of the (rst rnge hs to e greter thn the minimum of the seond rngeF qo k to your drwings nd verify tht this is trueF et this point we hve the ility to sy wht we wntF here re mny wys tht we ould do soF e re going to pik n pproh whih reks the prolem down into smller pieesF his will e esier for people to redF st will hve hne of eing reusle euse the funtion tht we rek out might e useful in other situtionsF e sid ove tht the squres overlp if their rnges overlp in oth x nd yF o we n write funtion tht heks to see if two rnges overlp in one dimensionF e n then ll this twie to see if the squres overlpF

def overlapRange(min1:Double,size1:Double,min2:Double, size2:Double):Boolean = min1<min2+size2 && min1+size1>min2 def overlapSquares(x1:Double,y1:Double,size1:Double, x2:Double,y2:Double,size2:Double):Boolean = overlapRange(x1,size1,x2,size2) && overlapRange(y1,size1,y2,size2)
xote tht euse oth of these funtions return foolenD there is no need for n if expressionF e put in the foolen expressions tht will give us the nswers we wntF yne other signi(nt ftor out the foolen 88 nd || opertors is tht they re short iruit opertorsF his mens tht if the vlue they will give is known fter the (rst rgument is evlutedD the seond rgument won9t e evlutedF por 88 this hppens if the (rst rgument is flse euse no mtter wht the seond rgument isD the (nl vlue will e flseF imilrlyD if the (rst rgument of || is trueD the (nl vlue will e true so there is no point spending time to evlute the seond rgumentF his will e signi(nt to us lter on when we get to expressions tht n use errorsF he only thing we ould do now tht would use n error is to divide y zeroF e n use tht to demonstrte how short iruiting n prevent n error nd tht the opertor is not short iruitedF

CHAPTER 5.

CONDITIONALS

WV

scala> val n=0 n: Int = 0 scala> 4/n java.lang.ArithmeticException: / by zero at .<init>(<console>:7) at .<clinit>(<console>) at RequestResult$.<init>(<console>:9) at RequestResult$.<clinit>(<console>) at RequestResult$scala_repl_result(<console>) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun... scala> n!=0 && 4/n==6 res3: Boolean = false scala> n==0 || 4/n==6 res4: Boolean = true scala> n==0 ^ 4/n==6 java.lang.ArithmeticException: / by zero at .<init>(<console>:7) at .<clinit>(<console>) at RequestResult$.<init>(<console>:9) at RequestResult$.<clinit>(<console>) at RequestResult$scala_repl_result(<console>) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun...

5.6 Bigger Expressions


o fr ll of our expressions hve een firly smllF yther ftors n ome into ply when they get lrgeF yne ftor tht eomes signi(nt is preedeneF his is the order in whih opertions re doneF ou know from mth tht mulE tiplition hppens efore ddition nd l follows tht ruleF ht hppens when we strt inluding these dditionl opertions for ompring vlues nd foolen opertorsc hese ren9t things you hve een tught in mth lssD ut for the most prt they re understndleF ell of the opertors introdued in this setion hppen fter ll the mthemtil opertors we worked with eE foreF his mkes sense s otherwise we ouldn9t types something like CS`BP without using prenthesesF imilrlyD omprisons hve higher preedene thn the foolen opertorsF he overlpnge funtion used oth of these fts s it omined dditionD omprisonD nd 88F es ws mentioned erlierD opertors re relly just methods in lF he ones we hve tlked out so fr re simply methods tht re de(ned in the l lirries on the pproprite typesF o 88 nd || re de(ned on the foolen typeF he omprison opertors re de(ned on numeri typesD etF hen you use opertor nottion with methodD the preedene is determined y the (rst hrter in the opertorF his tle shows the orderF

CHAPTER 5.

CONDITIONALS

WW

pirst ghrter @other speil hrtersA BG7 CE X a3 `b 8 | @ll lettersA @ll ssignment opertorsA le SFIX le of opertor preedene in lF stem hrink ide win gomo 6HFWW 6IFPW 6IFWW 6RFHW w 6IFPW 6IFRW 6PFSW 6RFWW v 6IFQW 6IFSW 6PFWW 6SFTW le SFPX pood item ostsF here is nother interesting point tht we hve used impliitly lredyD ut is worth noting expliitlyF his is tht if expressions n e nested inside of one notherF e sw this when we (rst tried to dd senior itizens t lower ostF

val cost = if(age<13) 20 else if(age>65) 20 else 35


he ontents of the else on the (rst if is itself n ifF his is generl property of most progrmming lngugesF he if in l needs some form of expression inside of it for the true nd flse possiilitiesF he if itself mkes perfetly vlid expression to nestF o you n nest ifs inside of one nother s muh s it mkes sense for the prolem you re solvingF o mke this more expliitD let9s go k to our theme prk nd this time onsider onessionsF he menu isn9t rod nd is stndrd for fst foodF hey hve drinksD friesD nd vrious min ourse items like hmurgers nd hot dogsF ou n lso get omo whih hs one of ehF por ny of these you n speify sizeF he ost is spei(ed y the simple mtrix shown hereF e need to onvert this tle into funtionF por the funtion we will pss in two stringsF he (rst is the item type nd the seond is the sizeD oth s tringsF he funtion should return how muh tht osts s houleF

def foodPrice(item:String,size:String):Double = { if(item=="Drink") { if(size=="S") 0.99

CHAPTER 5.

CONDITIONALS

IHH

else if(size=="M") 1.29 else 1.39 } else if(item=="Side") { if(size=="S") 1.29 else if(size=="M") 1.49 else 1.59 } else if(item=="Main") { if(size=="S") 1.99 else if(size=="M") 2.59 else 2.99 } else { if(size=="S") 4.09 else if(size=="M") 4.99 else 5.69 }

his method hs top level set of ifs tht pik the item typeF snside of eh is n if sttement tht piks from the di'erent sizesF he wy this ws writtenD it will defult to gomo if the item isn9t reognized nd to lrge if the size isn9t reognizedF here re etter wys to del with thisD ut this will work for nowF his method demonstrtes stndrd formtting style used withe this type of struture where the only thing in the else is nother if hekF snsted of putting nother set of urly res fter the else nd indenting everythingD leve o' the urly res nd just put the if thereF his prevents the indenttion from getting too deepF

5.7 Matching
he if expression isn9t the only onditionl onstrut in lF here is seondD fr more expressiveD onditionl onstrutD mthF hile the if onstrut piks etween two di'erent possiilitiesD sed on whether n expression is true or flseD the mth onstrut llows you to pik from lrge numer of options to see if prtiulr expression mthes ny of themF he term mthes here is vgueF sndeedD the power of the mth onstrut omes from something lled pattern matching whih we will go into detil out lterF por now we will strt with the simple usge where mth mens tht two things re equlF he syntx of the mth expression in its simplest form is s followsX

expr match { case pattern1 => expr1 case pattern2 => expr2 case pattern3 => expr3 ... }

CHAPTER 5.

CONDITIONALS

IHI

he vlue of the expression efore the mth keyword is heked ginst eh of the di'erent ptterns tht follow the se keywords in orderF he (rst pttern tht mthes will hve its expression evluted nd tht will e the vlue of the whole mth expressionF e use this to repet our exmple from ove with the ost of foodF

def foodPriceMatch(item:String,size:String):Double = item match { case "Drink" => size match { case "S" => 0.99 case "M" => 1.29 case _ => 1.39 } case "Side" => size match { case "S" => 1.29 case "M" => 1.49 case _ => 1.59 } case "Main" => size match { case "S" => 1.99 case "M" => 2.59 case _ => 2.99 } case _ => size match { case "S" => 4.09 case "M" => 4.29 case _ => 5.69 } }
hen n entire funtion is single mthD it is ustomry to put the strt of the mth fter the equls sign s done hereF snside we hve the four di'erent sesD eh with its own mth on the sizeF he one thing tht might seem odd is the use of the undersoreF en undersore s pttern mthes nythingF his is done so tht the ehvior would gree with wht we hd in the if version where it defulted to gomo s the item nd lrge s the sizeF his exmple shows tht the mth expressions n e nested nd the n e used to mth nythingF here is lot more to the mth expression thoughF he following exmple shows how to use mth to give responses to whether you might uy di'erent food itemsF

def buy(food:(String,Double)):Boolean = food match { case ("Steak",cost) if(cost<10) => true case ("Steak",_) => false case (_,cost) => cost<1 }
his is very limited exmpleD ut it demonstrtes severl spets of mth tht re worth notingF pirstD food is tuple nd the ses pull the two items

CHAPTER 5.

CONDITIONALS

IHP

out of tht tupleF ht is prt of the pttern spet of the mthF e will use this lter on when we hve other things with ptternsF he seond thing we see is tht if we put vrile nme in the ptternD it will mth with nything nd it will get the vlue of tht thingF sn the exmpleD the seond element of the tuple is given the nme ost in two di'erent plesF ht vrile ould pper in the expression for the se s in the lst se where we will uy nything for under dollrF sf n lso e prt of n if tht gurds the seF he pttern in the (rst se will mth nything tht hs the word tek s the foodF roweverD the if mens we will only use tht se if the ost is less thn IHF ytherwise it flls down nd heks lter sesF hile this is simple little exmpleD it hopefully demonstrtes the signi(nt power we n get from mth expressionF sf you re fmilir with other progrmming lnguges you might hve herd of swith sttement eforeF yn the surfeD mth might seem like swithD ut mth is fr more powerful nd )exile in wys llowing you to use it more thn swithF

5.8 Bit-wise Arithmetic


he its in inry numer re just like foolen vluesF e n perform foolen logi on the its in integer vlues the wy we would on stndrd true nd flse vluesF o do this we use slightly di'erent opertorsF e use 8 nd | insted of 88 nd ||F he versions with single hrter ren9t short iruitF he onept of short iruit doesn9t mke sense for this type of opertion euse it n9t e omplex opertion to evluteF he other di'erene is tht we use ~ insted of 3 for the itEwise negtionF sf you think k to hpter Q you will rememer tht every numer on omputer is represented in inryF e store vlues of one or zero to represent di'erent powers of twoF hen we do it wise opertions we simply tke the its in the sme position nd do the spei(ed opertions on them to get the its in the resultF o see how this works let9s run through set of exmples on the inry opertors where we use the four it numers IIHH nd IHIHF

1100 & 1010 -----1000 1100 | 1010 -----1110 1100 ^ 1010 -----0110

CHAPTER 5.

CONDITIONALS

IHQ

xegtion is pretty strightforwrdF ~IHHIaHIIHF yf ourseD these it omiE ntions ll hve numeri deiml vluesF e n put ommnds into l to do these sme thingsF yur (rst vlue is IP nd our seond is IHF he vlue we took the negtion of is WF rere re the opertions performed in lF ghek tht they mth the nswers we gotF

scala> 12 res3: Int scala> 12 res4: Int scala> 12 res5: Int scala> ~9 res6: Int

& = | = ^ =

10 8 10 14 10 6

= -10

he lst one is interestingF hen you hek if it mkes senseD rememer tht negtive vlues re represented using PsEomplimentF hile on the topi of it wise opertions there re two others tht re worth mentioningF hey re leftEshift nd rightEshift nd re written in l s `#` nd b#bF hese opertors shift the its in numer the spei(ed numer of positionsF sf you think out the mening of itsD this is like multiplying or dividing y powers of twoF st is like dding zeros to the end of deiml numer is the sme s multiplying y tenF ome simple exmples show you how we n use this to get powers of twoF

scala> 1 << 0 res7: Int = 1 scala> 1 << 1 res8: Int = 2 scala> 1 << 2 res9: Int = 4 scala> 1 << 3 res10: Int = 8
here is seond version of rightEshift written s b#b#bF he norml version doesn9t move the sign it so tht signs re preservedF he seond version doesn9t do this nd will shift the sign it down long with everything elseF ou might wonder why you would wnt to do these thingsF sing single integer vlue s olletion of foolen vlues is ommon in lirries sed on the g lnguge nd frequently pper in operting system odeF here is nother usge tht ould ome into ply in projets lter in this ookF sf you hve djusted disply settings on omputer you hve proly seen tht olors n e represented t VEitD ITEitD PREitD or QPEit vluesF qiven the undne of memory on modern omputersD most of the time people will use QPEit olorF rve you ever wondered wht tht mensc sf you hve ever written we pge or looked t we pge you hve seen olor represented s six hexdeiml digitsF he (rst two digits speify how muh redD the next

CHAPTER 5.

CONDITIONALS

IHR

two speify how muh greenD nd the lst two speify how muh lueF his is lled qf for ovious resons nd is extly wht PREit olor gives youF QPEit olor uses n extr VEits euse omputers n operte more quikly with memory in QPEit hunks euse they re typilly wired to del with QPEit integerF he dditionl VEits stores the lph hnnel whih n e used for trnsprenyF st doesn9t mtter muh for your sreenD ut it is something tht n e used to nie e'et in PEh grphis whih we will disuss in hpter PSF he QPEit olor is often lled eqf euse it hs lphD redD greenD nd lue vlues ll pked into QP itsF ih gets V its or yteF his is where itEwise opertions ome into plyF ou might e given four di'erent vlues for lphD redD greenD nd lue for olor nd need to pk them together into single QPEit integerF elterntelyD you might e given single eqf vlue s QPEit integer nd hve to (gure out the individul omponentsF sndeedD oth of these pper s exerises elowF

Self-Directed Study
inter the following sttements into the iv nd see wht they doF ry some vritions to mke sure you understnd wht is going onF xote tht some lines red vlues so the iv will puse until you enter those vluesF he outome of other lines will depend on wht you enterF

scala> val a = readInt() scala> val b = readInt() scala> val minimum = if(a<b) a else b scala> if(minimum != (a min b)) { println(Oops, something went wrong.) } else { println(That's good.) } scala> true && true scala> true && false scala> false && true scala> false && false scala> true || true scala> true || false scala> false || true scala> false || false scala> !true scala> !false scala> true ^ true scala> true ^ false scala> false ^ true scala> false ^ false scala> a < b || { println(a>=b); a >= b }

CHAPTER 5.

CONDITIONALS

IHS

scala> a < b && { println(a>=b); a >= b } scala> a match { case 7 => That is a lucky number. case 13 => That is an unlucky number. case _ => I'm not certain about that number. } scala> 13 & 5 scala> a.toBinaryString scala> a & 0xff scala> (a & 0xff).toBinaryString scala> a ^ 0xff scala> (a ^ 0xff).toBinaryString scala> (a << 3).toBinaryString scala> ((a >> 8) && 0xff).toBinaryString

Exercises
IF rite foolen expressions for the followingX @A essume you hve vrile lled geF ell if the person is old enough to leglly drinkF @A qiven height in inhesD tell if person n ride n musement prk ride tht requires riders to e etween RV nd URF PF hetermine if the following expressions re true or flseF essume the folE lowingD aID aPD aQD datrueD eaflseF @A aaI @A ` || b @A `a 88 daae @dA ICPaa @eA d @fA 3e @gA d || e @hA T!@!Aaa 88 @e||dA @iA b 88 b @jA C3a || @BEaa 88 !bA QF hetermine if the following expressions re true or flseF essume the folE lowingD aID aIHD aIHHD xatrueD yaflseF @A x @A x 88 y

CHAPTER 5.

CONDITIONALS

IHT

@A aaEW @dA ` || b @eA 3y 88 3x @fA @GAGaaG @gA @CCaaBCGA || y @hA `a 88 `a 88 ba @iA G@GAaaG @jA 3@x || yA RF writing expressions with if 333 SF write some mth expressions 333 TF st is ustomry to express olors on omputer s omintion of redD greenD nd lue long with nother vlue lled lph tht indites trnsE prenyF e single snt hs QP its or R ytesF he four di'erent olor vlues re often pked into single snt s n eqf vlueF he highest yte is the lph nd elow tht you hve redD greenD nd lue in orderF ih yte n store vlues etween H nd PSSF por lphD H is ompletely trnsE prent nd PSS is ompletely opqueF rite funtion tht tkes four snt rguments for lphD redD greenD nd lue nd returns n snt with the omined eqf vlueF sf one of the numers pssed in is outside the H to PSS rngeD use H or PSSD whihever it is loser toF xote tht itwise opertions re pproprite for this exerE iseF ou might (nd hexdeiml representtion of numers to e useful s wellF UF epet the previous exeriseD ut this time the rguments into the funtion should e houles etween HFH nd IFH tht you onvert to snts in the proper rngeF VF rite funtion tht does the opposite of wht you did for exerise TF st should tke n snt with n eqf vlue nd return @sntD sntD sntD sntA with the omponent vlues etween H nd PSSF WF rite funtion tht does the opposite of wht you did for exerise UF st should tke n snt with n eqf vlue nd return @houleD houleD houleD houleA with the omponent vlues etween HFH nd IFHF

Projects
IF rite funtion to tkes the oe0ients of qudrti eqution @D D nd in x2 CxCAF he funtion should print the roots for those oe0ientsF st need to hndle di'erent options for the roots nd prints one or two solutions with rel or omplex vlues s ppropriteF

CHAPTER 5.

CONDITIONALS

IHU

PF rite funtion tht tells you whether or not retngle overlps with irleF ou pss the funtion the required informtion for the two shpes tht inludes positions nd sizes nd it returns foolenF se this funE tion to see if retngulr footprint of house n e pled on lot tht hs three trees pproximted y irlesF vet the user input the lotion of the house nd the three treesF QF ou hve uilt simple root tht is supposed to move from wherever it is pled to )gF he root n move in one of two wysF st n roll ny distne t speed of one inh per seondF st n jump nd eh jump tkes one seond nd moves predetermined mountF hen it jumps it lwys jumps tht mountD not frtion of itF rite funtion tht tkes the distne you strt from the )g nd the distne overed in eh jump nd returns how mny seonds it will tke to get to the )g using n optiml pprohF @he trik with this prolem is to mke sure you onsider ll the possiilitiesFA RF his prolem strts trk of options tht you n work on tht uild up to hving funtioning ry trer t the end of the semester tht n render imges in QEhF por this (rst step s wnt you to write two funtionsF he (rst tells if nd where ry hits sphere nd the seond tells if nd where ry hits plneF e ry n e de(ned s strt point nd diretion vetor using the prmetri eqution r(t) = r0 + t rD for t 0F ou (nd intersetions y solving for the t tht stis(es ertin onditions like oming ertin distne from point @for sphereA or stisfying the eqution r(t) n = d @for plne with norml n tht is d units from the originAF his options is it more oneptully hllengingD ut if you do ll the ry tring options the results n e impressiveF he imge on the over of the ook ws mde using ry trer the uthor wrote in lF

Chapter 6

Recursion for Iteration


qining onditionls provided us with lot of powerF e re now le to express logi in our odeF here is still something very signi(nt tht we re missingF xow when we write piee of logiD it hppens oneF e n put tht logi into funtion nd then ll the funtion over nd overD ut it will only hppen s mny times s we ll itF e n9t esily vry the numer of times tht something hppensF here is more thn one wy to mke something hppen multiple times in lF yne of these wysD recursionD we n do with the onstruts tht we hve lredy lernedF

6.1 Basics of Recursion


eursion is onept tht omes from mthemtisF e mthemtil funtion is reursive if it is de(ned in terms of itselfF o see how this worksD we9ll egin with ftorilF ou might rell from mth lsses tht n3 ss the produt of ll the integers from I up to nF e might write this s n3aIBPBFFFBnF wore formlly we ould write it in the following wyX
n

n! =

i
i=1

F foth of these de(ne ftoril just in terms of multiplition nd ssume tht we know how to mke tht multiplition hppen repetedlyF e n e more expliit out the repetition if we write the de(nition using reursion like thisX

n! =

1 n (n 1)!

n<2 otherwise

F sn this de(nitionD the ftoril funtion is de(ned in terms of itselfF o desrie wht ftoril isD we use ftorilF o see how this worksD let9s run through n exmple nd tke the ftoril of SF fy our de(nition we get tht S3aSBR3F his is euse S is not less thn PF IHV

CHAPTER 6.

RECURSION FOR ITERATION

IHW

usequentlyD we n see tht R3aRBQ3 so S3aSBRBQ3F his leds to S3aSBRBQBP3 nd (nlly to S3aSBRBQBPBIF his de(nition nd its pplition illustrte two of the key spets of reurE sionF here re two possiilities for the vlue of this funtionF hih one we use depends on the vlue of nF sn the se where n is less thn PD the vlue of the ftoril is IF his is lled base caseF ell reursive funtions need some kind of se seF he ritil thing out se se is tht it isn9t reursiveF hen you get to se seD it should hve vlue tht n e lulted diretly without referene k to the funtionF ithout this you get wht is lled infinite recursionF here n e multiple di'erent se ses s wellF here is no restrition tht there e only oneD ut there must e t lest oneF o see why the se se is requiredD onsider wht would hppen without itF e would still get S3aSBRBQBP3D ut wht would hppen fter thtc ellD without se seD P3aPBI3F ehnilly there isn9t prolem thereD ut wht out I3c ellD I3aIBH3 in the sene of se se nd H3aHB@EIA3F his proess ontinues on foreverF ht is why it is lled in(nite reursionF he seond se demonstrtes the reursive seF xot only does this se refer k to the funtion itselfD it does so with di'erent vlue nd tht vlue should e moving us towrd se seF sn this seD we de(ne n3 sn terms of @nEIA3F sf the reursive se were to use the sme vlue of n we would gin hve in(nite reursionF imilrlyD if it used vlue greter thn n we would lso hve in(nite reursion euse our se se is for smll numersD not lrge numersF ht else ould we de(ne reursivelyc ellD we ould de(ne multiplitionD whih is used y ftorilD reursivelyF efter llD t lest for the positive inteE gersD isn9t multiplition nothing more thn repeted dditionc vike with the ftorilD we ould write de(nition of multiplition etween positive integers tht uses mth symol tht ssumes some type of repetition like thisX
n

mn=
i=1

F his sys tht mBn is m dded to itself n timesF his n e written s reursive funtion in the following wyX

mn=

0 m + m (n 1)

n=0 otherwise

F his funtion hs two ses gin with se se for smll vlue nd seondD reursive seD tht is de(ned in terms of the vlue we re reursing on using smller vlue of tht rgumentF e ould do the sme type of things to de(ne exponentition in terms of multiplitionF e ould lso use n inrement @dding IA to de(ne ddition y higher numersF st is worth tking look t wht tht would look likeF

m+n=

m 1 + m + (n 1)

n=0 otherwise

CHAPTER 6.

RECURSION FOR ITERATION

IIH

hile this seems it surdD it would e less so if we nmed our funtionsF gonsider this lternte wy of writing thisF

add(m, n) =

m 1 + add(m, n 1)

n=0 otherwise

xow it is ler tht s long s we n do inrement @CIA nd derement @EIA we ould write full dditionF ith full ddition we ould write multiplitionF ith multiplition we n write exponentition or ftorilF st turns out tht this isn9t ll you n doF st might e hrd to elieveD ut if you hve vrilesD reursion @whih simply requires funtions nd n if onstrutAD inrementD nd derementD you hve full model of omputtionF st n lulte nything tht you wntF yf ourseD we don9t do it tht wy euse it would e extremely slowF tillD from theoretil stndpoint it is very interesting to know tht so muh n e done with so littleF

6.2 Writing Recursion


e hve seen the mthemtil side of reursion nd hve written some si mthemtil funtions s reursive funtionsF xow we need to see how we write these things nd more in progrmF e wnt to look t mking reursive progrmming funtionsF he trnsltion from mth funtions to progrmming funtions isn9t hrdF sn ftD little will hnge from the mth nottion to the l nottionF es eforeD we9ll egin with the ftoril funtionF rere is the ftoril funE tion written in l in the ivF

scala> def fact(n:Int):Int = if(n<2) 1 else n*fact(n-1) fact: (n: Int)Int


e hve lled the funtion ftD short for ftorilF he ody of the funtion is single if expressionF pirst it heks the vlue of n to see if it is less thn PF sf it isD the expression hs vlue of IF ytherwise it is nBft@nEIAF e n see the results of using this funtion hereX

scala> fact(5) res1: Int = 120


e see here tht it orretly lultes the ftoril of SF yne signi(nt di'erene etween reursive nd nonEreursive funtions in l is tht we hve to speify the return type of reursive funtionsF sf you don9tD l will quikly let you knowF

scala> def fact(n:Int) = if(n<2) 1 else n*fact(n-1) <console>:6: error: recursive method fact needs result type def fact(n:Int) = if(n<2) 1 else n*fact(n-1) ^

CHAPTER 6.

RECURSION FOR ITERATION

III

ptoril is n interesting funtion tht is signi(nt in gomputer iene when we tlk out how muh work ertin progrms hve to doF ome progrms hve to do n mount of work tht sles with the ftoril of the numer of things they re working onF e n use our ftoril funtion to see wht tht would menF vet9s tke the ftoril of few di'erent vluesF

scala> fact(10) res2: Int = 3628800 scala> fact(15) res3: Int = 2004310016 scala> fact(20) res4: Int = -2102132736
he (rst two show you tht the ftoril funtion grows very quiklyF sndeedD progrms tht do ftoril work re referred to s intrtle euse you n9t use them for even modest size prolemsF he third exmple though shows something else interestingF he vlue of PH3 should e quite lrgeF st ertinly shouldn9t e negtiveF ht is going on herec sf you rememer k to hpter QD we tlked out the wy tht numers re represented on omputersF sntegers on omputers re represented y (nite numer of itsF es resultD they n only get so lrgeF he uilt in numer representtions in l use QP its for sntF sf we hnged our funtion just it to use vong we ould get TR itsF vet9s see tht in tionF

scala> def fact(n:Long):Long = if(n<2) 1L else n*fact(n-1) fact: (n: Long)Long scala> fact(20) res5: Long = 2432902008176640000 scala> fact(30) res6: Long = -8764578968847253504
he TR its in vong re enough to store PH3D ut they still fll short of QH3F sf we give up the speed of using the numers types hrd wired into the omputerD we n represent muh lrger numersF e n e limited y the mount of memory in the omputerF ht is vlue not mesured in itsD ut in illions of ytesF o do thisD we use the type figsntF he figsnt type provides us with ritrry preision rithmetiF st does this t the ost of speed nd memoryF ou don9t wnt to use figsnt unless you relly need itF roweverD it n e fun to ply with using funtion like ftoril whih hs the possiility of getting quite lrgeF vet9s rede(ne our funtion using this type nd see how it worksF

scala> def fact(n:BigInt):BigInt = if(n<2) 1L else n*fact(n-1) fact: (n: BigInt)BigInt scala> fact(30)

CHAPTER 6.

RECURSION FOR ITERATION

IIP

res7: BigInt = 265252859812191058636308480000000 scala> fact(150) res8: BigInt = 571338395644585459047893286526105400318955357860112641 825483758331798291248453983931265744886753111453771078787468542041626 662501986845044663559491959220665749425920957357789293253572904449624 724054167907221184454371222696755200000000000000000000000000000000000 00
xot only n this version tke the ftoril of QHD it n go to muh lrger vlues s you see hereF here ren9t tht mny pplitions tht need these types of numersD ut they n ertinly e fun to ply withF xow tht we hve eten ftoril to deth it is proly time to move on to di'erent exmpleF he lst setion ws ll out exmples pulled from mthemtisF he title of this hpter though is using reursion for itertionF his is fr roder progrmming onept thn the mthemtil funtions we hve tlked outF o let9s tke n exmple tht is very spei( to progrmmingF e simple exmple to strt with is to write funtion tht will ount down from ertin numer to zeroF fy ount here we just men it will print out the vluesF vike the ftoril we will pss in single numerD the numer we wnt to ount down fromF e lso hve to hve se seD the point where we stop ountingF ine we re ounting down to zeroD if the vlue is ever elow zero then we re done nd shouldn9t print nythingF sn the reursive se we will hve vlueD nD tht is greter thn or equl to zeroF e de(nitely wnt to print nF he question isD wht do we do fter thtc ellD if we re ounting downD then following n we wnt to hve the ount down tht egins with nEIF sndeedD this is how you should imgine the reursion workingF gounting down from n is done y ounting the nD then ounting down from nEIF gonverting this into ode looks like the followingX

def countDown(n:Int) { if(n>=0) { println(n) countDown(n-1) } }


he wy this ode is writtenD the se se does nothing so we hve n if sttement tht will use the funtion to simply return if the vlue of n is less thn HF ou n ll this funtion pssing in di'erent vlues for n to verify tht it worksF xow let9s try something slightly di'erentF ht if s wnt to ount from one vlue to notherc sn some wysD this funtion looks very muh like wht we lredy wroteF here re some di'erenes thoughF sn the lst funtion we were lwys ounting down to zero so the only informtion we needed to know ws wht we were ounting fromF sn this se thoughD we need to e told oth wht we re ounting from nd wht we re ounting toF ht mens tht our

CHAPTER 6.

RECURSION FOR ITERATION

IIQ

funtion needs two prmeters pssed inF e (rst ut t this might look like the followingX

def countFromTo(from:Int,to:Int) { println(from) if(from!=to) { countFromTo(from+1,to) } }


his funtion will work (ne under the ssumption tht we re ounting upF roweverD if you ll this with the intention of ounting down so tht from is igger thn toD you hve prolemF o see whyD let9s tre through this funtionF pirstD let9s see wht hppens if we ll it with P nd SD so we re trying to ount up from P to SF ht we re doing is referred to s tring the odeF st is the t of running through ode to see wht it doesF his is n essentil ility for ny progrmmerF efter llD how n you write ode to omplete given tsk if you ren9t le to understnd wht the ode you write will doc here re lots of di'erent pprohes to tringF wny involve tles where you write down the vlues of di'erent vrilesF por reursive funtions you n often just write down eh ll nd wht it doesD then show the lls it mkesF ht is wht we will do hereF e will leve out the method nme nd just put the vlues of the rguments s tht is wht hngesF

(2,5) (3,5) (4,5) (5,5)

=> prints 2 => prints 3 => prints 4 => prints 5

he lst ll does not ll itself euse the ondition from3ato is flseF xow onsider if we lled this funtion with the rguments reversedF st seems resonle to sk the funtion to ount from S to PF st just hs to ount downF o see wht it will do though we n tre itF

(5,2) (6,2) (7,2) (8,2) ...

=> prints 5 => prints 6 => prints 7 => prints 8

CHAPTER 6.

RECURSION FOR ITERATION

IIR

his funtion will ount for very long timeF st isn9t tehnilly in(nite reurE sion euse the snt type only hs (nite numer of vluesF yne it ounts ove 231 1 it wrps k round to 231 nd ount up from there to P where it will stopF ou hve to e ptient to see this ehvior thoughF iven if it isn9t in(niteD this isn9t the ehvior we wntF e would rther the funtion ount down from S to PF he question isD how n we do thisc o nswer this we should go k to the tre nd (gure out why it wsn9t doing tht in the (rst pleF vooking t the ode nd the tre you should quikly see tht the prolem is due to the ft tht the reursive ll is pssed vlue of fromCIF o the next ll is lwys using vlue one lrger thn the previous oneF ht we need is to use CI when we re ounting up nd EI when we re ounting downF his ehvior n e esily dded y repling the I with n if expressionF yur modi(ed funtion looks like thisX

def countFromTo(from:Int,to:Int) { println(from) if(from!=to) { countFromTo(from+(if(from<to) 1 else -1),to) } }


xow when the from vlue is less thn the to vlue we dd IF ytherwise we will dd EIF ine we don9t get to tht point if the two re equlD we don9t hve to worry out tht situtionF ou should enter this funtion in nd test it to mke sure tht it does wht we wntF

6.3 User input


e re still limited in wht we n relistilly do euse we re stuk using vlues tht we n esily lulteF por exmpleD we n go from one numer to the one efore it or the one fterF e ould use those vlues s inputs to more omplex funtionsD ut we still need them to e lulted from numers we n niely iterte throughF hese re shortomings tht will e (xed in the next hpterF por nowD we n look t how to mke the user @or more generlly stndrd inputA into soure of more interesting vluesF e sw k in hpter Q tht we n ll the funtion redsnt to red n integer from stndrd inputF xow we wnt to red multiple vlues nd do something with themF e will strt y tking the sum of spei( numer of vluesF e n write funtion lled sumsnputsntsF e will pss this funtion n integer tht represents how mny integers we wnt the user to input nd it will return the sum of those vluesF row n we de(ne suh funtion reursivelyc ellD if s wnt to sum up IH numersD s ould sy tht sum is the (rst numerD plus the sum of W othersF he se se here is tht if the numer of numers we re supposed to sum gets elow ID then the sum is zeroF vet9s see wht this would look like in odeF

CHAPTER 6.

RECURSION FOR ITERATION

IIS

def sumInputInts(num:Int):Int = { if(num>0) { readInt()+sumInputInts(num-1) } else { 0 } }


he if is eing used s n expression hereF st is the only expression in the funtion so it is the lst one nd will e the return vlue of the funtionF sf numD the rgument to the funtionD is not greter thn zeroD then the funtion returns zeroF sf it isD the funtion will red in new vlue nd return the sum of tht vlue nd wht we get from summing one fewer vluesF ht if we don9t know in dvne how mny vlues we re going to sumc ht if we wnt to keep going until the end is rehedc e ould do thisF yne prolem is determining wht represents the endF e need to hve the user type in something distintly di'erent tht tells us they hve entered ll the vlues they wnt to sumF en esy wy to do this would e to only llow the user to sum positive vlues nd stop s soon s nonEpositive vlue is enteredF his gives us funtion tht doesn9t tke ny rgumentsF e don9t hve to tell it nythingF st will return to us n integer for the sum of the numers entered efore the nonEpositive vlueF uh funtion ould e written s followsF

def sumInputPositive():Int = { val n=readInt() if(n>0) { n+sumInputPositive() } else { 0 } }


his time we red new vlue efore we determine if we will ontinue or stopF he deision is sed on tht vlueD whih we store in vrileD nF impty prentheses hve een dded fter the funtion nme for oth the delrtion nd the llF his is style issue euse they ren9t requiredF st is onsider proper style to use prentheses if the funtion hs side e'ets nd leve them o' if it doesn9tF ou will rell from hpter R tht side e'ets re the wy in whih funtion hnges things tht go eyond just returning vlueF ht does this funtion do tht uses us to sy it hs side e'etsc he side e'ets here re in the form of reding inputF eding input is side e'et euse it n hve n impt eyond tht one funtionF gonsider hving two di'erent funtions tht oth red inputF he order in whih you ll them is likely to hnge their ehviorF ht is euse the seond one will red input in the stte tht is left fter the (rst oneF his funtion does good jo of letting us dd together n ritrry numer of user inputsD ut it hs signi(nt limittionD it only works with positive

CHAPTER 6.

RECURSION FOR ITERATION

IIT

vluesF ht is euse we reserve negtive vlues s the stop onditionF here ould ertinly e irumstnes where this limittion ws prolemF row ould we get round itc ht other methods ould we use to tell the funtion to stop the reursionc e ould pik some prtiulr speil vlue like EWWW to e the end onditionF hile EWWW might not seem like prtiulrly ommon numerD this is relly no etter thn wht we hd efore euse our funtion still n9t operte on ny vlid integer vlueF e9d like to hve it where the termintion input is something like the word quitF omething speil tht isn9t numerF e n do this if we don9t use redsntF e ould insted use the redvine funtion whih will red full line of input nd returns stringF ou might e tempted the to rete method like thisX

def sumUntilQuit():Int = { val n=readLine() if(n!=quit) { n+sumUntilQuit() } else { 0 } }


sf you enter this into (le nd then lod it into the onsole though you will get the following errorF

<console>:8: error: type mismatch; found : java.lang.String required: Int n+sumUntilQuit() ^


his is euse the funtion is supposed to return n sntD ut n is string nd when we use C with string wht we get is stringF hy is n stringc feuse tht is the type returned y redvine nd l9s type inferene deided on the line vl naredvine@A tht n must e stringF his prolem n e esily (xedF e know if the user is giving us vlid inputD the only things tht will e entered re integer vlues until the word quit is typed inF o we should e le to onvert the string to n intF ht n e done s shown hereF

def sumUntilQuit():Int = { val n=readLine() if(n!=quit) { n.toInt+sumUntilQuit() } else { 0 } }

CHAPTER 6.

RECURSION FOR ITERATION

IIU

xow we hve version of the funtion whih will red one integer t time until it gets the word quitF sf you do some testing you might (gure out there ws nother slight hnge to the ehviorF he erlier funtions worked whether the numers were pled on one line with spes etween them or eh on seprte linesF his version only works in the seond seF e will e le to (x tht prolem in the next hpterF umming up unh of numers n e helpfulD ut it is it siF e will see if we n do something more omplexF e tiny step up in the omplexity would e to tke n vergeF he verge is nothing more thn the sum divided y the numer of elementsF sn the (rst version of the funtion when we enter how mny numer would e redD this would e trivil to writeF e don9t even need to write itF he user knows how mny numers there wereD just divide y thtF hings ren9t so strightforwrd for the other versions thoughF st isn9t ler we know how mny vlues were input nd we don9t wnt to fore the user to ount themF ine we need oth sum nd ount of the numer of vlues to lulte n vergeD we need funtion tht n give us the sum nd the numer of vluesF his is nother exmple of funtion tht needs to return two vlues nd s eforeD we will use tuple to do the joF o we will write new funtion lled sumendgount whih returns tuple tht hs the sum of ll the numers entered s well s the ount of how mny there wereF e will se this o' the lst version of sumntiluit so there re no restritions on the numers the user n inputF uh funtion might look like the followingX

def sumAndCount():(Int,Int) = { val n=readLine() if(n!=quit) { val (s,c)=sumAndCount() (s+n.toInt,c+1) } else { (0,0) } }
sf you lod this funtion into the iv nd ll itD you n enter set of numers nd see the return vlueF sfD for exmpleD you enter QD RD SD nd T on seprte lines followed y quitD you will get thisX

res0: (Int, Int) = (18,4)


his looks lot like wht we hd eforeD only every line relted to the return of the funtion now hs tuple for the sum nd the ountF e see it on the (rst line for the return typeF e lso see it on the lst line of oth rnhes of the if expression for the tul return vluesF he lst ple we see it is in the reursive rnh where the return vlues from the reursive ll is stored in tupleF his syntx of n ssignment into tuple is tully doing pttern mthing whih ws disussed t the end of the lst hpterF nlike with mth

CHAPTER 6.

RECURSION FOR ITERATION

IIV

sttementsD this type of pttern mth hs to mthF sf it doesn9tD the progrm will rsh nd give you n error messgeF xow we hve oth the sum nd the ountF st is simple mtter to use this in di'erent funtion tht will lulte the vergeF he funtion shown elow lls sumendgount nd uses the two vlues tht re returned to get (nl nswerF

def averageInput():Double = { val (sum,count)=sumAndCount() sum.toDouble/count }


he one thing tht you might t (rst (nd odd out this funtion is tht it hs two ples where houle ppersF ht is given s the return type nd in the lst expression the tohoule method is lled on sumF his is done euse verges ren9t generlly whole numersF e hve to ll tohoule on sum or ount euse otherwise l will perform integer division whih truntes the vlueF e ould onvert oth to houlesD ut tht isn9t required euse numeril opertions etween houle nd n snt utomtilly onvert the snt to houle nd result in houleF

6.4 Abstraction
ht ifD insted of tking the sum of unh of user inputsD we wnt to tke produtc ht would we hnge in sumendgount to mke it produtendE gountc he ovious hnge is tht we hnge ddition to multiplition in the reursive rnh of the ifF e less ovious hnge is tht we lso need the se se to return I insted of HF o our modi(ed funtion might look like thisF

def productAndCount():(Int,Int) = { val n=readLine() if(n!=quit) { val (s,c)=productAndCount() (s*n.toInt,c+1) } else { (1,0) } }
his is lmost extly the sme s wht we hd eforeF e just lled it di'erent nme nd hnged two hrters in itF his opying of ode where we mke minor hnges is something tht is generlly frowned uponF ou might sy tht it doesn9t smell right1 F here re numer of resons why you would wnt to void doing this type of thingF pirstD wht hppens if your (rst version
1 Indeed,
the term smell is the actual terminology used in the eld of refactoring for things in code that aren't quite right and should probably be xed.

CHAPTER 6.

RECURSION FOR ITERATION

IIW

hd ugc ellD you hve now duplited it nd when you (gure out something is wrong you hve to (x it in multiple plesF e seond option is losely relted to this whih is if you relize you wnt it more funtionlity so you wnt to dd somethingF egin you now hve multiple versions to dd tht intoF sn dditionD it just mkes the ode se hrder to work withF vonger ode mens more ples things n e messed up nd more ode to go through when there is prolemF por this resonD we strive to redue ode duplitionF he wy we do this is to inlude strtionF e look for wys to mke the originl ode more )exile so it n do everything we wntF e will see strtion omes up lot in this ookF st is one of the most importnt tools in gomputer iene nd remrkly powerful onept tht you will wnt to understndF rere we re strting with firly simple exmpleF sn order to strt these funtions to mke them into oneD we fous on the things tht were di'erent etween them nd sk if there is wy to pss tht informtion in s rguments to version of the funtion tht will do othF por thisD the hnging of the nme isn9t importntF ht is importnt is tht we hnged the opertion we were doing nd the se vlue tht ws returnedF he se vlue is esy to del withF e simply pss in n rgument to the method tht is the vlue returned t the seF ht might look like thisF

def inputAndCount(base:Int):(Int,Int) = { val n=readLine() if(n!=quit) { val (s,c)=inputAndCount(base) (s*n.toInt,c+1) } else { (base,0) } }
he rgument se is pssed down through the reursion nd is lso returned in the se seF roweverD this version is stuk with multiplition so we hven9t gined ll tht muhF heling with the multiplition is it hrderF por tht we need to think out wht multiplition nd ddition relly re nd in prtiulr how they re used hereF foth multiplition nd ddition re opertorsF hey tke in two opernds nd give us k vlueF hen desried tht wyD we n see they re like funtionsF sndeedD wht we need is funtion tht tkes two snts nd returns n sntF ht funtion ould e multiplition or ddition nd then the inputendgount funtion would e )exile enough to hndle either sum or produtF st might look like thisF

def inputAndCount(base:Int,func:(Int,Int)=>Int):(Int,Int) = { val n=readLine() if(n!=quit) { val (s,c)=inputAndCount(base,func)

CHAPTER 6.

RECURSION FOR ITERATION

IPH

(func(s,n.toInt),c+1) } else { (base,0) }

he seond rgument to inputendgountD whih is lled funD hs more omE plex typeF st is funtion typeF st is funtion tht tkes two snts s rguments nd returns n sntF es with seD we pss fun through on the reursive llF e lso used fun in ple of the B or the C in the (rst element of the return tuple in the reursive seF xow insted of doing sCnFtosnt or sBnFtosntD we re doing fun@sDnFtosntAF ht tht does depends on the funtion tht is pssed inF o mke sure we understnd this proess we need to see it in tionF vet9s strt with doing sum nd use the longestD esiest to understnd syntxF e de(ne funtion tht does ddition nd pss tht inF por the input we type in the numers QD RD nd S followed y quitF e just won9t show themF

scala> def add(x:Int,y:Int):Int = x+y add: (x: Int,y: Int)Int scala> inputAndCount(0,add) res3: (Int, Int) = (12,3)
sn the ll to inputendgount we used the funtion ddD whih ws de(ned ove it s the seond rgumentF sing funtion de(ned in this wy though fores us to do lot of typingF his is extly the reson l inludes funtion literlsF ou will rell from the hpter on funtions tht funtion literl llows us to de(ne funtion on the )y in lF he norml syntx for this looks lot like the funtion type in the de(nition of inputendgountF st uses n ab etween the rguments nd the ody of the funtionF sing funtion literl we ould ll inputendgount without de(ning the dd funtion in this wyF

scala> inputAndCount(0,(x,y)=>x+y) res4: (Int, Int) = (12,3)


yne thing to notie out this is tht we didn9t hve to speify the types on x nd yF ht is euse l knows tht the seond rgument to inputendgount is funtion tht tkes to snt vluesF es suhD it ssumes tht x nd y must e of type sntF xot ll uses of funtion literls will give l this informtionD ut mny will nd when they do we n do less typing y letting l (gure out the types for usF sf you rememer k to the setion on funtion literlsD you will rell there is n even shorter syntx for delring them tht only works in ertin situtionsF ht ws the syntx tht uses s pleholder for the rgumentsF his syntx n only e used if eh rgument ours only one nd in orderF sn this se tht hppens to e trueD so we re llowed to use the shorthndF ht simpli(es our ll ll the wy down to thisF

CHAPTER 6.

RECURSION FOR ITERATION

IPI

scala> inputAndCount(0,_+_) res5: (Int, Int) = (12,3)


yf ourseD the reson for doing this ws so tht we ould lso do produts without hving to write seond funtionF he produt funtion di'ered from the sum funtion in tht the se se ws I nd it used B insted of CF sf we mke those two hnges to wht we did oveD we will see tht we hve indeed reted single funtion tht n do either sum or produtF

scala> inputAndCount(1,_*_) res6: (Int, Int) = (60,3)


xot only did we sueed hereD we did so in wy tht feels stisfying to usF hyc feuse our strtion n e used in miniml wy nd only the essentil vritions hve to e expressedF e don9t hve to do lot of extr typing to use the strtionF st isn9t muh longer to ll inputendgount thn it ws to ll sumendgount or produtendgountF sn dditionD the only things we hnged etween the two lls were the hnging of the H to I nd the C to BF hose were the ext sme things we hd to hnge if we hd done the full opy nd pste of the funtionsF his mens tht the onept we wnt to express is oming through lerly nd isn9t ofusted with lot of overhedF he inputendgount funtion is wht we ll higher order funtionF ht is euse it is funtion tht uses other funtions to operteF e provide it with funtion to help it do its joF his type of onstrut is seen mostly in funtionl lngugesF st is possile to rete this type of e'et in other lngugesD ut the syntx is typilly muh longerF ou might sy we only hd to duplited the ode one to hve the sum nd the produtF ss it relly worth the e'ort of our strtion to prevent thtc ss this relly ll tht smellyc he nswer with only sum nd produt is proly noF e single ode duplition isn9t the end of the worldF roweverD if s next sk you to omplete versions tht return the minimum or the mximumD wht do you do thenc ithout the strtionD you get to opy nd pste two more versions of the ode nd mke similrly minor hnges to themF ith the strtionD you just ll inputendgount with di'erent rgumentsF he question of whether it is worth it to strt relly depends on how muh expnsion you expet in the futureF sf the strtion doesn9t tke muh e'ort it is proly worth doing to strt with euse it is often hrd to predit if you will need to extend something in the futureF ou might not feel this in lssesD ut it eomes very signi(nt in professionl development when you often ren9t told up front extly wht is wnted of you nd even when you reD the ustomer is prone to hnge their mind lter in the proessF

6.5 Looking Ahead


his won9t e our lst look t reursion in this ookF sndeedD we hve just srthed the surfeF e hve only used reursion in this hpter to repet

CHAPTER 6.

RECURSION FOR ITERATION

IPP

tsksF e hve used it s model for repetitionF he rel power of reursion omes from the ft tht it n do lot more thn just repetitionF eursive lls hve memoryF hey don9t just know where they reD they rememer wht they hve doneF his relly omes into ply when reursive funtion lls itself more thn oneF ht is topi for lterD ut efore we leve this (rst enounter with reursion we will give you little rin teser for you to think outF felow is little it of odeF ou will notie tht it is nerly identil to the ounthown funtion tht we wrote ner the eginning of this hpterF yther thn hnging the nme of the method the only di'erene is tht two lines hve een swppedF ut this funtion into lF ht does it doc wore importntlyD why does it do thtc

def count(n:Int) { if(n>=0) { count(n-1) println(n) } }

Self-Directed Study
inter the following sttements into the iv nd see wht they doF ry some vritions to mke sure you understnd wht is going onF xote tht some lines red vlues so the iv will puse until you enter those vluesF he outome of other lines will depend on wht you enterF

scala> val n=readInt() scala> val m=readInt() scala>


333 everything

Exercises
IF rite exponentition using multiplitionF our funtion only hs to work for integer vluesF PF sf you did ID most likely you hve funtion where if you rise numer to the N th powerD it will do N @or mye N 1A multiplitionsF gonsider how you ould mke this smrterF st turns out tht you n mke one tht does lot fewer multiplitionD log2 N to e extF hink out how you would do this nd write ode for itF QF rite reursive funtion tht will print powers of two up to some vlueF RF rite reursive funtion tht will print powers of two up to some powerF

CHAPTER 6.

RECURSION FOR ITERATION

IPQ

SF rite reursive funtions tht will print multiplition tle up to IHsF ry to get it running (rstD then onsider how you ould mke everything line upF TF 333 min nd mx versions of strt inputendgount s well nd opy nd pste versionsF UF hesrie the ehvior of the lst ount funtion in the hpterF VF rite reursive funtion lled isrime tht returns foolen nd lets you know whether or not numer is primeF WF rite funtion tht prints the prime ftors of numerF IHF he wndelrot set is frtl in the omplex plneF st is desried y 2 + c where z0 = 0 nd c is the point in the the simple eqution zn+1 = zn plneF sf the sequene is oundedD the point is in the setF sf it heds o' to in(nityD it isn9tF se the solution to exerise RFQ to write funtion tht will tke vlue of cD nd vlue of z nd return how mny itertions it tkes for the mgnitude of zn to eome greter thn R or IHH if it doesn9t get tht ig in IHH itertionsF

Projects
IF por this option s wnt you to write funtions tht do the si mth opE ertions of dditionD multiplitionD nd exponentition on nonEnegtive sntsF he th is tht you n9t use CD BD or ny funtions from mthF ou only get to ll the suessor nd predeessor funtionsF def su@iXsntAXsnt a iCI def pred@iXsntAXsnt a iEI hese funtions silly do ounting for youF o you will de(ne ddiE tion in terms of those twoD then de(ne multiplition in terms of ddition nd exponents in terms of multiplitionF PF rite funtion tht will return tring with the prime ftoriztion of positive sntF he formt for the print should e peCpeCFFF rere eh p is prime numer nd e is the how mny times it ppers in the prime ftoriztionF sf you ll this funtion with IPH it would return PQCQICSI euse IPHaPBPBPBQBSF ememer tht numer n is divisile y i if n7iaaHF por the prime numers strt ounting up from PF sf you pull out ll the ftors of lower numersD you won9t (nd ny ftors tht ren9t primeF por exmpleD when you pull PQaV out of IPH you get IS whih only hs ftors of Q nd S so you n9t get RF QF his projet uilds on top of projet SFRF ou re using the funtions from tht projet nd putting them into formt where they n e used for

CHAPTER 6.

RECURSION FOR ITERATION

IPR

multiple geometri ojetsF he user inputs ry (rst nd fter tht is series of spheres nd plnesF ou wnt funtion tht returns the (rst ojet hit y the ry nd the prmeter @tA of the hitF RF en interesting twist in iology over the pst few dedes is the ility to look t the popultions of di'erent speies nd how they intert with one notherF yftenD the wy in whih di'erent popultions vry over time n e pproximted y simple mthemtil expressionsF sn this projet you will use your si knowledge of onditionls nd funtions with reursion to exmine simple se where you hve two di'erent popultions tht intert in predtorEprey mnnerF he simplest form of this prolem is the rit nd fox senrioF he ide is tht eh summer you ount the popultion of rits nd foxes in ertin regionF his region is firly well isolted so you don9t hve nimls oming in or levingF sn dditionD the limte is extremely temE perte nd there is lwys enough grss so environmentl ftors don9t seem to impt the popultionsF ell tht hppens is eh yer the rits try to et nd hve ies while not getting eten nd the foxes try to th ritsF e will mke up some formuls for wht hppens to the popultion from one yer to the next nd you will write progrm to produe this sequeneF yver the ourse of eh yerD the rit popultion will e impted in the following wysF ome rits will e ornD some rits will die of nturl usesD nd some rits will e etenF imilrly some foxes will e orn nd some will dieF he numer of rits eten depends upon the popultion of foxes @more foxes et more ritsA nd the numer of foxes who re orn nd die depends on the numer of rits euse foxes n9t live long or hve young without (nding rits to etF e n omine these things to ome up with some equtions tht predit the numers of foxes nd rits in given yer sed on the numer in the previous yerF

Rn+1 = Rn + A Rn B Rn Fn Fn+1 = Fn C Fn + D Rn Fn
rere we ssume tht the nturl tendeny of rit popultions is to inE rese without foxes round nd the nturl tendeny of fox popultions is to derese without rits roundF he R onstnts should hve posiE tive vluesF A represents the norml inrese in rit popultion without predtionF B is the predtion rte nd is multiplied y oth the rit popultion nd the fox popultion euse if either one is smllD the preE dtion rte is smllF C is the rte t whih foxes would normlly die out without eing le to er young @if they didn9t hve enough foodAF D is the rte t whih fox will er young when they do hve rits to feed onF

CHAPTER 6.

RECURSION FOR ITERATION

IPS

he input for your progrm is the initil rit popultionD R0 D the initil fox popultion F0 D nd the four onstntsF o strt you o'D you might try vlues of IHHD IHD HFHID HFHHID HFHSD nd HFHHIF he lst four numers re AD B D C D nd D respetivelyF ou n ply with these vlues to try to (nd some tht produe interesting resultsF rint out the (rst IHHH itertionsF o mke it so tht you n see your results esilyD s wnt your output to e only numersF xever prompt for nythingF he dvntge of this is tht you n rete (le tht is esy to plot with progrm like gnuplotF hen you run the progrm you rediret the output to (le then you n run gnuplot nd plot it to see wht it looks likeF sf you print Q numers per lineD n R F D nd put it in (le lled popFtxt then you n plot tht in gnuplot with ommnd like plot 9popFtxt9 using @6IAX@6PAD 9popFtxt9 using @6IAX@6QAF here re mny other options in gnuplot nd you n use the help ommnd to see themF

Chapter 7

Arrays and Lists in Scala


edding onditionls nd logi expnded our pilities drmtillyF gomE ining it with reursion gives us the ility to do lmost nything we wntF ehnillyD we hve full omputing powerF roweverD there re some ides tht re hllenging to express with wht we urrently know nd there re etter wys to sy them in l nd progrmming lnguges in generlF yne of these ides is the ility to refer to mny di'erent ojetsF sn hpter Q we gined the ility to refer to ojets y nmes with vl nd vr delrE tionsF sing thoseD we ould mke s mny nmes s we wnt nd hrd ode in referenes to themF e ould even hve ig mth sttements tht llow us to selet prtiulr vriles sed on some vlueF hese pprohes re verE ose nd not prtiulrly usefulF sn this hpter we will egin lerning out collections in lF golletions re types tht llow us to store nd look up mny di'erent vlues using single nmeF wost of this hpter will fous on the most si typesD arrays nd listsF hey re two di'erent types tht on the surfe seem to provide similr funtionlityD ut we will see tht they re tully very di'erentF

7.1 Making Arrays


he most si olletions of dt in l or other lnguges re rrys nd listsF irtully every lnguge will inlude one s something of fundmentl spet of the lngugeF l hppens to inlude othF he rry nd the list re wht l refers to s sequencesF ht mens tht they store numer of di'erent vlues in spei( order nd you n get to the elements in them y n integer indexF his (rst setion will slowly uild up why suh things re signi(nt nd the most si usge of them in rrysF sn the lst hpter we used reursion to do things suh s sum or tke the produt of unh of numers entered y the userF ht if we wnted to do othc e ould hve done oth sum nd produt if the user entered the numers twieD ut tht would e ine0ientF e hd one signi(nt prolem IPT

CHAPTER 7.

ARRAYS AND LISTS IN SCALA

IPU

with wht we were doingF e took the numers from the user nd performed opertions on themD ut we didn9t relly store them so tht we ould use them ginF st ws ll one shot delF he reson for this ws tht the types we hve so fr store single vlue orD in the se of tupleD (xed numer of vluesF e don9t relly hve good wy to store vrile numer of vlues so tht we n work with them nd do multiple opertions on themF ht is extly wht olletions will llow us to doF o relly understnd thisD it helps to look t some exmplesF e will strt y mking some rrys tht hve vlues in themF

scala> Array(1,2,3,4) res0: Array[Int] = Array(1, 2, 3, 4) scala> Array(1.0,2.0,3.0,4.0) res1: Array[Double] = Array(1.0, 2.0, 3.0, 4.0) scala> Array('c','a','t') res2: Array[Char] = Array(c, a, t) scala> Array(This,is,a,test) res3: Array[java.lang.String] = Array(This, is, a, test)
rere we hve reted four di'erent rrys of di'erent typesF he syntx for mking n rry with vlues in it is to follow the word erry with list of prmeters for the vlues we wnt in the rryF es lwysD fter eh expression the iv tells us the nme used for thisD the types of the expressionD nd the vlue of the expressionF he type of the expression here shows something tht we hve never seen eforeF he type isn9t just erryF he type nme erry is followed y squre rkets tht hve nother type in themF his is lled parameterized typeF ell the olletion types in l re prmeterizedF e will tlk out this in more detil lter in this hpterD ut the mening should e lerF he type errysnt is n rry tht n hold integer vlues in itF es usulD we didn9t hve to tell l tht the (rst rry ws n rry of type sntD it (gured tht outF ou n override l9s type inferene nd spei(lly tell it the type you wntF he exmple elow mkes n erryhoule even though ll the vlues in it re integersF his is perfetly vlid euse ll vlues in snt re lso vlid vlues of houleF

scala> Array[Double](1,2,3,4) res4: Array[Double] = Array(1.0, 2.0, 3.0, 4.0)


uh foring hs to mth wht you pss inF es you n see elowD l will not llow you to do this for n invlid onversionF

scala> Array[Int](Does,this,work) <console>:6: error: type mismatch; found : java.lang.String(Does) required: Int Array[Int](Does,this,work) ^ <console>:6: error: type mismatch;

CHAPTER 7.

ARRAYS AND LISTS IN SCALA

IPV

found : java.lang.String(this) required: Int Array[Int](Does,this,work) ^ <console>:6: error: type mismatch; found : java.lang.String(work) required: Int Array[Int](Does,this,work) ^
e n lso mke rrys tht hve the defult initil vlueF his is helpful for mking lrger rrysF st is not unusul for rrys to hve thousnds or even millions of elementsF e ertinly don9t wnt to hve to type in vlues for those y hndF rere is the syntx for thtF

scala> new Array[Int](101) 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,

res7: 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,

Array[Int] = Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)

he defult vlue for numeri types is zeroF he defult for the foolen type is flseF por most other typesD mny of whih we hven9t lerned outD the defult is nullF

7.2 Using Arrays


o now you know how to mke rrysD ut wht n you do with themc he (rst things we need to do re to get the vlues stored in the rry nd hnge the vlues stored in the rryF his is done y following the nme of the rry with prentheses nd numer tht is the index of the thing we wntF errysD s with most things in most modern progrmming lngugesD re zero indexedF o the (rst element in the rry is t index zero nd if there re x things in the rryD the lst one is t index xEIF rere is n exmpleF

scala> val arr=Array(7,4,6,3,9,1) arr: Array[Int] = Array(7, 4, 6, 3, 9, 1) scala> arr(0) res8: Int = 7 scala> arr(1) res9: Int = 4 scala> arr(5) res10: Int = 1
he (rst sttement retes new vrile nmed rr tht is n rry of integers nd gives tht rry six vlues to storeF he next three ommnds silly

CHAPTER 7.

ARRAYS AND LISTS IN SCALA

IPW

pull out vlues from tht rryF he expression rr@HA gets the (rst elementsD rr@IA gets the seondD nd rr@SA gets the lstF ht goes in the prentheses doesn9t hve to e simple integer eitherF st n e ny expression of type sntF ou ould do something muh more omplex to pull out vlueF

scala> i: Int scala> res12:

val i=2 = 2 arr(2*i-2) Int = 6

he sme type of expression n lso e used in n ssignment expressionF o we n lter the vlues tht re stored in n rry s we see in the following exmpleF

scala> arr(4)=99 scala> arr res13: Array[Int] = Array(7, 4, 6, 3, 99, 1)


rere we see how we n use ssignment to hnge the vlue of one of the elements of the rryF his might surprise you euse we originlly delred rr to e vlF reviously we sid tht you n9t hnge the vlue of vrile tht is reted with vlF his doesn9t tully rek tht ruleF ou seeD the nme rr still refers to the sme rryF ht hs hnged is the vlue in the rryF en nlogy might e tht n rry is house nd the vlues re the people in itF he vrile rr refers to prtiulr houseF eople might ome nd go from the houseD ut the house itself is the smeF e n demonstrte this y trying to hnge wht rry the vrile rr referenesF

scala> arr=Array(2,7,5) <console>:6: error: reassignment to val arr=Array(2,7,5) ^


e ll the erry type mutable type euse the vlues in it n e hngedF ypes whose internl vlues n9t e hnged re lled immutable typesF his distintion is very signi(nt to us in l nd in progrmming in generl s it lters how we del with dtF e will tlk more out it euse the vist typeD whih we will lso look t in this hpterD hppens to e immutleF sndeedD ll of the types tht we hve seen so fr re immutleF yne they re retedD the vlues they hve never hngeF he erry is our (rst exmple of something tht is mutleF xot everything out n rry n e hngedF es we hve seenD we n hnge the vlues stored in n rryF roweverD we n9t hnge how mny things re stored in n rryF he numer of things n rry holds n e lled the length or the size of the rryF sn ftD the erry type hs methods lled length nd size whih give us this informtionF

CHAPTER 7.

ARRAYS AND LISTS IN SCALA

IQH

scala> arr.length res5: Int = 6 scala> arr.size res6: Int = 6


hen you rete n rry you hve to speify length nd tht length will never hngeF sf you use vr style vrileD you n mke new rry with di'erent length nd hve the nme refer to itD ut to do tht you rete ompletely new rryD you don9t lter the size of the old oneF sf you try to use n index vlue tht is either negtive or too lrgeD l will give you n error messge sying tht you hve gone outside the ounds of the rryF e n see wht tht looks like here with ttempts to ess nd hnge indexes out of oundsF

scala> arr(100) java.lang.ArrayIndexOutOfBoundsException: 100 at .<init>(<console>:7) at .<clinit>(<console>) at RequestResult$.<init>(<console>:9) at RequestResult$.<clinit>(<console>) at RequestResult$scala_repl_result(<console>) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun... scala> arr(100)=0 java.lang.ArrayIndexOutOfBoundsException: 100 at .<init>(<console>:7) at .<clinit>(<console>) at RequestResult$.<init>(<console>:9) at RequestResult$.<clinit>(<console>) at RequestResult$scala_repl_result(<console>) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun...
xow tht we know the ground rules for using rrysD we n write some funE tions tht tke dvntge of them in useful wyF sn the lst hpter we used reursion to red in set of numers tht we ould then do opertions onF yne motivtion we used for olletions ws tht we ouldn9t store the vlues to do two or more opertions on themF o two useful funtions might e to hve one tht (lls n rry from user input nd nother tht does the types of opertions we did eforeD ut this time on the rryF e will strt with the funtion to (ll the rry from user inputF yviously this funtion needs to e pssed the rry tht it will (llF hen we re using n rryD it will e esiest to use the style where we speify t the eginning how mny numers re to e redF his is euse rrys hve (xed sizeF he rry knows its size so tht informtion doesn9t need to e pssedF ht does need to e pssed is the index tht the next numer will e red intoF

CHAPTER 7.

ARRAYS AND LISTS IN SCALA

IQI

he termintion ondition would e tht we re trying to red into lotion eyond the end of the rryF he funtion to do this might look like thisF

def fillArray(arr:Array[Int],index:Int) { if(index<arr.length) { arr(index)=readInt() fillArray(arr,index+1) } }


his funtion is strightforwrdD ut it is worth noting tht it doesn9t return nythingF he ft tht rrys re mutle mens tht we n pss in n rry nd hve the funtion mutte the ontentsF es resultD nothing needs to e returnedF he results of this funtion re held in the modi(ed ontents of the rryF he following shows this funtion in tionF

scala> val numbers=new Array[Int](4) numbers: Array[Int] = Array(0, 0, 0, 0) scala> fillArray(numbers,0) scala> numbers res3: Array[Int] = Array(2, 3, 4, 5)
e new rry of integers is reted tht n hold four vluesF e ll (llerry nd enter the vlues PD QD RD nd SF efter doing tht we n inspet numers nd see tht it now holds those vluesF xow we need to perform n opertion on the ontents of the rryF e will skip the step of mking speil funtion for just doing ddition or multipliE tion nd jump stright to the more strt nd )exile method where we pss in funtion to operte on the ontentsF sn ddition to the funtion doing the opertionD we lso need n rry nd n integer for the urrent indexF nlike wht we did in the previous hpterD we don9t need to pss in se euse we know when we re t the eginning or end of the rryF he funtion ould look like thisF

def operateOnArray(arr:Array[Int],index:Int,func:(Int,Int)=>Int):Int = { if(index<arr.length-1) { func(arr(index),operateOnArray(arr,index+1,func)) } else { arr(arr.length-1) } }


sf n index t or eyond the lst element of the rry is pssed inD this returns the lst element of the rryF ytherwiseD it pplies the funtion to the urrent elements nd the result of the reursive funtion on susequent elementsF e n see this in tion on the previously de(ned rryD rrD in these ommndsF

CHAPTER 7.

ARRAYS AND LISTS IN SCALA

IQP

scala> operateOnArray(arr,0,_+_) res0: Int = 30 scala> operateOnArray(arr,0,_*_) res1: Int = 4536


elredy this llows us to see the dded power we get from using n rryF rving the vlues stored gives us the ility to operte on them multiple times without hving to input them multiple timesF

7.3 Lists
errys re the uilt in olletion of hoie in most nonEfuntionl lngugesF en rry is typilly stored s single lok of memoryF his mkes them fst nd e0ient for lot of opertionsF es we sw thoughD rrys re mutleF puntionl lnguges tend to len wy from muttion nd other side e'etsF sf you don9t llow muttionD rrys eome muh less e0ientF sf you wnt to hnge single vlue in the rry you hve to mke omplete opy of the rryF por this resonD funtionl lnguges tend to prefer listsF ehnilly these re linked listsD dt struture tht will e disussed lter in the ookF ou don9t hve to understnd the struture in detil though to see how to use itF e n uild list using the sme syntx we used to uild n rry with initil vluesF

scala> List(7,4,6,3,9,1) res2: List[Int] = List(7, 4, 6, 3, 9, 1)


vike the rry typeD the list type is prmetri nd l will (gure out the est type if you use this syntxF here is no syntx for mking n uninitilized listF ht is euse lists re immutleF yne you hve reted listD the vlues in it n9t e hngedF es suhD there isn9t muh point in reting long list with some defult vlueF ghnging it would require mking new listF roweverD there is nother wy to put lists together when we don9t know initilly ll of the vlues tht will e stored in themF e n e0iently uild lists one element t time if we dd elements to the front of the listF o dd elements to list we use the ons opertorD XXF rere is n exmple of dding single element to n existing listF

scala> val lst=List(2,3,4) lst: List[Int] = List(2, 3, 4) scala> 1::lst res3: List[Int] = List(1, 2, 3, 4)
e egin y reting list tht ontins PD QD nd RD then ons I to the eginning of the listF his opertion didn9t lter the originl listF snsted it gve us new list with n extr element t the eginningF feuse of the wy tht lists workD this is e0ientF st didn9t tully hve to opy the whole list to mke it workF e n look t lst gin to see tht it hsn9t hngedF

CHAPTER 7.

ARRAYS AND LISTS IN SCALA

IQQ

scala> lst res4: List[Int] = List(2, 3, 4)


sf you uild list with the ons opertorD it is ommon to strt with n empty listF here re two wys to represent n empty list in lF yne is to use wht we did eforeD ut not put ny rguments in the prenthesesF he other is to use xilF o we n uild the sme list we hd efore this wyF

scala> 1::2::3::4::Nil res5: List[Int] = List(1, 2, 3, 4)


ou hve to ple the xil t the end euse the XX opertor needs to hve list on the right hnd sideF xotie tht for this to workD the XX opertor is right ssoitiveF o IXXPXXQXXxil is the sme s IXX@PXX@QXXxilAAF his is the opposite of the norml mthemtil opertors whih re left ssoitiveF sn l ny opertor tht ends with olon will e right ssoitiveF e n use the ons opertor to write funtion tht uilds list of numers from user inputF his is reursive method tht will red in numers until it gets to quitF qoing until quit works well for lists euse we n esily dd new elements to listF ht wsn9t the se for rrys nd we needed to hve the size of the rry set when we egnF he method for doing this is quite simpleF

def inputList():List[Int] = { val in=readLine() if(in==quit) Nil else in.toInt::inputList() }


e n see this t work s well if we run it nd type in QD RD SD nd quit on seprte linesF

scala> inputList() res1: List[Int] = List(3, 4, 5)


st is possile to ess the elements of list the sme wy you do n rry y putting n index inside of prenthesesF roweverD for list this is very ine0ientF he preferred methodD espeilly in reursive funtionD is to use the methods hed nd tilF he hed method will give you k the (rst element of the listF he til method gives you list of ll the elements fter the (rst elementF sing these methods we n write n operteynvist funtion tht mirrors the operteynerry funtion like thisF

def operateOnList(lst:List[Int],func:(Int,Int)=>Int):Int = { if(lst.tail==Nil) lst.head else func(lst.head,operateOnList(lst.tail,func)) }

CHAPTER 7.

ARRAYS AND LISTS IN SCALA

IQR

xote tht we don9t require n index to e pssed inF e don9t hve ny CI or EI in this funtion eitherF ht type of ehvior omes from the ft tht when we reurseD we pss in lstFtilF e n see this funtion in tion hereF

scala> val lst=List(7,4,6,3,9,1) lst: List[Int] = List(7, 4, 6, 3, 9, 1) scala> operateOnList(lst,_+_) res0: Int = 30 scala> operateOnList(lst,_*_) res1: Int = 4536
his funtion ws written using n if sttementF hen working with listsD it is lso ommon to use pttern mthingF he XX n e used in pttern to indite list with di'erent prtsF his prtiulr funtion n e rewritten s shown hereF

def operateOnList2(lst:List[Int],func:(Int,Int)=>Int):Int = lst match { case h::Nil => h case h::t => func(h,operateOnList2(t,func)) case _ => 0 }
ou might wonder out the lst seF his isn9t requiredD ut if we leve it out we will get wrning telling us tht the mth is not exhustiveF his isn9t just the ompiler eing overly piky eitherF st turns out tht the originl method tht uses n if expression isn9t ompletely sfeF ry lling it with n empty list nd you will see whyF

7.4 Standard Methods


yne of the strengths of l is tht it hs rih interfesF hese re interfes with lot of di'erent methods in themF e looked t length nd size on the rry nd hed nd til on the listD ut this ws only srthing the surfeF ou n tully ll either of those on either lists or rrysF roweverD length nd size ren9t tht e0ient for lists while til is ine0ient on the rryF sn this setion we will run through smpling of the other methods tht re ville to us when working with lists nd rrysF e will strt with the simple onesF e hve roken the methods into few groups sed on wht they doF snside of eh group the methods re in lphetil orderF he methods tht sy they give you new olletion return olletion of the sme type tht it is lled onF o if you ll them on n erry you will get k n erryF sf you ll them on vist you will get k vistF hort exmples re shown for eh using the lst vrile de(ned oveF

wethods tht give you prt of olletion

CHAPTER 7.

ARRAYS AND LISTS IN SCALA

IQS

 drop ! kes n snt nd gives you k new olletion with ll the


elements fter skipping tht mnyF

lstFdrop@PA vistsnt a vist@TD QD WD IA

 init ! kes no rguments nd returns new olletion with ll the


elements exept the lstF

lstFinit vistsnt a vist@UD RD TD QD WA

 lst ! kes no rguments nd returns the lst element in the olleE


tionF

lstFlst snt a I

 slie ! kes two rguments whih re oth integer indexesF st returns

new olletion with ll the elements eginning with the index of the (rst rgument nd ending with the one efore the index of the seond vlueF

lstFslie@PDRA vistsnt a vist@TD QA

 splitet ! kes n snt for the index of the split lotionF st returns
lstFsplitet@QA @vistsntD vistsntA a @vist@UD RD TADvist@QD WD IAA

two new olletions where the (rst hs the (rst n elements nd the seond hs the restF

 tke ! kes n snt nd gives k new olletion with tht mny


elements from the eginning of this olletionF

lstFtke@QA vistsnt a vist@UD RD TA

 tkeight ! vike tkeD ut pulls the lst n elementsF


lstFtkeight@QA vistsnt a vist@QD WD IA foolen tests

 ontins ! kes n element nd returns whether or not the olletion


ontins n element equl to itF

lstFontins@VA foolen a flse

 endsith ! kes olletion of elements nd tells whether the urE

rent olletion ends with elements equl to those in the olletion pssed inF

CHAPTER 7.

ARRAYS AND LISTS IN SCALA

IQT

lstFendsith@vist@QDWDIAA foolen a true

 isimpty ! eturns whether or not the olletion is emptyF


lstFisimpty foolen a flse

 nonimpty ! he opposite of isimptyF


lstFnonimpty foolen a true

 strtsith ! kes olletion of elements nd tells whether the


lstFstrtsith@vist@UDSDTAA foolen a flse erh for something

urrent olletion strts with elements equl to those in the olletion pssed inF

 indexyf ! kes n element nd returns the index of the (rst element


lstFindexyf@QA snt a Q

in the olletion equl to the vlue pssed inF eturns EI if no element is foundF

 lstsndexyf ! kes n element nd returns the index of the lst


element in the olletion equl to the vlue pssed inF eturns EI if no element is foundF

lstFlstsndexyf@RA snt a I yther simple methods of note

 di' ! kes olletion of the sme type s n rgument nd returns

the multiset di'erene etween the twoF his mens tht it will give you k ll the elements tht were in the originl olletion tht don9t hve mth in the rgument olletionF

lstFdi'@vist@IDPDQDRAA vistsnt a vist@UD TD WA

 mktring ! gn e lled with zeroD oneD or three rgumentsF st

uilds single long string from the string representtions of the eleE mentsF sf no rgument is provided then nothing is put etween the strings for the elementsF sf one rgument is spei(edD it should e string tht is used to seprte the element stringsF sf three rguE ments re spei(ed the middle is seprtor nd the (rst nd lst re strings to put efore nd fter the elementsF

CHAPTER 7.

ARRAYS AND LISTS IN SCALA

IQU

lstFmktring@4 4A tring a U R T Q W I

 reverse ! kes no rguments nd returns new olletion with the


elements in the reverse orderF

lstFreverse vistsnt a vist@ID WD QD TD RD UA

 toerryD tovist ! ke no rguments nd mkes new olletion of


the type spei(ed with the elements in the urrent olletionF

lstFtoerry errysnt a erry@UD RD TD QD WD IA

 zip ! kes nother olletion nd returns olletion of tuples where

the (rst element omes from the olletion this is lled on nd the seond omes from the olletion pssed inF he length of the result is the shorter of the twoF

lstFzip@lstFreverseA vist@sntD sntA a vist@@UDIAD @RDWAD @TDQAD @QDTAD @WDRAD @IDUAA

 zipithsndex ! eturns new olletion of tuples where the (rst is


n element from the olletion nd the seond is its indexF

lstFzipithsndex vist@sntD sntA a vist@@UDHAD @RDIAD @TDPAD @QDQAD @WDRAD @IDSAA


he methods listed ove will work on ny type of sequeneF o they will work on vistsntD visttringD or vistvisthouleF here re few methods provided tht hve some speil requirements for the type of things in the listF hey require tht ertin opertions e de(nedF hese methodsD whih re selfEexplntoryD re minD mxD sumD nd produtF he min nd mx methods will work for types tht n e orderedF ht inludes not just things like snt nd houleD ut lso trings nd mny other types where n ordering mkes senseF he sum nd produt methods require tht the type of the olletion e numeriF o while we wrote operteynvist nd operteynerry to do sums nd prodE uts of those olletionsD l would hve llowed us to simply ll the sum or produt methods s is seen hereF

scala> lst.sum res2: Int = 30 scala> lst.product res3: Int = 4536


he requirement tht the vlues e numeri mens tht while you n onteE nte trings with CD you n9t put them together with sumF por visttring or errytringD you should use mktring to ontente the vluesF

CHAPTER 7.

ARRAYS AND LISTS IN SCALA

IQV

hile you might feel like the list of methods shown here is quite lot nd gives us mny pilitiesD we hven9t yet hit on the rel power of the l olletionsF ell of these methods hve tken norml vlues for rgumentsF tust like our (rst reursive methodsD they n e mde more powerful y dding some strtion nd mking them higher order methodsF felow is list of mny of the higher order methods tht re prt of the sequenes in lF

ount ! kes funtion tht will operte on n element nd return foolenF eturns the numer of elements in the olletion for whih this returns trueF

 lstFount@bSA  snt a Q
drophile ! kes funtion tht will operte on n element nd return foolenF eturns new olletion tht ontins ll elements fter the (rst group for whih tht funtion is trueF

 lstFdrophile@bQA  vistsnt a vist@QD WD IA


exists ! kes funtion tht will operte on n element nd return foolenF eturns true if there is some element in the olletion for whih the funtion is trueF

 lstFexists@x ab xbR 88 x`UA  foolen a true


(lter ! kes funtion tht will operte on n element nd return foolenF eturns new olletion tht ontins only the elements for whih the funtion is trueF

 lstF(lter@`SA  vistsnt a vist@RD QD IA


)twp ! kes funtion the will operte on n element nd return olletionF eturns new olletion uilt from ll the result olletions ppended togetherF

 lstF)twp@n ab if@n`TA lstFtke@nA else xilA  vistsnt a vist@UD RD TD QD UD RD TD UA


forll ! kes funtion tht will operte on n element nd return foolenF eturns true if the funtion is true for ll elements of the olleE tionF

 lstFforll@bPA

CHAPTER 7.

ARRAYS AND LISTS IN SCALA

IQW

 foolen a flse
foreh ! kes funtion tht opertes on n elements nd pplies it to ll elements in the olletionF eturns nothingF

      

lstFforeh@nabprintln@PBnAA IR V IP T IV P

indexhere ! kes funtion tht will operte on n element nd return foolenF eturns the index of the (rst element for whih the funtion is trueF

 lstFindexhere@7PaaHA  snt a I
lstsndexhere ! kes funtion tht will operte on n element nd return foolenF eturns the index of the lst element for whih the funtion is trueF

 lstFlstsndexhere@7PaaHA  snt a P
mp ! kes funtion tht opertes on n element nd returns someE thingF st returns new olletion tht ontins the results of pplying tht funtionF

 lstFmp@BPA  vistsnt a vist@IRD VD IPD TD IVD PA


prtition E kes funtion tht will operte on n element nd return foolenF eturns tuple with two new olletionsF he (rst ontins only the elements for whih the funtion is true nd the seond is the restF

 lstFprtition@`SA  @vistsntD vistsntA a @vist@RD QD IADvist@UD TD WAA


tkehile ! kes funtion tht will operte on n element nd return foolenF eturns new olletion tht ontins ll elements ll the elements t the eginning for whih tht funtion is trueF

CHAPTER 7.

ARRAYS AND LISTS IN SCALA

IRH

 lstFtkehile@bQA  vistsnt a vist@UD RD TA


hile the (rst set of methods ws strightforwrdD this group ould use it more explntionF e will fous on mp nd (lter euse they re very stnE drd in the funtionl progrmming worldF smgine we hve list or n rry of people9s nmesF his list might e very longD ut for our smple ode we will use just few so you n see the illustrtionF he nmes re in the norml formt tht people write themX (rst middle lst with the middle nme eing optionl or potentilly hving multiple middle nmesF por progrmming purposes we would like them to e in the formt lstD (rst middle euse we often re more out the lst nmeF ht we hve desried here is tht pplition of funtion to every element of sequene to get k new sequene with the modi(ed elementsF ht is extly wht the mp method does for usF ell we hve to do is (gure out how we would write funtion to do tht trnsformtion nd then we re setF he trnsformtion we wnt to do is to tke the lst word in the nme nd move it to the front with omm nd spe etween it nd the (rst nmeF fsillyD we wnt to split up the string on the lst speF he methods listed ove ould do this nielyD if only they worked on stringF es it turns outD they doF e n use string s sequene of hrtersF o we n use lstsndexyf to (nd the lst spe nd splitet to mke two stringsF e n see this on prtiulr string hereF

scala> val name=Mark C. Lewis name: java.lang.String = Mark C. Lewis scala> name.splitAt(name.lastIndexOf(' ')+1) res45: (String, String) = (Mark C. ,Lewis)
xow ll we need to do is put tht k together in the opposite order with omm nd speF sf we were going to e reorgnizing nmes like this frequentlyD we ould put this ode in stnd lone funtionF sf notD we n use funtion literl to de(ne it on the )yF por this exmpleD we will do it the seond wyF

scala> val names=List(Mark C. Lewis,Jason C. Hughes, Glen R. Stewart,Jen Hogan) names: List[java.lang.String] = List(Mark C. Lewis, Jason C. Hughes, Glen R. Stewart, Jen Hogan) scala> val lnames=names.map(n => { val (rest,last)=n.splitAt(n.lastIndexOf(' ')+1) last+, +rest } ) lnames: List[java.lang.String] = List(Lewis, Mark C. , Hughes, Jason C. , Stewart, Glen R. , Hogan, Jen )
o the use of mp llowed us to omplete tsk tht ould hve tken us firly lrge mount of ode in quik nd short wyF

CHAPTER 7.

ARRAYS AND LISTS IN SCALA

IRI

sf you hd long list of these nmesD you might wnt to do something like (nd ll the people who hve lst nmes eginning with prtiulr letterF por exmpleD we might wnt to (nd everyone whose lst nmes strts with n 9r9F por this we would use the (lter funtionF he (lter funtion will selet out vlues tht stisfy some ondition nd give us sequene with only those vluesF

scala> lnames.filter(_.startsWith("H")) res48: List[java.lang.String] = List(Hughes, Jason C. , Hogan, Jen )


hnks to (lter nd the strtsith methodD this is very simple one linerF here re some other methods tht weren9t listed ove euse they tke it more explntionF hey shouldn9t e too hrd to understnd though if you hve followed up to this point euse they do extly wht we did ourselves erlier in this hpter with the operteynerry nd operteynvist funtionsF e9ll strt with the redue methodsD redueveft nd redueightF hese methE ods tke funtion tht opertes on two elements of the sequene nd returns vlue of tht typeF he redue methods repetedly pply the funtion to suE essive elements the sme wy the operteynerry nd operteynvist methods didF he di'erent etween the two is whether they pply the opertions movE ing from left to right of from right to leftF sf the opertion is ommuttiveD like ddition or multiplitionD then the order doesn9t impt the resultD only potentilly the e0ienyF por nonEommuttive opertions it n mtterF rere re few exmples using the lst vrile tht we de(ned erlierF

scala> res49: scala> res50: scala> res51: scala> res52:

lst.reduceLeft(_+_) Int = 30 lst.reduceLeft(_*_) Int = 4536 lst.reduceLeft(_-_) Int = -16 lst.reduceRight(_-_) Int = 14

he (rst two lls do wht we hve seen efore tking the sum nd produt of the listF he lst two use di'ereneD whih isn9t ommuttiveD nd show how the results of redueveft nd redueight re di'erentF he redueveft method gives us @@@@UERAETAEQAEWAEIF he redue right method gives us UE@RE@TE@QE@WEIAAAAF sn the lst hpter we mde reursive method tht ould do these types of opertions with user inputF ht di'ered from wht we did in this hpter in tht we hd to pss in n extr vlue to use when the user terminted the reursionF e didn9t do nything speil with thtD ut it ould hve opened other possiilitiesF he redue opertions hve to operte on the element type of the olletion for oth rguments euse tht is wht hppens in the most deeply nested pplitionF sf we speify the se vlue the funtion n tke one rgument of di'erent type thn the elements in the list s long s it returns tht type s wellF sf we sy tht the sequene hs type e nd we wnt funtion tht will produe type fF sf the funtion hs the form @fDeAabf

CHAPTER 7.

ARRAYS AND LISTS IN SCALA

IRP

nd we provide (rst vlue of type f then we n run through the sequene pplying this funtion to eh of the e vlues until we get (nl f t the endF his funtionlity is provided y the foldveft nd foldight methodsF hese methods use something we hven9t seen yetD urryingF e urried funtion is funtion tht tkes one set of rguments nd returns funtion tht tkes nother set of rgumentsF rere is simple exmple of mking urried funtion using the norml l funtion type nd funtion literl syntxF

scala> def add(x:Int):(Int)=>Int = (y:Int)=>x+y add: (x: Int)(Int) => Int scala> val plus5=add(5) plus5: (Int) => Int = <function1> scala> plus5(6) res54: Int = 11
he (rst input de(nes funtion dd tht tkes n integer nd returns funtion whih tkes n integer nd returns n integerF he dd funtion is higherE order funtion euse it returns funtionF sn the seond line we ll dd nd pss it the rgument SF e store the result of this in vrile nmed plusSF xote tht plusS is tully funtion tht tkes n integer nd returns n integerF et the end we ll plusS nd pss it the vlue T whih gives us k IIF his exmple shows wht it mens to urry funtionF here n e times when this pproh is quite usefulF por tht resonD lD nd numer of other lngugesD provide shortut for doing itF sf you de(ne funtion nd follow it with more thn one rgument listD the funtion is urriedF o the ove ould e entered like this instedF

scala> def add(x:Int)(y:Int) = x+y add: (x: Int)(y: Int)Int scala> val plus5=add(5)_ plus5: (Int) => Int = <function1> scala> plus5(6) res55: Int = 11 scala> add(5)(6) res56: Int = 11
yne ig di'erene here is the undersore where the seond rgument list would goF his tells l tht you relly ment to only speify the (rst rgumentF his is introdued here euse the foldveft nd foldight methods re urE riedF he (rst rgument list tkes the se vlue to use on the (rst pplitionF he seond list is the funtion to pplyF he types e nd f don9t hve to e di'erent so we n use fold left to sum up list of integers like thisF

scala> lst.foldLeft(0)(_+_) res57: Int = 30

CHAPTER 7.

ARRAYS AND LISTS IN SCALA

IRQ

roweverD unlike the redue methodsD we n do other things like ount up the totl numer of hrters in sequene of stringsF e return method on sequene of strings ould only give us k stringD ut the fold methods n give us k nother typeF rere we do extly tht hereF e show oth the longer funtion literl syntx s well s the shorter versionF

scala> val wordList=List("How","many","characters","do","we","have") wordList: List[java.lang.String] = List(How, many, characters, do, we, have) scala> wordList.foldLeft(0)((count,word)=>count+word.length) res58: Int = 25 scala> wordList.foldLeft(0)(_+_.length) res59: Int = 25
et some point you might hve wondered where you would (nd out out ll of these methodsF iven with everything disussed in this setionD our list is inompleteF he omplete list of ll the types ville nd methods for them n e found in the epplitions rogrmmer snterfe @esAF ou n (nd the l es t the min l we siteF his hs lot of elements tht go eyond your urrent knowledgeD ut one of the min ojetives of this ook is tht you will e le to look up informtion in the es when you hve questions out how to do things in lF

7.5 A World of Types


e hve only egun to srth the surfe when it omes to types in lF fy the end of this ook we will see tht not only re there mnyD mny types provided y the l lngugeGlirriesD we n even de(ne our own types nd give them nmes though we won9t e doing this for whileF tillD it is worth eing more expliit out wht type is nd some of the detils of types in lF vet9s egin with the question of wht is typeF e type is set of vlues nd the ssoited opertions tht n e performed on those vluesF gonsider the type sntF here re set of di'erent vlues tht we n represent with n instne of sntF hey re ll the integer vlues etween EPIRURVQTRV nd PIRURVQTRUF here is lso set of opertions tht you n perform on n snt or on pirs of them suh s ddition nd sutrtionF sn this hpter we hve egun to see tht there is more to types in l thn the sis like sntF he types vist nd erry ren9t omplete on their ownF hey re prmetri typesF o e omplete they hve to hve type prmetersF o vistsnt is omplete type s is errytringF vist nd erry re fr from the only prmetri typesF wny of the types in the l lirry re prmetriF sn the seond hlf of this ook we will mke our own prmetri typesF por now it will e enough to tlk out them in the existing lirry ode nd how they n e used with funtionsF

CHAPTER 7.

ARRAYS AND LISTS IN SCALA

IRR

7.5.1 The Option Type


sf you strt digging through the es muh you will (nd tht the type yption omes up fir itF he ide of n Option type is tht they should e used when you ren9t ertin if you will hve vlue or notF en yptione n either e omee or xoneF sf it is ome it will hve vlue in it tht n e retrieved with getF sf there ws no vlue then you get xone nd know tht it doesn9t hve vlueF en exmple of method tht does this is the (nd method on sequeneF ou n ll (nd on either list or n rry nd pss it funtion tht tkes n element nd returns foolenF he (nd method is supposed to return the (rst element for whih the funtion returns trueF ht desription sounds simple enoughD ut wht if there isn9t onec ht hppens if (nd runs through the whole sequene nd nothing mkes the funtion return truec por tht resonD the (nd method returns yptione where e is the type ontined in the sequeneF o if nothing worksD it n return xoneF vet9s run through two exmples to see how this works using our list of integers we hve een using throughout this hpterF

scala> res20: scala> res21:

lst.find(_<4) Option[Int] = Some(3) lst.find(_<1) Option[Int] = None

he list does ontin elements tht re less thn RF he (rst of these is Q so we get k ome@QAF roweverD it doesn9t ontin nything less thn I so tht ll returns xoneF ou might wonder how you n use this type of return vlueF he nswer is to use mthF his little exmple tkes the result of (nd nd tells us wht it found or else tells us tht nothing ws foundF

scala> lst.find(_<4) match { | case Some(i) => "Found "+i | case None => "Nothing found" | } res22: java.lang.String = Found 3

7.5.2 Parametric Functions


ypes list vistD erryD nd yption re the only things tht n hve prmetersF puntions n hve prmeters s wellF his is something tht we will revisit lter onD ut it n help you to red the es if you re introdued to the syntxF e would mke funtion prmetri if we wnt it to work with multiple di'erent typesF he simplest exmple of parametric function is the identity method shown hereF

scala> def ident[A](a:A)=a ident: [A](a: A)A

CHAPTER 7.

ARRAYS AND LISTS IN SCALA

IRS

his method tkes n rgument of ny type nd returns the vlue pssed inF hile there ren9t mny situtions where you would wnt to do thisD it demonE strtes the syntx of prmetri funtionsF ou simply ple type prmeter nme in squre rkets etween the funtion nme nd the norml rgument listF st lso demonstrtes the power of prmetri funtionsD espeilly if we put it to use s we do hereF

scala> ident(3) res1: Int = 3 scala> ident(3.3) res2: Double = 3.3 scala> ident("3.3") res3: java.lang.String = 3.3
pirstD this one funtion works just (ne with n sntD nd houleD nd tringF ht is pretty goodF iven etterD it worked with ll those types without us telling it the typesF rmetri funtions n lmost lwys infer the types of the prmetersF rere is slightly more omplex exmple though it relly doesn9t do muh moreD funtion tht tkes two rguments nd returns tuple with those two vlues in itF

scala> def makeTuple[A,B](a:A,b:B) = (a,b) makeTuple: [A,B](a: A,b: B)(A, B)


his demonstrtes how funtion n hve multiple prmetersF hey pper s omm seprted list in the squre rketsF e lst simple exmple would e funtion tht mkes lists with three elementsF

scala> def threeList[A](a1:A,a2:A,a3:A) = List(a1,a2,a3) threeList: [A](a1: A,a2: A,a3: A)List[A]


he min reson for introduing these is tht they help us understnd something we sw erlier in this hpterD the fold methodsF e sid tht fold ws very muh like one of the reursive funtions we wrote in the lst hpter where we pss in oth se vlue nd funtionF roweverD the funtion tht we wrote only works with sntsF he fold methods work on sequenes of ny type nd wht is moreD they n return di'erent typeF ith the use of prmeters we n write funtion with this sme pilityF

def ourFold[A,B](lst:List[A],base:B)(f:(A,B)=>B):B = { if(lst.isEmpty) base else f(lst.head,ourFold(lst.tail,base,f)) }


vike the one in the esD this method is urriedF st turns out tht doing so helps with type inferene nd llows us to not hve to speify types on the funtionF e n see this working with lst using two di'erent proessing funtionsF

CHAPTER 7.

ARRAYS AND LISTS IN SCALA

IRT

scala> ourFold(lst,0)(_+_) res0: Int = 30 scala> ourFold(lst,"")(_+" "+_) res2: java.lang.String = 7 4 6 3 9 1


he (rst one tkes the sum s we hve seen mny times lredyF his doesn9t relly exerise the ility to hve di'erent types euse everything involved is n sntF he seond exmple though puts tht snts together in tringD e'etively mking use of tht seond typeF here ws nother exmple we sw previously tht ould ene(t from prE metri typesF fk in hpter R we looked t doing funtion ompositionF et the time we only worked with mthemtil funtions nd limited ourselves to the houle typeF fy this point you should see there is lot more to funtions thn numersF e relly should e le to ompose two funtionsD f nd gD s long s the output of funtion g is type tht we n pss into funtion fF o there re three types involved hereD the type pssed into gD the type returned y g nd pssed into fD nd the type returned y fF hnks to prmetri typesD we n write suh funtion in one line of lF

def compose[A,B,C](f:(B)=>A,g:(C)=>B):(C)=>A = (x)=>f(g(x))

7.5.3 Subtyping
o fr we hve tlked out types s if they re ompletely independent nd unreltedF e hve written funtions tht might works with n snt or tring or upleF fy dding prmeters we were le to mke funtions tht ould work with ny typeD ut this still didn9t imply ny reltionship etween the typesF sn relityD lD like most ojetEoriented lngugesD supports subtypingF e type f is subtype of type e if ny ple where we would wnt to use n ojet of type eD we n use n ojet of type f instedF e will go into lot more detil out sutyping when we tlk out inE heritneD ut for now you should e wre of the term euse there will e times when it will ome upF he sutype reltionships in l re shown in the (gure elowF et the top of the (gure there is n ultimte supertype lled enyF ivery ojet in l is n instne of enyF ine ll vlues in l re ojetsD everything is n instne of enyD either diretly or indiretlyF he types like snt nd houle tht we lerned out k in hpter Q re on the left hnd side of the (gure nd they re only sutypes of enyF yn the right hnd side there is nother type lled enyef tht hs unh of unspei(ed types elow itF ell the other types we hve or will tlk out fll somewhere under enyefF et the ottom of the digrm is type lled xothing whih is sutype of ll other types in lF here is no vlue of type xothingF he type exists to mke the type system omplete nd to hndle situtions when funtions don9t returnF e won9t e mking signi(nt expliit use of prmetri funtions nd sutyping until signi(ntly lter in the ook in hpter PHF roweverD these

CHAPTER 7.

ARRAYS AND LISTS IN SCALA

IRU

Any

AnyVal Unit Double Boolean Float Long Int Short Byte Char List

AnyRef

Seq

String

Array Other Classes

Null

Nothing

pigure UFIX higrm of generl sutype reltionships in lF his (gure hs een dpted from similr (gure in Programming in Scala y yderskyD poonD nd ennersF hile erry isn9t tully sutype of eqD it n e used s suh euse of impliit onversionD topi for lter in the ookF

CHAPTER 7.

ARRAYS AND LISTS IN SCALA

IRV

onepts will ome up in impliit wys efore then so you should e wre of their existeneF

7.6 Variable Length Argument Lists


rve you wondered out onstruting vists nd errys with lls like thisc

val lst=List(7,4,6,3,9,1)
here re some detils tht we won9t go intoD ut one spet of this type of ll is something tht we now know enough to tlk outF e re le to pss vrile numer of rguments in this llF sn this se we hve pssed six rgumentsD ut it would work just s well with ny numerF he funtions we hve written n9t do thisF ivery funtion we hve written so fr hs hd n rgument list with spei( numer of vlues in itF o how n we mke it so our funtion will let us pss in vrile numer of rgumentsc sn ftD it isn9t hrd to doF imply dd n sterisk fter the lst type of the lst rgument in the prmeter listF his will llow the ller to pss zero or more of tht typeF e onvenient ple to do this would e n verge funtion like we might use for lulting grdeF uh method might look something like thisF

def average(nums:Double*):Double = ...


he question isD how do we use nums inside of the funtionc es you might guessD this goes into this hpter euse we tret nums just like vist or n erryF ehnillyD it is eqD supertype of othD nd ll of the methods disussed in this hpter re ville on itF hese methods will mke it very esy to write the verge funtionF

def average(nums:Double*):Double = nums.sum/nums.length


ht9s itF xothing more is needed euse we n use sum on sequene of houle vlues nd we n get the length of ny sequeneF ht if we wnt the verge with the minimum vlue droppedc ht doesn9t dd muh omplexity euse there is min method tht we n ll s wellF

def averageDropMin(nums:Double*):Double = (nums.sum-nums.min)/(nums.length-1)


e ould use these long with the fulleve funtion from hpter R to mke revised version of ourseevergeF

def courseAverage(test1:Double,test2:Double,assn1:Double, assn2:Double,assn3:Double,quiz1:Double,quiz2:Double,

CHAPTER 7.

ARRAYS AND LISTS IN SCALA

IRW

quiz3:Double,quiz4:Double):Double = { val aveTest=average(test1,test2) val aveAssn=average(assn1,assn2,assn3) val aveQuiz=averageDropMin(quiz1,quiz2,quiz3,quiz4) fullAve(aveTest,aveAssn,aveQuiz)

his gives us less totl ode thn efore euse we were le to reuse the verge funtionF roweverD now tht we know out lists nd rrysD the wy we ll this method is little it unplesingF e re (xed in the numer of test grdesD ssignment grdesD nd quiz grdesF his would e lot more )exile if we pssed in lists of these di'erent vlues instedF hen the funtion would look more like thisF

def courseAverage(tests:List[Double],assns:List[Double], quizzes:List[Double]):Double = { ... }


nfortuntelyD if you try to write this in the (rst wy tht omes to mind you will (nd tht l doesn9t like itF

def courseAverage(tests:List[Double],assns:List[Double], quizzes:List[Double]):Double = { val aveTest=average(tests) val aveAssn=average(assns) val aveQuiz=averageDropMin(quizzes) fullAve(aveTest,aveAssn,aveQuiz) }
ou will get n error tht looks like thisF

<console>:10: error: type mismatch; found : List[Double] required: Double val aveTest=average(tests) ^ <console>:11: error: type mismatch; found : List[Double] required: Double val aveAssn=average(assns) ^ <console>:12: error: type mismatch; found : List[Double] required: Double val aveQuiz=averageDropMin(quizzes) ^

CHAPTER 7.

ARRAYS AND LISTS IN SCALA

ISH

his is euse visthoule isn9t the sme s houleB s typeF roweverD the two re very similr in prtie nd it seems tht you should e le to quikly nd esily use the lists in ple tht lls for vrile length rgumentF sndeedD you nF ou hve to tell l tht tht is wht you re doingF ou do this with syntx tht is muh like speifying the type of something with olon fter the nme followed y the typeF e don9t use houleB s the type thoughD insted you use B euse l relly doesn9t re out the spei( typeF

def courseAverage(tests:List[Double],assns:List[Double], quizzes:List[Double]):Double = { val aveTest=average(tests:_*) val aveAssn=average(assns:_*) val aveQuiz=averageDropMin(quizzes:_*) fullAve(aveTest,aveAssn,aveQuiz) }
xow we hve funtion tht omputes n verge with lists so it is )exile in the numer of grdes pssed in nd rther simple to ll nd use in lrger progrmF sf you do enough testing on this ode you will (nd there there is ugF ou n mke it produe inorret outputF e leve it s n exerise for the reder to (nd this ugF

7.7 Mutability and Aliasing


sn this hpter we hve seen tht vist is immutle while erry is mutleF st hs een stted tht the funtionl style will tend to use immutle nd tht while mutle dt hs signi(nt ene(ts for some opertionsD it is lso potentilly less sfeF ou might wonder why it is less sfe thoughF efter llD it shouldn9t e too hrd to mke sure tht you don9t mke hnges to n rryF ht is true in smll progrmsD ut it gets hrder nd hrder s the progrms get lrger nd for resons tht you proly don9t fully grsp t this pointF e ig prt of the prolem omes from something lled lisingF his is when two di'erent nmes refer to the sme ojetF o understnd thisD we need to re(ne our view of wht is hppening in the memory of the omputerF gonsider the following vrile delrtionsF

var var var var var

i1=5 d1=5.9 s1="Scala is fun!" l1=List(1,2,3,4) a1=Array(1,2,3,4)

ell of these hve een mde s vrs just to give us the option of ltering them elowF xormlly we would wnt to use vl unless we expliitly found reson why we hd to hnge themF sn this se the reson is just for illustrtionF

CHAPTER 7.

ARRAYS AND LISTS IN SCALA

ISI

i1 d1 s1 l1 a1

5 5.9 Scala is fun! 1,2,3,4 1,2,3,4

pigure UFPX imple imge of memory lyout for few vrilesF he ojets on the right side re overly simpli(edD espeilly the listD ut this portrys su0ient detil for understnding wht is hppening t this pointF he memory lyout looks something like wht is shown in pigure UFPF his is n idelized representtionF sn relity memory is ll liner nd hs struture to it tht will e disussed in ghpter IQF por nowD this view is su0ientF yn the left re oxes tht represent the vrilesF irlier we sid tht you ould piture vriles s oxes tht store vluesF sn l etter piture is to see the vriles s oxes tht store referenes to vluesF sn some situtions l will put the tul vlues in the oxes for the vrilesD ut tht is n optimiztion tht you don9t relly hve ontrol over nd it won9t lter the ehviorF o it is good to piture the memory like thisF ht hppens to this piture if we hnge the vlue of two of the vrilesc por exmpleD sy tht now we exeute these two lines of odeF

i1=8 s1="New string."


he (rst one hnges iI so tht it referenes the vlue VF he seond one hnges the sI so tht it referenes this lternte stringF ht would this look like in memoryc he result is shown in pigure UFQF st S nd the tring l is fun3 hve not een hngedF hey remin in memory just like eforeF feuse nothing referenes themD these ojets will e olleted nd disposed of utomtillyF ht hs hnged is the referenes in iI nd sIF hey now point to new ojets in new hunks of memory tht hold these new vluesF foth the snt nd tring types re immutleF es resultD one the ojets re reted

CHAPTER 7.

ARRAYS AND LISTS IN SCALA

ISP

i1

5 8

d1 s1

5.9 Scala is fun! New string.

l1 a1

1,2,3,4 1,2,3,4

pigure UFQX wodi(ed view of the memory fter two vriles hve een ssigned di'erent vluesF nothing n hnge themF hey don9t llow ny opertions tht would lter their vluesF sf we hd mde these vriles using vl we wouldn9t e le to hnge where the rrows point eitherF sndeedD ll of the types used here re immutle with the exeption of the erryF o erry is the only one where we n hnge the vlue in the ox on the rightF o see how this n mtter we will onsider only the vist nd the erry vriles nd dd two more lines of ode to the pitureF

val l2=l1 val a2=a1


his gives us slightly di'erent piture tht is shown in pigure UFRF xow we hve two di'erent vriles tht point to eh of the list nd rry ojetsF hese seond referenes to the sme ojet re often lled lisesF elising is where mutility strts to use prolemsF sf you hven9t (gured out why yetD perhps this ode will mke it lerF

scala> a2(3)=99 scala> a1 res1: Array[Int] = Array(1, 2, 3, 99)

CHAPTER 7.

ARRAYS AND LISTS IN SCALA

ISQ

l1 l2 a1 a2

1,2,3,4

1,2,3,4

pigure UFRX ht the memory looks like fter the introdution of lP nd PF sn the (rst line we hnge the vlue in the lst slot in PF yn the next line we look t the vlue of IF xote tht it is hngedF e didn9t expliitly do nything with ID ut the vlue is hnged euse P is n lis of IF ou n9t do this with lP euse the list type is immutleF here re times when the ility to mke n lis nd hnge it is gretF here re some tsks for whih this n mke things muh more e0ientF rowE everD if you lose trk of wht is going on nd wht vlues re lises of wht vlues you n run into serious prolemsF

7.8 Basic Argument Passing


xow tht we hve looked t the wy memory is orgnized for vrile delrE tions nd the lising issueD we should tke nother look t wht hppens when you ll funtionF he two re tully very similrF hen you pss vlues into funtionD the funtion hs lol vls with the lol rgument nmesD ut they referene the sme ojets tht the outside vriles referenedF gonsider the following ode from sriptF

def getAndClear(arr:Array[Int],index:Int):Int = { val ret=arr(index) arr(index)=0 ret } val numbers=Array(7,4,9,8,5,3,2,6,1) val place=5 val value=getAndClear(numbers,place) // Other stuff

CHAPTER 7.

ARRAYS AND LISTS IN SCALA

ISR

In top level of script:

numbers place 7,4,9,8,5,3,2,6,1


In getAndClear:

arr index

pigure UFSX he memory lyout from the getendgler sriptF he rguments pssed into the funtion eome lises for the ojets reted t the top level of the sriptF he funtion is pssed n rry of ints nd n index for lotion in tht rryF st is supposed to return the vlue t tht lotion nd lso ler tht lotionF he mening is to store zero t tht lotionF o see how this works look t pigure UFS whih shows the rrngement of memoryF he funtion is de(ned nd the vriles numers nd ple re oth delred nd initilizedF e get new ojets for them to refereneF hen the getendgler funtion is lledD numers nd ple re pssed in to e the vlues of the rguments rr nd indexF hile the ode is in getendglerD rr is n lis for the ojet referred to y numers nd index is n lis for the ojet referred to y pleF his is signi(nt euse the getendgler method hs side e'etF st modi(es one of the vlues stored in the rry tht is pssed to itD when the ode gets down to yther stu'D the memory looks it di'erent s shown in pigure UFTF et tht point the funtion hs (nished so its lol vriles re no longer neededF sn dditionD the 6th element in the rry numers hs een hngedF he funtion mnged to hnge the vlue for the rry s seen outsideF ith nme like getendgler you ould proly (gure out tht this type of side e'et might hppenF roweverD when you pss ny mutle vlue into funtionD you need to e wre tht the funtion ould hnge your vlueD even if you don9t relly wnt it toF

CHAPTER 7.

ARRAYS AND LISTS IN SCALA

ISS

In top level of script after getAndClear:

numbers place value

7,4,9,8,5,0,2,6,1 5 3

pigure UFTX he on(gurtion of memory fter getendgler hs exeutedF row would this e di'erent with listc ellD the list would e immutle so it would e impossile for the funtion to hnge the listF sf you wnted it hngedD the funtion would need to return tuple inluding oth the vlue gotten nd new list with tht vlue hngedF he ode elow shows how tht ould e done with some of the methods we hve introdued in this hpterF

def getAndClear(lst:List[Int],index:Int):(Int,List[Int]) = { (lst(index),lst.zipWithIndex.map( tup => { val (n,i)=tup if(i==index) 0 else n} ) ) }


here is only one expression in this funtionD the tuple to returnF he (rst element in the tuple is lst@indexAF st looks up the proper vlue nd uses the vlue thereF ememer tht looking things up in this wy on list isn9t relly e0ientD ut we hve to do so if given list nd n indexF he seond prt of the tuple is it more omplexF st lled the method zipithsndex on lstF he returns new list where eh element is tuple tht ontins n elements from the list long with the index of tht elementF e hve to do this euse we need the index in order to deide if it is the one to e lered or notF sf we were lering sed on vlue insted of position this wouldn9t e neededF he method mp is immeditely lled on the list of tuples nd it is given funtion literl tht tkes one rgument lled tupD short for tupleF his funtion literl uses urly res nd hs two linesF he (rst line is vl tht pulls the two prts out of the tupleF he numer from the list is lled n nd the index is lled iF he funtion literl (nished with n if expression tht heks the index nd gives the vlue of H or n sed on if i is the sme s indexF here re other wys to write thisF yne tht ould e more e0ient when the index is smll ompred to the length of the list is shown hereF

CHAPTER 7.

ARRAYS AND LISTS IN SCALA

IST

def getAndClear2(lst:List[Int],index:Int):(Int,List[Int]) = { (lst(index),lst.take(index):::(0::lst.drop(index+1))) }


his version uses the ons opertorD XXD whih we sw eforeF st dds one new element to the front of list nd gives k tht listF st lso uses n opertor tht we hven9t seen previouslyD the XXX opertorF his does roughly the sme thing s ons exept tht the rgument on the left is full list tht should e ppended to the front of the seond listF yf ourseD euse the list version is hving to reuild the listD it ould go step further nd truly ler the vlueF st ould remove it from the list insted of overwriting it with zeroF his would e done with (lter insted of mp on the (rst versionF he seond version is even esier to hngeF e leve tht s n exerise for the reder to rete nd tryF en interesting question now eomes whih of these is etterc st is etter to use n rry whih n e mutted or list whih n9tc he nswer is tht it depends on whether you wnt funtion to e le to mutte the dtF sf the funtion is supposed to mutte the dt then there n e speed ene(t to pssing something mutleF roweverD if you don9t wnt the dt mutted then there is prolem with pssing mutle dtF hen you pss mutle dt into funtionD you hve no ontrol over whether it is muttedF sn situtions where you don9t wnt your dt muttedD this requires tht you mke defensive copyF o protet your version of the dtD you mke opy of it nd pss the opy into the funtionF por this resonD the question of whether you wnt to use mutle or imE mutle struture depends lot on the wy in whih you use tht dtF sf it is going to e mutted frequently then it might mke sense for it to e mutleF roweverD if it isn9t going to e mutted frequently then immutle likely mkes sense so you don9t hve to mke defensive opiesF iven in situtions where there might e fir it of muttionD you need to onsider how muh defensive oping will e needed if you hoose mutleF

7.9 Pass-By-Name
irlier we looked t the wy in whih rguments re pssed in lF his is style lled pass-by-valueF he funtion gets opy of wht the vrile ws in the lling odeF he funtion n9t hnge tht vrileD it n only hnge wht it refers to if wht it refers to is mutleF ome lnguges provide n lternte wy of pssing things lled pass-by-referenceF hen something is pssed y refereneD the funtion hve the ility to hnge the vrile in the lling funtion itselfF he ft tht ll vriles in l silly re referenes lurs the line etween the twoD ut fundmentlly l only llows pssEyEvlue nd the funtion n only modify things seen to the outside if the vrile refers to mutle ojetF

CHAPTER 7.

ARRAYS AND LISTS IN SCALA

ISU

hile l does not provide true pssEyErefereneD it does provide pssing style tht few other lnguges provideD pass-by-nameF he ide of pssE yEnme is tht the rgument is pssed not s vlueD ut s thunk tht is silly set of ode tht will e exeuted nd give vlue when the prmeter is used in the funtionF ou n imgine pss y nme s utomtilly reting funtion tht tkes no rgument nd returns vlue tht will e exeuted eh time the rgument is usedF o help you understnd this nd see the syntxD we will give simple exmpleF e will strt mking si inrement funtion in the wy we re used to doingF

scala> def incr(n:Int):Int = { | println("About to increment.") | n+1 | } incr: (n: Int)Int


he print sttement is just to help us keep trk of wht is hppening whenF xow we will write the sme funtion ginD ut this time pss the rgument y nme instedF

scala> def incrByName(n : =>Int):Int = { | println(About to increment.) | n+1 | } incrByName: (n: => Int)Int
he syntx for pssing n rgument y nme is to put nd equls rrow efore the type of the rgumentF his is the sme rrow used in funtion literlsF sf we were to put empty prentheses in front of it to get @Aab we would hve the type of funtion tht tkes no rguments nd returns n sntF he yEnme rgument is muh the sme only when you ll the funtion you don9t hve to expliitly mke funtionF o strt o'D we9ll ll this funtion in the simplest wy we possily ouldF

scala> incr(5) About to increment. res0: Int = 6 scala> incrByName(5) About to increment. res1: Int = 6
xo surprises hereF hey pper to oth do the sme thingF foth print the sttement nd give us k TF roweverD the two ren9t relly doing the sme thingF o mke tht lerD we will ll them gin nd hve the rgument e lok tht inludes printF

scala> incr({println("Eval"); 5})

CHAPTER 7.

ARRAYS AND LISTS IN SCALA

ISV

Eval About to increment. res2: Int = 6 scala> incrByName({println("Eval"); 5}) About to increment. Eval res3: Int = 6
xow it is ler tht they ren9t doing the sme thingF hen you pss n rgument y vlueD it is evluted efore the funtion strts so tht you n hve the vlue to pss throughF hen you pss y nmeD the evlution hppens when the prmeter is usedF ht is why the line ivl printed out fter eout to inrementF in the seond seF he println in the funtion hppens efore the vlue of n is ever essedF sing pssEyEnme gives you the ility to do some rther interesting things when muttions of vlues omes into plyF o see thtD we n write slightly di'erent funtionF

scala> def thriceMultiplied(n : => Int):Int = n*n*n thriceMultiplied: (n: => Int)Int
st might seem tht this method should e lled uedD ut s we will seeD this might not lwys pply for it euse it uses pss y nmeF o strt withD let9s ll it with n expression tht gives simple vlueD ut prints something (rstF

scala> thriceMultiplied({println("Get value."); 5}) Get value. Get value. Get value. res4: Int = 125
xote tht the print sttement hppened three timesF his is euse the vlue n ws used three times in the funtionF rd the prmeter not een pssed y nmeD tht would not hve hppenedF st would hve printed oneD when the funtion ws lledF ry this for yourselfF his prtiulr ll still gve us vlid ue thoughF o why wsn9t the funtion simple lled uec he reson is tht if the ode in the rgument does the right thingD the result won9t e ueF rere is n exmpleF

scala> var i=5 i: Int = 5 scala> thriceMultiplied({i+=1; i}) res5: Int = 336
QQT is not perfet ueF o how did we get this vluec sn this exmple we introdued vrF he ode in the pssEyEnme rgument lters this vrF es resultD every time tht n is usedD the vlue given y n is di'erentF he (rst

CHAPTER 7.

ARRAYS AND LISTS IN SCALA

ISW

time we use n the vlue is T euse the originl S ws inremented nd then returnedF he next time it is U euse the T tht i ws set to the previous time is inremented ginF he lst time it is VF o the nswer is TBUBVaQQTF hese lls with oth prentheses nd urly res might seem oddF he retors of l thought soF es resultD they mde it so tht if funtion or method tkes n rgument list with only one vlue in itD tht vlue n e in urly res insted of prenthesesF his llows shorter syntx for the ll tht looks like thisF

scala> thriceMultiplied {i+=1; i} res6: Int = 990


ou might e tempted to think tht leving o' the prentheses hnged wht hppened euse the result is di'erentF st wsn9t the prentheses thoughF ememer tht fter the lst ll i hd een inremented up to VF o this time the result ws WBIHBIIaWWHF

7.10 Fill and Tabulate


yne of the resons for introduing pss y nme in this hpter is tht there re some other wys to mke rrys nd listsF yne of them uses pss y nmeF reviously we sw how we ould follow erry or vist with list in prentheses to get k either n rry or list with those vlues in itF e ould lso use new to get lrge rry of defult vlues or XX to put together listsF here re lso methods we n ll on erry nd vist lled (ll nd tulteF foth n e used to mke new erry or vistF hey oth work well for mking lrge errys nd vistsD unlike the version where you hve to speify the individul vluesF vet9s look t how these workF he (ll method is urried method tht tkes (rst rgument speifying how mny elements to mke nd seond rgument whih is pssEyEnme rgument giving the vlueF he simplest invotion of this might look like the followingF

scala> Array.fill(10)(4) res3: Array[Int] = Array(4, 4, 4, 4, 4, 4, 4, 4, 4, 4) scala> List.fill(6)(23) res4: List[Int] = List(23, 23, 23, 23, 23, 23) scala> List.fill(6)("hi") res5: List[java.lang.String] = List(hi, hi, hi, hi, hi, hi)
sf the seond rgument is onstntD then the ll simply (lls the whole rry or list with tht vlueF roweverD tht rgument is pssed y nme so it is tully reEevluted for eh element of the sequene nd if it hs side e'etsD they will hppen multiple timesF he esiest wy to see this is to hve the seond rgument print somethingF

CHAPTER 7.

ARRAYS AND LISTS IN SCALA

ITH

scala> Array.fill(4){ println("Evaluating argument"); 5 } Evaluating argument Evaluating argument Evaluating argument Evaluating argument res6: Array[Int] = Array(5, 5, 5, 5)
xote tht here the seond rgument hs een put in urly res onlyF eE memer tht l llows you to do tht for n rgument list tht only hs one rgumentF ou n dd n extr set of prenthesesD ut you will still need the urly res euse this is lok of ode with two expressions in itF his exE mple is illustrtiveD ut not relly ll tht usefulF e more interesting exmple involves using vrF

scala> var i=1 i: Int = 1 scala> List.fill(5){ i*=2; i } res7: List[Int] = List(2, 4, 8, 16, 32)
rere the vr i is initilized to e IF he vlue rgument multiplies i y P nd stores tht vlue k in iF hen it gives k i s the vlue to useF ou n see in the output tht this gives us powers of PF hile there re situtions where this n e helpfulD this method of (lling n rry with powers of two is likely to onfuse most people reding your odeF en even more useful exmple is to hve the vlue rgument red inputF

scala> Array.fill(5){ readInt() } res8: Array[Int] = Array(6, 4, 8, 2, 3)


his is wht we strted o' the hpter doingD writing funtions to red vlues into n rry or listF st turns out tht s long s we know how mny elements we wntD we n do this with single line of ode thnks to (ll nd pssEyEnmeF st is often helpfulD when lulting vlues for n rry or listD to know the index of the vlue you re lulting forF he (ll method doesn9t do this for us y defultF e ould use vr to keep trk of thtD in mnner similr to wht we did oveD ut this is pinF ht is why the tulte method existsF ou ll tulte muh like you do (llD only the seond rgument isn9t pssEyEnme vrileD it is funtion tht tkes n snt nd returns the type the sequene should e (lled withF o if you wnt to (ll n rry with the result of evluting polynomil on the index you ould do the followingF

scala> Array.tabulate(6)(x => 3*x*x+5*x-7) res9: Array[Int] = Array(-7, 1, 15, 35, 61, 93)
his (lls the rry with vlues of 3x2 + 5x 7 where x is the index in the rryF

CHAPTER 7.

ARRAYS AND LISTS IN SCALA

ITI

7.11 Complete Grades Script/Software Development


sn hpter R we spent some time writing funtions to lulte verges in lssF e now hve the ility to put together everything tht we hve lerned nd write sript tht will keep trk of the grdes for single student nd e le to lulte tht student9s vergeF his ould e extended to multiple studentsD ut we won9t do tht hereF hen we solve lrge prolem there re ertin steps tht muh e tkenF he (rst is to get ler desription of wht prolem you re solvingF his step is lled nlysisF he nlysis step doesn9t involve ny oding or even thinking out odingF e just wnt desription tht hs enough detil tht we know wht it is we re supposed to reteF yne we hve tht we n move on to the designF sn the design step we (gure out how we re going to go out solving the prolem desried in the nlysisF he design step doesn9t involve oding eitherD ut it spei(es wht we will do when we get to the odingF he design phse is where we do our prolem deompositionF e think out how to rek the prolem down nd wht piees we will need to put together to get singleD whole solution to the prolemF efter we hve design we get to implementtionF his is where we will tully write the progrmF sdellyD y the time tht we get to implementtion we hve worked out most of the prolemsF he ility to see the prolems we will enounter requires lot of experieneF es novie progrmmersD you should try to spend time on designD thinking out how to rek the prolem downD ut don9t eome so intent on hving omplete design tht you stll out nd never get to implementtionF efter you hve n implementtion you hve to mke sure it works nd (x ny prolemsF his is lled the testing nd deugging phse euse it is where you test the ode to (nd ll the ugs (x themF por rel softwreD fter ll the ugs re (xed nd the softwre hs een rolled outD you worry out mintenneF his is where you ontinue to mke ltertions to the softwre to improve it or ddress ustomer requestsF et the level you re t nowD you typilly don9t do muh nlysis or minE tenneF ou don9t do nlysis euse generlly your instrutor or this ook will give you firly omplete desription of wht you re doingF ou don9t do mintenne euse you don9t hve ustomer se tht is using the softwreF e little of eh of these n still reep into your work when you mke sure you fully understnd the desription of prolem nd then perhps if you re given lter prolem tht inorportes ode you hd done previouslyF ou should spend signi(nt mount of time working on design nd deugE gingF sn ftD the implementtion phse is often the shortest phse of softwre design1 F sf done properlyD most of the thinking goes into the design phse so
1 At
least if you do things properly the implementation will be short. I like to tell my students that hours of coding can save minutes of thinking. The point of this is that if you don't sit and think about design before you go to the keyboard and write code you are likely to spend hours hashing out the design that you could have nailed down in a few minutes by

CHAPTER 7.

ARRAYS AND LISTS IN SCALA

ITP

implementtion is simply typing in wht you hd designedF esting nd deE ugging is extremely vrile in timeF st is possile to write your progrm nd hve everything work perfetly the (rst timeF ht gets less likely s progrms get longer nd is espeilly rre for novie progrmmersD though the stti type heking in l will help to mke it so tht if everything in your progrm heks out it hs etter hne of workingF hen things don9t workD deugE ging n tke ritrrily long periods of time nd is often the longest phse of softwre developmentF sn rel softwre development these di'erent phses ren9t lwys so distint nd they re rrely done in nie len sequentil orderF st is ommon tht in one phse of development you relize something tht ws missed in n erlier phseF ome pprohes to softwre development mix the phses together so tht the developer is involved in more thn one t ny given timeF sf you ontinue on in gomputer ieneD these topis should e overed in full detil in ourse on oftwre ingineeringF et this point we hve very vgue desription of the prolem tht we re going to solveF por tht resonD we need to do some nlysis up front so tht we hve ler desription of extly wht we re going to solveF his sript is going to use text menu to give the user optionsF he options will inlude the ility to dd grdes of di'erent types s well s n option to print the urrent grdes nd vergeF ypes of grdes re testsD quizzesD nd ssignmentF por the (nl vergeD the tests nd ssignments ount RH7 eh nd the quizzes mke up the remining PH7F he lowest quiz grde should e droppedF he menu will hve numers y eh option nd users enter numer to selet tht optionF ht is proly su0ient nlysis for our needs hereF e n strt working on the design nd if we hit nything we hve questions onD we n go k nd dd some detil to the nlysis efore we proeed further with the designF o how re we going to rek this prolem downc et the top level we hve ode tht repets over nd over nd eh time menu is printedD the user selets n optionD nd we exeute ode to perform the seleted optionF he only wy we urrently know how to do something repetedly n unspei(ed numer of times is with reursive funtionF o we will need reursive funtion tht ontins ll this other funtionlityF ht funtion will ll itself until we hit the ondition where it exitsF here is nturl deomposition t this pointF rinting the menu is nie funtionF e hve lredy seen tht we n write nie funtions for tking verges or verges dropping the minimum grde s well s one to lulte the (nl vergeF o tht reks down the funtionlityF sf you were to run to the keyord now nd strt typing you would quikly relize tht something signi(nt ws left out of the designD how we re storing the grdesF here re mny wys tht we ould do thisD ut given tht our only funtionlity is to dd grdes nd lulte vergesD the solution is firly lerF yur only rel options re rrys nd lists t this pointF errys hve (xed size whih is less thn idel
thinking about it to begin with.

CHAPTER 7.

ARRAYS AND LISTS IN SCALA

ITQ

for this pplition euse we will e dding grdes nd hven9t spei(ed how mny there n eF o lists mke more senseF e n use three lists tht store the three di'erent types of grdesF sf we do this in n impertive styleD the lists will e delred with vr efore the min funtionF sf we use funtionl styleD they will e pssed into the next ll for the itertionF e will look t oth to illustrte the di'erenesF wost of the funtions won9t e ltered y this distintionF ht gives us deent design for this little pplitionF xow we turn to the implementtionF e will reuse the ourse verge funtion from setion UFT nd the funtions tht it lls for nowF e need new funtions for our min reursive funtion nd printing the menuF e9ll strt with n impertive version of the min funtion nd look t funtionl dpttion fterwrdF

def printMenu { println("""Select one of the following options: 1. Add a test grade. 2. Add a quiz grade. 3. Add an assignment grade. 4. Calculate average. 5. Quit.""") } var tests = List[Double]() var quizzes = List[Double]() var assignments = List[Double]() def mainGrades { printMenu readInt() match { case 1 => println("Enter a test grade.") tests = readDouble() :: tests case 2 => println("Enter a quiz grade.") quizzes = readDouble() :: quizzes case 3 => println("Enter an assignment grade.") assignments = readDouble() :: assignments case 4 => println("The average is "+courseAverage(tests,assignments,quizzes)) case 5 => return case _ => println("Unknown option. Try again.") } mainGrades }
his egins with the printwenu funtion whih simply prints menuF he only

CHAPTER 7.

ARRAYS AND LISTS IN SCALA

ITR

thing of interest here is the use of the triple quote string so tht the string n e mde to spn multiple linesF sf you don9t do thisD you will hve to use n to denote line reksF sn this impertive versionD the printwenu funtion is followed y the delE rtion of three vrilesF hey re ll vrs nd they re of the type visthouleF he hve to e vrs euse the vist itself is immutleF o whenever someE thing is dded we hve to hnge the vrile referene nd point to new vistF ememerD this n e done e0iently for the vist type so tht is (neF sf you type this ode in nd ply with it itD you will proly (nd tht you n mke it ehve poorlyF sn prtiulrD you n get it so tht when you sk for the verge you get n output like thisF

The average is NaN


his should led you to two questionsF pirstD wht is this thing lled xxc eondD wht is using thisc ehnilly the seond mtters more euse we need to know tht to (x itF roweverD knowing the nswer to the (rst n help you (gure it out if you weren9t le to do so from your testingF he houle typeD s we hve disussed previouslyD is used to represent numeri vlues tht hve frtionl prtsF st hs rther lrge rnge nd good preisionD ut it is tehnilly (xed preision typeF ou n9t represent ny rel numer with itF sn dditionD some mthemtil opertions produe results tht ren9t well de(nedF gonsider the followingF

scala> 1.0/0.0 res2: Double = Infinity scala> -1.0/0.0 res3: Double = -Infinity
ou should hve lerned in mth lss tht you n9t divide y zeroF sf you do this with snts you get n errorF roweverD if you do it with houles you get wht you see hereF eny opertion tht goes outside the rnge of the doule will lso get you either sn(nity or Esn(nityD depending on whih side of the rnge it goes out on s is shown hereF

scala> 1e150*1e200 res6: Double = Infinity


ht does ll of this hve to do with xxc ellD xx stnd for xotEExumer nd it is the result of n opertion when it isn9t ler wht the result should eF yne wy to get this is to dd sn(nity nd Esn(nity or do other opertions with sn(nity or Esn(nity tht the omputer n9t know the result ofF gonsider this exmpleF

scala> 1e150*1e200-1.0/0.0 res10: Double = NaN

CHAPTER 7.

ARRAYS AND LISTS IN SCALA

ITS

sn generl the omputer n9t know if this would e out of rnge on the positive or negtive so it goes to xx euse it gives upF here is one other wy to get xxX divide zero y zeroF

scala> 0.0/0.0 res11: Double = NaN


his is wht is hppening to use our errorD nd it hppens when zero test or ssignment grdes or only one quiz grde hs een enteredF sf we hve no test or ssignment grdeD the norml verge will return HFHGHD s the sum is the houle HFH nd the length is the snt HF sf the list of quiz grdes only hs one elementD then tht one is the minimumF o the funtion returns @xE xAG@IEIA where x is the one grde s houleF glerly tht is going to e xxF o how do we (x thisc e need to mke the verge nd the vergehropwin funtions it smrter so tht they hve speil ses in the instnes when they shouldn9t do divisionF e n do this y putting if expressions in othF

def average(nums:Double*):Double = if(nums.isEmpty) 0 else nums.sum/nums.length def averageDropMin(nums:Double*):Double = if(nums.isEmpty || nums.tail.isEmpty) 0 else (nums.sum-nums.min)/(nums.length-1)
sf you use these versions of the funtions things should work wellF xow to the funtionl lterntiveF he impertive version uses three vr delrtions outside of the funtionF hese delrtions n e seen y nything in the sript tht follows themF e typilly refer to this s the glol sopeF por smll sripts this might not e prolemD ut you don9t wnt to get into the hit of mking things glolF enything tht is glol in lrge progrm n e messed up y ny line of odeD mking it very hrd to trk down ertin types of errorsF st is etter to hve our vriles delred in lol sopeD inside of funtionF sf we simply delre the vriles inside of minqrdesD it won9t work eE use when you mke reursive llD you get new versions of ll of the lol vrilesF snstedD we wnt to pss the three lists into the funtion s rgumentF he rguments to funtion t just like lol vl delrtions exept tht the vlue is provided y the lling odeF his new version will not inlude ny vr delrtionsD nor will it hve ny mutle vlues s everything is stored in immutle listsF o other thn the printingD it is ompletely funtionlF rere is wht suh funtion might look likeF

def mainGrades(tests:List[Double],assignments:List[Double], quizzes:List[Double]) { printMenu readInt() match { case 1 =>

CHAPTER 7.

ARRAYS AND LISTS IN SCALA

ITT

println("Enter a test grade.") mainGrades(readDouble() :: tests,assignments,quizzes) case 2 => println("Enter a quiz grade.") mainGrades(tests,assignments,readDouble() :: quizzes) case 3 => println("Enter an assignment grade.") mainGrades(tests,readDouble() :: assignments,quizzes) case 4 => println("The average is "+courseAverage(tests,assignments,quizzes)) mainGrades(tests,assignments,quizzes) case 5 => return case _ => println("Unknown option. Try again.") mainGrades(tests,assignments,quizzes)

snsted of mutting vluesD this version psses the newly uilt list into the reursive ll where it is ompletely new rgument vlue for the next level down in the reursionF he options tht don9t hnge the lists simply pss through the sme vluesF

Self-Directed Study
inter the following sttements into the iv nd see wht they doF ry some vritions to mke sure you understnd wht is going onF

scala> scala> scala>


333 everything

Exercises
IF hink of s mny wys s you n to mke n errysnt tht hs the vlues IEIH in itF rite them ll to test tht they workF he (rst two should e esyF sf you work you n get t lest three others knowing wht hs een overed so frF PF hink of s mny wys s you n to mke vistsnt tht hs the vlues IEIH in itF rite them ll to test tht they workF he (rst two should e esyF sf you work you n get t lest three others knowing wht hs een overed so frF

CHAPTER 7.

ARRAYS AND LISTS IN SCALA

ITU

QF wke vistghr tht ontins 99E9z9 without typing in ll the hrtersF @se toghr to mke this workFA RF se some of the si methods on listGrry 333 SF rite severl versions of ode tht will tke n errysnt nd return the numer of even vlues in the rryF ih one will use di'erent tehniqueF o test this on lrger rry you n mke one using erE ryF(ll@IHHA@utilFndomFnextsnt@IHHAA @A se reursive funtionF @A se the ount higherEorder methodF @A se the (lter higherEorder method in onjuntion with regulr methodF @dA se the mp higherEorder method in onjuntion with regulr methodF TF ou n tret tring s sequene of ghr nd use ll the methods tht we introdued here for vist nd erry on itF sing thtD wht ode would you use to do the followingc por ll of these ssume tht str is tring provided y the user through redvine@AF @A qet version of the string with ll the spes removedF @A qet version of the string with ll vowels removedF @A plit o' the (rst word of the tringF rite ode tht gives you @tringD tringA where the (rst element is the (rst word in str nd the seond one is everything elseF @dA gonvert to sequene tht hs the integer vlues of eh of the hrters in strF @eA rite ode tht will tke sequene of sntD like the one you just mkeD nd give you k tringF @xote tht if you get sequene of ghr you n use mktring to get simple tring from itFA

Projects
IF e n express generl polynomil s

An xn + An1 xn1 + An2 xn2 + ... + A2 x2 + A1 x + A0


where the A vlues re the oe0ients on di'erent termsF ou n view sequene of houles s polynomil y sying tht the vlue t index n is the vlue of An F sing this representtionD erry@IFHDHFHDPFHA would represent 2x2 + 1F xote tht the order when you look t the rry is the opposite of the order seen in the polynomilF

CHAPTER 7.

ARRAYS AND LISTS IN SCALA

ITV

sing this representtion of polynomilD write funtions tht do ddition nd sutrtion of two polynomils using rrysF ou n ssume tht the rrys pssed in re the sme lengthF elso write funtions tht gives you the derivtive of polynomil nd the ntiderivtive2 F xote tht the ntiderivtive funtion will need nd extr rgument for the vlue of the onstnt termF o help you lernD try to write these funtions using oth reursion with n index nd using stndrd methods on sequenesF por the former option try doing it with lists s well nd using XX to uild the lists in the reursionF por the ltter hint when you do dd nd sutrt is to onsider using the zip methodF sf you wnt n extr hllengeD try writing multiplition s wellF his is signi(ntly hrder prolemD ut if you n do it with oth reursion nd the uilt in methods you should feel good out your understndingF PF his projet hs you implement simple form of enryption nd derypE tionF ou should write t lest two funtions lled enrypt nd deryptF he form of enryption we re using is o'set enryption where you simply o'set letters in the lphetF sf you pik n o'set of ID then if there is n 99 in the originl messgeD the enrypted messge will hve 99F por (rst utD write these funtions so they just dd or sutrt spei(ed o'E set to ll hrtersF @xote tht when you do rithmeti on ghr you get n sntF se the toghr method to get k tht typeF o @99CIAFtoghr will give you 99FA our methods will oth tke tring nd n snt nd return tringF he snt pssed in is the o'set to pply to the hrtersF his pproh is esyD ut it produes nonEletters in ertin situtions like when you do n o'set on 9z9F e(ne your funtions so tht the skip nything tht isn9t letter nd wrps round so tht if the o'set goes ove z it omes k to F ou hve to hndle pitl letters s wellF @xote tht the ghr type hs methods lled isvetterD ispperD nd isE vower tht n help you with thisF ou n lso do omprisons nd mth with the ghr typeFA sf you wnt n extr hllenge nd you wnt to mke it hrder for someone to try to rek your odeD revise your methods so tht they tke n extr snt nd insert rndom hrters t intervls of tht spingF o if the vlue is SD you will insert n extr rndom hrter etween every (fth hrter from the messgeF ou n generte rndom letter hrter with the expression @99CutilFndomFnextsnt@PTAAFtoghrF
2 You
might recognize this better as an indenite integral.

CHAPTER 7.

ARRAYS AND LISTS IN SCALA

ITW

por this whole prolem rememer tht you n tret trings s sequenesF o you n use them like n erryghr exept tht they re not mutleF QF por this projet you will e doing some simple dt nlysisF sf you go to httpXGGwwwFsFtrinityFeduG~mlewisGlfookGghpterUGdtFtxt you will (nd text (le tht hs vlues in itF st is wether dt for PGIUGPHIH in n entonioD from the ether ndergroundF st hs one line for eh hour nd eh line hs single doule tht it the temperture for tht hourF rite funtion tht will red this into n erryhoule using rediretion nd redhouleF hen write funtions to lulte the followE ingX stndrd devition nd hnge per hourF he stndrd devition will return houleF he hnge will return n erryhoule tht is one shorter thn the originl dt setF RF his projet is to e uilt on top of projet TFQF por this one you mke funtions tht will tke vist or erry of the vlues used to represent spheres nd plnes nd return the impt prmeter of the (rst one the ry hits nd the informtion on tht geometryF SF por this projetD you will write funtion tht ould help people plyE ing rleF ou will wnt to rek this down so you hve multiple funtions in the endD ut the lst one is wht relly mttersF sf you go to httpXGGwwwFsFtrinityFeduG~mlewisGlfookGordsGPofIPFtxt there is (le with list of RIPQV inglish wordsF here is one word per lineF sing input rediretion nd redvine you will red the ontents of this (le into n errytringF yne you hve this (le red inD your gol is to give k words tht the person ould likely mke using letters heGshe hs to plyF our end gol is funtion tht tkes the list of words nd tring of the letters the person hs to ply whih returns ll the words tht n e mde from their letters plus one other letterF he one other letter is something you don9t know tht should hve een plyed somewhere on the ordF por our purposes here we don9t re wht it isF ou should give k ny word tht n e formed with some suset of the plyer9s letters plus one extrF o do this you relly wnt to use funtions to rek the prolem downF gonsider wht higher order methods ould e helpful nd wht types of funtions you need to use with themF o mke this ll work with input rediretion downlod nd edit the PofIPFtxt (le nd insert top line where you put the letters the plyer hs in rleF he sript will red tht line to get the letters nd then red the proper numer of lines to get ll the wordsF vstlyD to help you solve this prolem onsider using the di' methodF his method tells you the di'erene etween two sequenesF ly round

CHAPTER 7.

ARRAYS AND LISTS IN SCALA

IUH

with lling di' using di'erent strings to see wht it doesF trt with Fdi'@deA nd deFdi'@AF

Chapter 8

Loops
e sw in hpter T how we ould use reursion to produe n itertive ehvior where something ws done multiple timesF e lso sw in hpter U tht we n use olletions to mke ertin opertions hppen multiple timesF hese pprohes re the primry methods used in funtionl lnguges nd they ofE ten work well to provide the funtionlity we need in lF wost lngugesD inluding lD provide other onstruts lled loops tht re designed spei(E lly for reting this itertive ehviorF sn this hpter we will explore the loop strutures present in l nd see how we n use these in our progrmsF e will strt y repeting some of the things tht we did previously using reursionF

8.1 while Loop


he most si looping onstrut in l nd mny other lnguges is the while loopF he nme tells you roughly wht it doesF ou should keep repeting something while some ondition is trueF he syntx of the while loop is s followsF

while(condition ) statement
he ondition n e ny expression tht evlutes to foolen typeF he sttement is very ommonly lok of odeD so you will typilly see the while followed y urly resF o see n exmple of thisD let9s use while loop in funtion tht uilds list of numers input y the userF he list will end when the user enters quitF his is extly like the exmple tht we did with reursionF e ouldn9t do it with the olletions euse we didn9t know in dvne how mny numers there would eF

def readInts:List[Int] = { var lst=List[Int]() var input=readLine()


IUI

CHAPTER 8.

LOOPS

IUP

while(input!="quit") { lst=input.toInt :: lst input=readLine() } lst

his ode is distintly impertiveF e hve to delre two vriles with vr to mke it workF sn ftD the while loop nd it9s prtnerD the doEwhile loop tht we will disuss in the next setionD re sttements onlyF hey re not expressions nd n not e used in ples tht need to hve vlueF he ft tht the while loop hs to e used in n impertive wy is somewht impliit in the wy it worksF por the ode inside of the while loop to exeuteD the ondition must e true originllyF sn order for the loop to (nishD the vlue of the ondition hs to hnge to flseF his hnge requires the muttion of dt t some point so it is impossile to use the while loop in ompletely funtionl wyF enother thing to note out the while loop is tht it is preEhek loopF his mens tht the ondition is heked efore the ody of the loop is exeutedF es resultD it is possile tht the ontents of the loop will never exeuteF sf the ondition is flse when the loop is (rst rehedD the ody of the loop will never exeuteF vet9s look t nother exmple of the while loopF yne of our (rst exmples of using reursion to get itertion ws the ftorilF e n reEwrite ftoril using while loop in the following wyF

def factorial(n:Int):Int = { var product=1 var i=1 while(i<=n) { product*=i i+=1 } product }
e delre two vriles nmed produt nd i t the eginning nd initilize oth to the vlue of IF he ondition on the while loop uses it to iterte s long s i is less thn or equl to nF snside the loopD the vlue produt is multiplied y i nd i is inremented y oneF he Ba nd Ca opertors re exmples of ssignment opertorsF hey proE vide hndy shorthnd for when you wnt to pply mthemtil opertion to vlue nd store the result k in the originl vrileF ou n follow ny opertor y n equl sign nd l will see it s ompound opertion tht performs the spei(ed opertor nd stores the vlue kF he storing of the vlue is muttion opertionF es suhD these opertors hve to e used with mutle dtF ht either requires vr delrtionsD or mutle onstruts suh s rrysF

CHAPTER 8.

LOOPS

IUQ

his funtion lso shows nother element tht is ommon to most while loops nd whih n led to ommon form of ugsF he line iCaI is wht we often ll the itertor of the loopF st is wht moves us from one se to the next in the loopF he ommon ug is to identlly leve out the itertorF gonsider wht hppens in this ode if you do thtF ithout the line iaiCID the vlue of i will never hngeF es resultD the ondition will never hnge either nd if it is true to egin withD it will e true foreverF his leds to wht we ll n in(nite loopD loop tht never exitsF his type of error is esy to put into the ode with while loopD euse the loop doesn9t inlude nything in its struture to remind you to inlude the itertorF

8.2 do-while Loop


l provides seond onstrut tht is very losely relted to the while loopF st is the doEwhile loopF he syntx for the dEwhile loop is s followsF

do { statements } while(condition )
he urly res ren9t tehnilly required here eitherD ut it is rre to see doEwhile loop without themF eginD the sttement does very muh wht it sys tht it doesF st will do the sttements while the ondition is trueF qiven how very similr this sounds to the norml while loopD you might wonder wht the di'erene isF he di'erene is implied y the lyoutF he norml while loop heks the ondition efore it exeutes the sttements in the ody of the loopF he doEwhile loop heks the ondition fter it exeutes the ody of the loopF es resultD the ody of doEwhile loop will lwys exeute t lest oneF he doEwhile loop isn9t used tht often in progrmmingF he only times it is used re in situtions where the postEhek nture of the loop is helpful nd you wnt the ontents of the loop to lwys hppen oneF e ommon exmple of this is in menu sed pplitions where you need to red wht the user wnts to do nd then t on itF he deision of whether or not the loop should e exeuted gin is sed on wht option the user piksF he minqrdes funtion from the end of the lst hpter ws n exmple of thisF sn tht hpter we wrote the progrm using reursion euse tht ws the only method we knew for mking the progrm exeute the sme ode repetedlyF his funtion n e onverted over to use doEwhile loop nd the result might look like the followingF

def mainGrades { var tests=List[Double]() var assignments=List[Double]() var quizzes=List[Double]() var option=0

CHAPTER 8.

LOOPS

IUR

do {

printMenu option=readInt() option match { case 1 => println("Enter a test grade.") tests ::= readDouble() case 2 => println("Enter a quiz grade.") quizzes ::= readDouble() case 3 => println("Enter an assignment grade.") assignments ::= readDouble() case 4 => println("The average is "+ courseAverage(tests,assignments,quizzes)) case 5 => case _ => println("Unknown option. Try again.") } } while(option!=5)

hether you use this or the ode in setion UFII is primrily question of styleF wost developers would proly write this version y defultD ut tht is minly euse most developers hve kground in impertive progrmming nd will tend to fvor tht pproh for resons of fmilirityF

8.3 for Loop


he while loop is the simplest loopD ut it isn9t the most ommonly used loop in most lngugesF sn lnguges tht provide for loopD it is typilly the most ommonly used loopF he for loop in l is it di'erent from tht provided in other lngugesD ut you will proly (nd tht it is the one tht you turn to the most when you re putting itertion into your odeF sn most lngugesD the nturl usge of the for loop is to ount so we9ll strt with thtF e for loop tht ounts from I to IH nd prints out the vlues would e written s follows in lF

for(i <- 1 to 10) { println(i) }


he nme i is vrile nme for lF es suhD you n ll it whtever you wntF por ounting loops it is very ommon to use nmes suh s iD jD nd kF roweverD nything will work nd s with other vrile nmesD it is etter if

CHAPTER 8.

LOOPS

IUS

your hoie ommunites something to those reding the ode to mke it esier for them to understndF efter the vrile nme is n rrow pointing to the left mde from less thn nd hyphen or minus signF ou will see this in ll of your for loops in lF efter tht is nie expression tht you should e le to redF e9ll tlk more out extly wht tht mens shortlyF ou n red this for loop s something like for i pulled from I to IHF he left pointing rrow n e niely volized s pulling elements from the thing on the right nd putting them into the thing on the leftF es we sw in hpter UD the indexes in olletions in l don9t strt ounting t oneF snstedD they strt ounting t zeroF es suhD you often wouldn9t ount from I to IHF snstedD we would normlly ount from H up to WF his ould e expressed in l y repling I to IH with H to WF roweverD it is very ommon tht you wnt to strt t zero nd express the numer of elements you wnt to go throughF por this resonD the following lso work in lF

for(i <- 0 until 10) { println(i) }


sing until uses the ounting to (nish one efore the lst vlue listedF he for loop in l isn9t just out ounting thoughF sndeedD this usge is something of speil se in lF sn generlD the expression to the right of the `E in for loop in l n evlute to ny type of olletionF sn other lngugesD this type of loop tht runs through the elements of olletion is often lled forEeh loop euse it does something for eh element of the olletionF ht might remind you of the foreh method from setion UFRF his is more thn pssing resemlneD ut tht is something you don9t need to understnd t this pointF o illustrte this usge of the for loopD onsider the following ode in the ivF

scala> List.tabulate(10)(i => i*i) res0: List[Int] = List(0, 1, 4, 9, 16, 25, 36, 49, 64, 81) scala> for(elem <- res2) { | println(elem) | } 0 1 4 9 16 25 36 49 64 81

CHAPTER 8.

LOOPS

IUT

sn this seD the for loop tully does extly the sme thing tht foreh does nd runs the ode inside the loop on eh of the di'erent elements in the listF ht ode you put in the for loop n e ritrrily omplexF he print sttements shown here just mke simple exmplesF e more generl desription of the syntx of the for loop would e the folE lowingF

for(name <- collection ) statement


he nme n e ny vlid l nmeF he olletion n e ny expression tht results in olletionF he sttement n e nything tht you wnt to hve hppenF prequently ode lok is used nd you will see multiple sttements in urly resF vet9s use for loop to evlute polynomilF e will tret n erryhoule s the polynomil where eh element in the rry is oe0ient of term in the polynomilF por exmpleD the polynomil 3x3 + 6x2 4x + 7 is represented s erry@QFHDTFHDERFHDUFHAF e wnt the funtion to evlute the polynomil for prtiulr vlue of x tht will lso e pssed into the funtionF e will write this in severl wysF he (rst one will use ounting loopF

def evalPolyCount(coefs:Array[Double],x:Double):Double = { var ret=0.0 for(i <- 0 until coefs.length) { ret+=coefs(i)*math.pow(x,coefs.length-1-i) } ret }
his will workD ut it is prtiulrly ine0ientF he use of mthFpow for smll integer exponents is very ine0ientF lking through the rry with the index isn9t dD ut if we deided to use vist for the oe0ients tht would hngeF ell tht the for loop is intended to go through the elements of olletionF es suhD we ould just run through the elements of oefs nd perform the mthF he only hllenge in this is tht we were using the indexD iD to lulte the power of x s wellF e ould get rid of tht nd remove the use of pow if we simply went through the rry in the reverse orderF utting tht logi into ode produes thisF

def evalPolyReverse(coefs:Array[Double],x:Double):Double = { var ret=0.0 var power=1.0 for(c <- coefs.reverse) { ret+=c*power power*=x }

CHAPTER 8.

LOOPS

IUU

ret

his version doesn9t ount with n indexF snsted it runs through the rry elementsF ih vlue in the rry is put into nd then the return vlue is inrementedF e seprte vrile lled power is reted with vlue of IFH nd eh time through it is multiplied y xF his provides us with running power of x nd removes the need to ll mthFpowF his funtion is lso perfetly orretF st9s min drwk is tht in order to do the powers of x properlyD the rry hd to e reversedF qiven this usgeD tht will rete ompletely new rry nd opy the elements ross in the reverse orderF hile tht is lso ine0ientD this does llow us to niely illustrte the using of the for loop to run through ny olletionD even one tht is reted through opertions on other olletionsF

8.3.1 Range Type


xow tht you hve seen tht the for loop relly just runs through olletionD you might wonder out the ounting usge with something like thisF

for(i <- 0 until 10) { ...


o understnd this it might help to type some expressions into the iv nd see wht is relly going onF rere we hve done thtF

scala> 1 to 10 res8: scala.collection.immutable.Range.Inclusive with scala.collection.immutable.Range.ByOne = Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) scala> 0 until 10 res9: scala.collection.immutable.Range with scala.collection.immutable.Range.ByOne = Range(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
e won9t try to understnd wht this gives us in ny gret detilD ut there is one signi(nt thing to relize from thisF he expressions I to IH nd H until IH give us k vlues tht tully re olletionsF hese re instnes of the nge typeF he nge type in l gives us simple wy to use the forEeh style loop tht l provides to do the ounting opertions tht most progrmmers re used to using the for loop to omplishF ou n use to nd until with other integer types inluding the ghr typeF o the expression 99 to 9z9 will give you olletion of ll of the lower se letterF ht if you wnt to ount downc he nge type hs n opertion y de(ned on it tht will llow you to speify the step etween elements in the ngeF o if you wnt to go from IH down to I you n use IH to I y EIF e n use this to get version of the polynomil evlution funtion the uses the index ountingD ut doesn9t require power nd insted keeps trk of the exponent of xF

CHAPTER 8.

LOOPS

IUV

def evalPolyCountDown(coefs:Array[Double],x:Double):Double = { var ret=0.0 var power=1.0 for(i <- coefs.length-1 to 0 by -1) { ret+=coefs(i)*power power*=x } ret }
his version hs most of the dvntges of oth of the previous versionsF st doesn9t hve to reverse the rryD nor does it require the use of mthFpowF he one downside is tht it still wouldn9t trnslte well to vistF sf you use yD you n lso use nges of the houle typeF ytherD less stndrdD numeri types like figsnt will lso work niely with the nge typeF he ft tht the nge type is relly olletion mens tht ll of the methods tht were disussed in the lst hpter re ville for themF his leds to onise wy of expressing ftorilF

scala> (1 to 5).product res21: Int = 120


sn ddition to produt nd sumD you n lso pply mpsD (ltersD or other opertions to instnes of the nge typeF here re sometimes when you wnt to ount through the indies of olE letion like n rryF ou ould do this with ode like the following ssuming tht you hve n rry lled F

for(i <- 0 until a.length) ...


ou n lso use the indies method on the olletionF glling Findies will give you rnge tht goes from the (rst index to the lst oneF o this loop ould lso e expressed in this wyF

for(i <- a.indices) ...


xot only is this shorterD it is slightly less error prone in tht you n9t idently strt t I insted of HD nor n you identlly use to insted of untilF

8.3.2 yield
he while loop is sttement only nd n9t e used s n expressionF his isn9t true of the for loopF ou n use the for loop to produe vlue so tht is n e used s n expressionF his is done y putting the yield keyword right fter the lose prentheses of the for loopF hen you use yieldD insted of sttement you need to hve n expressionF he result of the for expression is new olletion with ll of the yielded vlues in itF he following shows simple exmple of thisF

CHAPTER 8.

LOOPS

IUW

scala> for(i <- 1 to 10) yield i*i res22: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 4, 9, 16, 25, 36, 49, 64, 81, 100)
enother slightly di'erent exmple shows how you ould use for loop to mke olletion tht is (lled with vlues red in from inputF

val nums=for(i <- 1 to 10) yield readInt()


his ould work s n lterntive to (ll if you (nd it more redleF ou should note tht the exmple gives result with type we hven9t seen eforeF he generl type is listed s n sndexedeqsnt nd the spei( ojet is etorsntF hon9t let these di'erent types throw you o'F por our purposesD we will use them just like we would the erry typeF he di'erene etween the erry nd the etor is tht the etor is immutleF ou n index into it e0iently like n erryD ut like vistD you ren9t llowed to hnge the vlues of the elementsF ell the stndrd funtions tht we sw erlier for erry nd vist will work on these types s wellF

8.3.3 if Guards
he for loop in l lso llows onditionlsF efter the (rst genertorD you n put n if tht hs ondition on itF he for loop will only hppen for those instnes where the ondition is trueF his n led to more ompt syntx thn putting if inside of the for loopF st n lso e more e0ientF wost importntlyD it n e useful when you hve yield so tht you don9t dd unwnted elements to the vlue of the expressionF es n exmple of thisD nd other spets of the for loopD lets onsider hving sequene of points in PEh tht re stored s @houleDhouleAF s wnt n expression tht will give me k sequene tht hs the distnes to those pointsF he th is tht s only wnt the distnes tht re less thn oneF ithout the if gurdD this would require two stepsF yne would lulte the distnes nd seond would (lter out the lrge vluesF he if gurd lets us do this in single loopF

for((x,y) <- points; if(magnitude(x,y)<1.0)) yield magnitude(x,y)


his exmple ws written ssuming funtion lled mgnitude tht might look like the followingF

def magnitude(x:Double,y:Double):Double = math.sqrt(x*x+y*y)


he eginning of this loop illustrtes how you n use pttern on tuple to pull out the two elements in the pointF his is tully one of the gret strengths of the for loop in l tht helps simplify your progrmmingF he one signi(nt drwk of this pproh is tht the mgnitude funtion is lled twieF he sqrt funtion n e expensive so this is less thn idelF e9ll see how to get round tht shortlyF

CHAPTER 8.

LOOPS

IVH

8.3.4 Multiple Generators


he for loop in l lso supports the ility to iterte ross multiple olleE tions in single for loopF his n e done y putting more thn one vrileE xme `E olletion in the prenthesesF ih of these tht you put into the for loop will generte vlues from the olletion to run through the logiF he (rst genertor will pull the (rst vlue from its olletionF e seond genertor will then run through ll of its vlues efore the (rst one goes on to the seond opE tionF o the numer of times the ody of the loop hppens goes s the produt of the numer of elements in the olletions for the genertorsD not the sumF ho help you understnd thisD onsider the following exmpleF

scala> for(i <- 1 to 5; c <- 'a' to 'c') println(i+" "+c) 1 a 1 b 1 c 2 a 2 b 2 c 3 a 3 b 3 c 4 a 4 b 4 c 5 a 5 b 5 c


ou n see tht the hrter vrileD D goes through ll of its vlues for eh vlue tht i tkes onF es resultD there re IS lines printedF ou might wonder why you would wnt to do thisF gonsider the exmple of using PEtuple to represent pointsF ou might wnt to mke olletion of ll the points on grid in some rnge of x nd y vlues with prtiulr sping in the gridF ou ould do tht with the following odeF

val val val val val val val

xmin = -1.5 xmax = 0.5 xstep = 0.01 ymin = -1.0 ymax = 1.0 ystep = 0.01 pnts=for(x <- xmin to xmax by xstep; y <- ymin to ymax by ystep) yield (x,y)

he output from the lst line will pper in the iv s something like the followingF

CHAPTER 8.

LOOPS

IVI

pnts: scala.collection.immutable.IndexedSeq[(Double, Double)] = Vector((-1.5,-1.0), (-1.5,-0.99), (-1.5,-0.98), (-1.5,-0.97), (-1.5,-0.96), (-1.5,-0.95), (-1.5,-0.94), (-1.5,-0.93), (-1.5,-0.92), (-1.5,-0.91), (-1.5,-0.9), (-1.5,-0.89), (-1.5,-0.88), (-1.5,-0.87), (-1.5,-0.86), (-1.5,-0.85), (-1.5,-0.84), (-1.5,-0.83), (-1.5,-0.82), (-1.5,-0.81), (-1.5,-0.8), (-1.5,-0.79), (-1.5,-0.78), (-1.5,-0.77), (-1.5,-0.76), (-1.5,-0.75), (-1.5,-0.74), (-1.5,-0.73), (-1.5,-0.72), (-1.5,-0.71), (-1.5,-0.7), (-1.5,-0.69), (-1.5,-0.68), (-1.5,-0.67), (-1.5,-0.66), (-1.5,-0.65), (-1.5,-0.64), (-1.5,-0.63), (-1.5,-0.62), (-1.5,-0.61), (-1.5,-0.6), (-1.5,-0.59), (-1.5,-0.58), (-1.5,-0.57), (-1.5,-0.56), (-1.5,-0.55), (-1.5,-0.54), (-1.5,-0.53), (-1.5,-0.52), (-1.5,-0.51), (-1.5,-0.5), (-1.5,-0.49), (-1....
sn this seD the output is trunted efore it even gets to the seond vlue of xF

8.3.5 Variable Declarations


sf gurdsD multiple genertorsD mthing ptternsD the for loop seems like dremD ut wit3 here9s more3 ou n de(ne vriles inside of the for loopF his is helpful for situtions like we hd erlier where we don9t wnt to hve to lulte the mgnitude twie for eh itertionF

for((x,y) <- points; val dist=magnitude(x,y); if(dist<1.0)) yield dist


sn this smpleD the mgnitude is lulted nd stored in distF ht vlue is then used in the two di'erent lotions where it hd een lulted eforeF he genertorsD if gurdsD nd vlue delrtions n e omined in ny wy given tht genertor omes (rstF his provides signi(nt mount of power in single onstrutF tust don9t use it to mke ode tht no one n understndF

8.4 Multidimensional Arrays


hen we (rst introdued rrys nd lists k in hpter UD we sw tht these types re prmetriF ht mens tht the type requires type rgument to e fully de(nedF o you n9t hve just n erry or just vistF snsted you hve errysnt or visttringF ih of these is type in lF he prmeter for these prmetri types n e ny type1 F sf you put these together you n uild things like erryerryhouleD vistvisttringD or visterrysntF ou don9t hve to stop there thoughF l will e perfetly hppy with
1 There
can be restrictions on parametric types, but the collections generally allow any type to be used.

CHAPTER 8.

LOOPS

IVP

visterryvistvisterrysntF st isn9t ler wht you would wnt suh type forD ut if you (nd useD l will support itF sn the se of rrys of rry typesD we hve speil term for themF hey re lled multidimensionl rrysF his is euse of how you might piture them in your hedF ou n piture norml rry s row with multiple ins tht eh store vlueF en erryerrysnt ould e pitured s tle of integers tht hs rows nd olumnsF uh tle ould e sid to e two dimensionlF sf you hd n erryerryerrysnt you ould piture it s ue of vlues in three dimensionsF sn generl ll these things n e pplied to lists just s well s rrysD ut the term multidimensionl list isn9t nerly s ommonF o how n you rete nd use multidimensionl rrysc he most si syntx mirrors wht we used to originlly rete norml rrysF

scala> val tda1=Array(Array(1,2,3),Array(4,5,6)) tda1: Array[Array[Int]] = Array(Array(1, 2, 3), Array(4, 5, 6))


sn this usge the numer of elements in eh suErry does not hve to e the smeF hen the lengths re di'erentD they re lled rgged rrysF hen they re ll the smeD they re lled retngulr rrysF sf you re interested in mking lrge retngulr rrysD you should use either the (ll method or the tulte methodF his usge is shown elowF

scala> val tda2=Array.fill(10,10)(0) tda2: Array[Array[Int]] = Array(Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0), Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0), Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0), Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0), Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0), Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0), Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0), Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0), Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0), Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)) scala> val tda2=Array.tabulate(10,10)((i,j) => i*j) tda2: Array[Array[Int]] = Array(Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0), Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9), Array(0, 2, 4, 6, 8, 10, 12, 14, 16, 18), Array(0, 3, 6, 9, 12, 15, 18, 21, 24, 27), Array(0, 4, 8, 12, 16, 20, 24, 28, 32, 36), Array(0, 5, 10, 15, 20, 25, 30, 35, 40, 45), Array(0, 6, 12, 18, 24, 30, 36, 42, 48, 54), Array(0, 7, 14, 21, 28, 35, 42, 49, 56, 63), Array(0, 8, 16, 24, 32, 40, 48, 56, 64, 72), Array(0, 9, 18, 27, 36, 45, 54, 63, 72, 81))
xote tht the numer of rguments you pss into the (rst rgument list of tulte or (ll determines the dimensionlity of the resulting strutureF sn the se of tulteD the funtion tht is pssed in seond needs to tke s mny rguments s there re dimensionsF ou n lso use tulte to mke nonEretngulr rrys y uilding IEh rry those ontents re rrys nd using the index to determine the lengthF ht tehnique is used here to rete tringulr PEh rryF

scala> val tda3=Array.tabulate(10)(i => Array.fill(i+1)(0))

CHAPTER 8.

LOOPS

IVQ

tda3: Array[Array[Int]] = Array(Array(0), Array(0, 0), Array(0, 0, 0), Array(0, 0, 0, 0), Array(0, 0, 0, 0, 0), Array(0, 0, 0, 0, 0, 0), Array(0, 0, 0, 0, 0, 0, 0), Array(0, 0, 0, 0, 0, 0, 0, 0), Array(0, 0, 0, 0, 0, 0, 0, 0, 0), Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0))
xote tht the output here hs di'erent numer of elements in eh of the suErrysF o ess the elements of PEh rryD simply put two sets of prentheses fter the rry nme with two di'erent indies in themF por exmpleD we n pull vlues out of tdP in this wyF

scala> tda2(3)(4) res0: Int = 12


he PEh rry tdP ws reted to e something like multiplition tleF his prtiulr expression pulled o' the element t position QDR whih is IPF he dvntges nd restritions of the vist nd erry type tht were disE ussed previously pply to higher dimensionl ses s wellF yne you hve mde n rryD the vlues n e hngedD ut the length n9tF imilrlyD you n mke new lists y e0iently dding to the hed of old onesD ut you n9t mutte vlues in list even if it hs higher dimensionF o ring these things k to the originl topi of the hpterD how n you use for loops to produe higher dimensionl dt struturesc yne might think tht multiple genertors would do thisF roweverD tht isn9t the se s you n see if you go k to our exmples in tht setionF sf you wnt to hve onstrut with higher dimensionsD you need to hve multiple nested for loopsF es n exmple of thisD we will use for loops to uild the multiplition tle tht we uilt erlier with tulteF

val multTable = for(i <- 0 until 10) yield { for(j <- 0 until 10) yield i*j }
sf you exeute this ode in the iv you get the following resultF

multTable: scala.collection.immutable.IndexedSeq[scala.collection.immutable. IndexedSeq[Int]] = Vector(Vector(0, 0, 0, 0, 0, 0, 0, 0, 0, 0), Vector(0, 1, 2, 3, 4, 5, 6, 7, 8, 9), Vector(0, 2, 4, 6, 8, 10, 12, 14, 16, 18), Vector(0, 3, 6, 9, 12, 15, 18, 21, 24, 27), Vector(0, 4, 8, 12, 16, 20, 24, 28, 32, 36), Vector(0, 5, 10, 15, 20, 25, 30, 35, 40, 45), Vector(0, 6, 12, 18, 24, 30, 36, 42, 48, 54), Vector(0, 7, 14, 21, 28, 35, 42, 49, 56, 63), Vector(0, 8, 16, 24, 32, 40, 48, 56, 64, 72), Vector(0, 9, 18, 27, 36, 45, 54, 63, 72, 81))
his hve the sme vlues s the erryerrysnt tht we mde erlier nd we n use it the sme wy despite the ft tht it is tehnilly etoretorsntF

CHAPTER 8.

LOOPS

IVR

8.5 Testing
e hve now gotten to the point where you n write progrms of resonle omplexityF ou know most of the onstruts tht exist in the l progrmE ming lngugeF es soon s you strt writing lrger progrmsD there re some new elements of the progrmming proess tht eomes more signi(nt suh s testing nd deuggingF tust euse you hve written the ode nd it ompiles nd runs doesn9t men tht it is orretF o determine if it tully does wht you wnt it to you need to test itF his mens tht you need to run the ode with vriety of di'erent inputs to mke sure tht they ll work nd then (x the prolems when they don9tF he (rst prt of thisD running the progrm with di'erent inputs is lled testingF he hllenge in testing is trying to (gure out wht inputs mke good testsF hen you re testing ode you re tully looking for inputs tht will rek wht you hve writtenF ou wnt to give it some things tht you know it will work onD ut you lso wnt to give it some things tht you think might rek itF sn dditionD good set of tests will go through ll of the funtionlity of the odeF hinking of things tht will rek the ode often involves looking for oundE ry onditionsF hings tht re right t the edge of vlid inputF por exmpleD if you hve funtion tht tkes n rry or listD wht hppens if the list or rry you pss in is emptyc ou wnt to hek di'erent smll numer input sets s well s lrge onesF sf the ode tkes numeri vluesD does it work for oth positive nd negtivec ht out zeroc qiving you k nswers tht re wrong or don9t mke sense n e worse thn rshingF sf the input is tringD wht hppens when the tring is emptyc here re some situtions where you will e ertin tht the input hs prtiulr strutureF sn other situtions the input will e oming from user who might give you something tht isn9t quite wht you expetedF iven when the input is oming from nother prt of the progrm nd something tht you think will hve the right formtD there n e ses tht you hven9t onsideredF qood testing will help you (nd these situtionsF sf prts of your ode require tht ertin things e trueD you n use the require funtion in l to fore the progrm to terminte if ondition is violtedF ou n ll require with just foolen rgumentF sf the foolen is flseD the progrm will terminteF ou n mke the termintion n e mde more informtive y providing seond rgument tht is messge to give the user if the requirement filsF he following shows how this might e usedF

def weightedAverage(values:Array[Double],weights:Array[Double]):Double = { require(values.length==weights.length, "Must have same number of values and weights.") require(weights.length>0,"Average of zero elements not defined.") require(weights.sum!=0.0,"Sum of weights can't be zero.")

CHAPTER 8.

LOOPS

IVS

(for((v,w) <- values.zip(weights)) yield v*w).sum/weights.sum

his funtion is intended to tke the weighted sum of set of vluesF here re numer of requirements on the vlues pssed into itF here re three require lls tht mke sure tht eh of these is true efore it lultes the vlueF his might seem like lot of extr typingD ut if you put lls to require in your ode whenever there relly is requirementD you will (nd tht it mkes the deugging proess lot esierF he other prt of testing is overgeF howing tht the ode works for one test input isn9t su0ient to show tht it is relly orretF row mny tests do you hve to write to feel on(dent tht your ode worksc yne of the hllenges of gomputer iene is tht you n9t prove tht progrms re orretF his ws one of the erliest results of gomputer iene nd is still fundmentl spet of the theory of the (eldF gertinlyD some progrms n e proved to e orretD ut generlly the est we hieve is to show tht our progrms work ross rod rnge of inputsF here re some riteri eyond looking for oundry ses you n use to determine if you hve enough testsF he metri to determine this is lled ode overgeF ou wnt to know wht frtion of your ode hs een exeuted y the testsF here re numer of di'erent ode overge metris tht n e usedF

puntion overge E rs every funtion een lledc ttement overge E rs every sttement een exeutedc heision overge E rs every option in rnhing strutures @if nd mthA een exeutedc gondition overge E rs every foolen suEexpression evluted s oth true nd flsec gonditionGdeision overge E gomintion of the two oveF voop overge E rs every loop een exeuted zeroD oneD nd more thn one timesc th overge E rs every pth through prt of the ode een exeutedc
he more omplete the overge your test set hsD the more on(dent tht you re tht your ode is orretF he levels of overge higher in this list re silly miniml stndrdsF sf your tests hven9t gone to every funtion or every sttementD then there re prts of the progrm tht you simply hven9t testedF qoing eyond those you strt looking t di'erent wys for things to hppenF here re often severl di'erent ples from whih funtion n e lledF govering deisions will mke sure tht you hve lled them from di'erent lotionsF govering onditions mkes sure tht ll the possiilities for why di'erent prts of the ode might e rehed hve een exerisedF

CHAPTER 8.

LOOPS

IVT

sf you stop nd think out itD you will proly relize tht getting onE ditionGdeision overge requires quite few test sesF iven these options potentilly leve lot of possiilities unheked s they don9t fore loops to hppen di'erent numers of timesF he ultimte form of overgeD pth ovE ergeD is generlly unttinle for ny progrm of even modest sizeF rving pth overge implies tht you hve tested every possile pth tht the exeE ution ould tke through the odeF gonsider simple funtion with three if sttements one fter the otherF yne pth through the ode would hve ll three evlute to trueF enother pth might hve the (rst two true nd the lst flseF here re tully eight di'erent pths through suh funtionF sf you dd nother ifD the numer of pths doules to ITF th overge requires exponenE tilly mny di'erent ses e tested s onditionl sttements re ddedF sf tht wsn9t d enoughD single while loop retes n in(nite numer of di'erent pths s the loop ould exeute zeroD oneD twoD or more timesF ih one is di'erent pth through the odeF es suhD pth overge is generlly viewed s n unttinle idel for nything eyond firly simple funtionsF hue to the hllenges of getting good overge on lrge olletions of odeD it is ommon to do testing on smll loks t timeF his proess is lled nit testingF ih di'erent unit of the ode hs test suite written for it tht heks it9s funtionlity independent of other prts of the odeF hese test suites re run over nd over gin during development to mke sure tht no new hnges rek ode tht ws written erlierF he rel dvntge of nit testing is tht in smll unitD one n hope to get firly omplete pth overgeF roweverD it isn9t su0ient to only do nit testsF es the di'erent units re ssemledD they hve to e put through integrtion tests tht test how the piees work togetherF st is very possile for two units of ode to work perfetly in isoltion nd fil miserly when they re put togetherF

8.6 Views (Advanced Topic)


he olletion methods tht we lerned out in hpter U provide you with the ility to write onise expressions tht hve remrkle powerF nfortuntelyD if you string together mny of these methodsD the result n e ine0ient odeF gonsider the following for some list of sntsF

numList.filter(_>70).map(_/10-6).sum
his expression mkes two dditionl lists nd runs through lists totl of three timesF st (rst runs through numvist with the (lter nd produes new list of the elements tht pss the (lterF st then runs through tht list nd mps the elements to rete nother listF pinlly it runs through tht list nd tkes the sum of the elementsF he multiple intermedite lists nd the itertion through them is ine0ientF ell of this extr work hppens euse the vist type is strit typeF ht mens tht whtever it ontins is truly kept in memory s rel strutureF por

CHAPTER 8.

LOOPS

IVU

expressions like this we would like the ility to hve nonEstrit representtion of the vistF sn l suh things re lled iewsF wost opertions on view rue the opertion without tully performing itF vter onD the opertions n e fored whih will use them to tully hppen nd produe strit representtionF o get view ll the view method of olletionF ypertions like mp nd (lter tht re done on the view will give you new view type tht hs memory of wht opertions re to e performedD ut the work won9t hve een done yetF ou n fore the opertions to e pplied to give you k strit representtion of the dt with the fore methodF ome other methodsD suh s sumD whih produe (nl vlueD will lso fore the rued opertions to e performedF o the ove ould e done using views in the following wyF

numList.view.filter(_>70).map(_/10-6).sum
his ode only runs through the olletion one t the ll to sum nd doesn9t rete ny intermedite listsF sf numvist were prtiulrly longD this ould provide signi(nt ene(tF

Self-Directed Study
inter the following sttements into the iv nd see wht they doF ome will produe errorsF ou should try to (gure out whyF ry some vritions to mke sure you understnd wht is going onF

scala> def succ(n:Int):Int = n+1 scala> succ(1)


333

Exercises
wny of these exerises re identil to ones tht were given in hpter TF he only di'erene is tht those prolems were to e solved with reursion nd these re to e solved with loopsF IF rite the isrime tht returns foolen telling if numer is prime using loopF PF rite funtion using loop tht will print powers of two up to some vlueF QF rite funtion using loop tht will print powers of two up to some powerF RF rite funtion using loops tht will print multiplition tle up to IHsF ry to get it running (rstD then onsider how you ould mke everything line upF

CHAPTER 8.

LOOPS

IVV

SF rite funtion tht returns vistsnt of the prime ftors of numer using loopF TF epet exerise TFIH using loop insted of reursionF UF rite ode tht n tke vistsnt nd give you k new one where ll the vlues hve een douledF ho this with while loopD for loop without yieldD nd for loop with yieldF VF his prolem is like UFS in tht you re supposed to ount the numer of even vlues in n errysntF he di'erene is tht now you will do it one with while loop nd one with for loopF WF 333 rimlity testing for getting ig prime numersF IHF 333 wultiplitive inverse in modulo speF

Projects
IF his projet uilds on top of projet UFRF por this you will (ll in n entire grid of vlues with intersetion prmeters for set of geometryF wost imges on omputers re mde s grids of vlues where the vlues give the olorsF e don9t quite hve the ility to introdue olors nd imges yetD ut we re getting loseF por now s wnt you to (ll n erryerryhoule with the t prmeE ters for olletion of geometryF ou should write funtion tht tkes the following rgumentsX lotion of the viewer s QEh pointD forwrd diretion for the viewer s QEh vetorD up diretion for the viewer s QEh vetorD sequene of geometry @spheres nd plnesAD nd the numer of ells ross the squre grid should eF ou will st one ry for eh ell in the grid nd see if it hits nything nd if soD how fr out it hitsF pill the grid with the vlues for minimum intersetion prmeterF he grid represents plne in spe tht is one unit in front of the viewer position with top left orner tht is one unit up nd one unit to the leftF he grid extends to one unit to the right nd one unit downF his is the si pproh for uilding imges using ry tringF PF yne of the useful things tht you lern in lulus is tht funtions n e pproximtedF our lulus text will mention oth the wvurin series pproximtion nd the ylor series pproximtionF hey re silly the sme other thn wvurin series re lwys tken out xaH nd this is wht we will e working with hereF he de(nition of the wvurin series is f (i) (0) i f ( x) x i! i

CHAPTER 8.

LOOPS

IVW

F o this is the sum from iaH up to some n @or in(nity if you wnt to e relly urteAF sn the sum we hve x rised to the i power times the ith derivtive of f@xA evlutted t H divided y i ftorilF yviouslyD this is rel pin to use on funtions where tking the derivtive isn9t esyF roweverD for some funtions where the derivtives re strightforwrdD performing this pproximtion is very esyF ixmples of tht would e ex D sin(x)D nd cos(x)F s wnt you to write progrm tht does wluE rin pproximtion of cos(x)F ht9s not tht hrd euse the derivtive is sin(x)D whih hs derivtive of cos(x) whih goes to sin(x) then k to cos(x)F elso note tht you re lwys evluting t xaH so ll the terms for sin go to zeroF he (rst few terms in this series reX x4 x6 x8 x2 +0+ 0 +0+ + ... 10 2! 4! 6! 8! por this projetD you should sk the user for the x to useD s well s n uryF se the mthFos funtion to get the rel vlue of osine t tht vlue of xF hen iterte until the di'erene etween the series vlue nd wht tht funtion gives you is less thn the input uryF efter the loopD print out the rel vlueD the vlue you got from the seriesD nd how mny terms you hd to sum in itF @por extr reditD mke your progrm use ylor series instedF his mens inputing nother vlue x0 whih the series is expnded roundFA QF gomputers re used extensively for simulting physil systemsD espeilly when the system is hrd or impossile to uild in lF por this projet you will write simple simultion of the grvittionl uepler prolemF ou will lso explore the ury of wht you re doing little itF smgine you hve ody in orit round strF e9ll ssume tht the str is muh lrger thn the other ody so it stys t the originD @HDHAD of our oordinte systemF he other ody strts t some position @xDyA with veloity @vxDvyAF e simple 4integrtor4 for system like this n e onstruted y disretizing xewton9s lws @ fny wy of sying tht we void lulus nd do things in wy tht is more omputer friendlyAF m 2 xewton9s seond lw tells us F1 = m1 a1 nd for grvity F = G m1d F 2 1 e9re going to simplify this for our toy system nd just sy tht a = d 2F y x e n rek this into omponents nd get ax = d 3 nd ay = d3 F xowD the trik on the omputer is to sy tht insted of moving smoothlyD the prtile jumps over ertin timestepsD dtF o fter one timestep the new position is x = x + dt vx nd y = y + dt vy F imilrlyD vx = vx + dt ax nd vy = vy + dt ay F hoing this in loop 4integrtes4 the motion of the odyF @se the mthFsqrt funtion in mth to lulte dFA his integrtor is very simpleD ut fr from perfetF sf you strt with your ody t @IDHA with veloity of @HDIA it should e in nie iruE lr orit stying tht distne foreverF fy mesuring how tht distne

CHAPTER 8.

LOOPS

IWH

hngesD you n get mesure of how urteD or inurteD the inteE grtor isF ou n ply with other positions nd veloities to see wht hppensF ou will write progrm tht tkes the initil xD yD vxD nd vy s well s timestepD dtD s inputsF st should dvne the system for totl time of IHFH @so if dtaHFI tht requires IHH itertionsAF et the end of it you should mesure the distne from the origin nd print messge giving tht nd the originl distneF hen hek to see if the hnge is less thn I7F sf it isD sy tht the integrtion ws urte enoughD otherwise sy it isn9tF sn omment in your ode you should tell me how smll you hd to mke your timestep for this to e rehed given the oordinte I H H IF @s should note tht this mesure of ury is only good for irulr oritsF e ren9t going to do enough physis to go eyond thtD ut if you hppen to wnt toD the rel ojetive is to onserve totl energyF ou n get extr redit y ompring initl nd (nl totl energies of the systemF por funD you n hnge it so it prints the x nd y vlues during the simultion nd see wht is hppening with gnuplot in mnner similr to wht is desried in projet TFRF his n lso e helpful for deuggingF s hve inluded suh printouts in the smple outputF RF en lternte physis prolem tht n e solved in the sme wy s tht for the previous projet is lulting the trjetory of projetileF 333 SF por this prolem you will do some string prsing tht hs reltionships to hemil formuls in hemistryF e re going to keep things firly simple for thisF he si ide is tht the user types in string tht is hemil formulD nd your progrm should prse tht string nd tell how mny of eh type of element re on eh side of the equtionF his is the (rst step in lning hemil equtionF e lter projet will hve you go through the proess of doing the tul lningF he formt of the hemil eqution will look something like thisX grRCyParPyCgyPF his is retion for urningGoxidizing methneF xote tht it isn9t well lned euse there need to e oe0ients in front of eh termF our progrm will ssume oe0ient on eh term in the eqution s lower se letter strting with 99 in lphetil order from left to right nd output how mny of eh element there reF o for this input the output would eX gX BIadBI rX BRaBP yX BPaBICdBP or if you wnt to len it up itD

CHAPTER 8.

LOOPS

IWI

gX ad rX BRaBP yX BPaCdBP his gives us three liner equtions tht we ould try to solve @tully we hve Q equtions for R unknowns so the system is underdeterminedD ut tht is often the se so we will (nd the solution where D D D nd d hve the smllest vlues possile nd re ll integers ut you don9t hve to worry out tht nowAF e won9t e solving it in this projetF o e more spei( out the inputD it hs sequene of terms tht re seprted y C or aF ere the regents re in terms on the left hnd side of the a nd the produts re on the right hnd side of the aF ih term n hve one or more element nmesD eh followed y the numer of tht element in the given moleuleF he element nmes will ll e one hrters long nd pitlizedF elsoD the numer of elements will e just one digitF sf no numer is present you ssume there is only oneF ellowing elements with more thn one letter @upperse followed y lowerseA or numers with more thn one digit is extr reditF he output should hve seprte line for eh element tht ws present in the equtionF st should list the symol for the element followed y olon nd then the eqution tht tells wht the oe0ients hve to stisfy for tht element to e lned on oth sides of the equtionF ou n hoose either formt oveF

Chapter 9

Text Files
wost of the progrms tht you use on regulr sis would e fr less useful if they didn9t hve the ility to red from nd write to (lesF gonsider word proessor tht ouldn9t sve your (les nd let you lod them k in lterF yne where you hd to print the pper efore you losed to progrm to hve ny reord of wht you hd doneF uh progrm wouldn9t e very useful nd s suhD it wouldn9t e used muhF ht is true even if it provided you with very full set of other pilitiesF he reson for this is tht ll work you do without (le sits in the temporry memory of the omputer tht is given to the pplition when it runsF hen the pplition is stoppedD for ny resonD ll of tht memory is lostF s might e given over to other pplitions or used y the operting systemF htever hppens to itD you no longer hve the ility to get to it in ny useful wyF piles give you the ility to store vlues from one run of progrm to the nextF piles n lso e used to store informtion tht you don9t wnt to hve to write into the soure ode or just to store mounts of informtion lrger thn wht will (t in the memory of the mhineF hisk drives re muh slower thn memory so this lst prt hs to e done with extreme utionF

9.1 I/O Redirection


sn ertin wyD you hve lredy hd the ility to mke your progrm del with (les through sGy rediretionF hen you run the progrm from the omE mnd line s sriptD you n hve stndrd input ome from (le using `F ou n lso mke the stndrd output go to (le using bF his works very niely if you re going to e entering the sme vlues multiple times or wnt to preserve the output so tht you n look t itF he down side of using sGy rediretion is tht it is rther limitedF ou only get to red from one (le or write to one (leF ht is moreD if you deide to red from (leD you n9t lso hve the user provide some of the input from the keyordD or if you deide to hve the output go to (leD your user won9t IWP

CHAPTER 9.

TEXT FILES

IWQ

see nything tht is printed ome up on the sreenF hese limittions mke this pproh imprtil for most pplitionsF es suhD it is importnt for us to lern other wys

9.2 Packages and Import Statements


fefore we n lern out reding from (les nd writing to (lesD we need to lern little out how ode is orgnized in lrge projetsD nd spei(lly in the stndrd lirries of lF iverything tht we hve used so fr ws ville in l without us hving to speify where to look for itF he si prts of the lnguge re simply ville y defultF pile hndling is not ville y defultF e will hve to tell l where to go looking in the lirries for these thingsF he l lnguge uses pkges to orgnize odeD feture inherited from tv nd present in mny other lngugesF o understnd the reson for pkE gesD onsider the vist type tht we lerned to use in hpter UF his type is de(ned y lss written in the l lirries tht is ville to you y defult euse it is so ommonly usedF roweverD the word vist is not n unommon oneF ithout pkges there ould only e one type lled vistF sf nyone tried to rete nother oneD it would on)it with the (rst oneF kges llow you to hve multiple types tht ll hve the sme se nme like vistD ut whih re di'erentited y eing in di'erent pkgeF sn the se of vistD the one you hve een using is tehnilly slFolletionFimmutleFvistF roweverD the nme vist ould lso refer to jvFutilFvist or jvFwtFvistF hese longer nmes re the fully spei(ed nmes of the typesF hey speify oth pkge nme nd the spei( type nmeF kges re typilly nmed in ll lower se nd the dots seprte supkges in hierrhy going from rodest to most spei(F o the vist tht you hve een using sits in the top level pkge slD whih hs supkge lled olletionD whih inside of it pkge lled immutleD nd the vist type is inside of tht supkgeF e won9t worry out reting pkges t this pointF ht is topi tht is etter left for lter onF ight now ll you need to understnd is tht they exist nd how to del with ode tht is in pkgesF o illustrte wht you need to knowD we9ll onsider one of the types we will use for the topi of this hpterF o help us red from (les we will use instnes of the slFioFoure typeF hile it is useful to know the fully spei(ed nme if this type s well s tht of othersD these full nmes re rel pin to type in ll the timeF smgine if you hd to type in slFolletionFimmutleFvist ny time you wnted vist in your odeF his is the reson tht the import sttement existsF en import sttement gives l diretions on how to (nd thingsF sf it sees the nme of type or vlue tht isn9t delred lollyD it will look in things tht hve een imported to see if it n (nd it thereF he si syntx of n import sttement is to hve the keyword import followed y wht you wnt to importF o mke it esy to use slFioFoure you n do the followingF

import scala.io.Source

CHAPTER 9.

TEXT FILES

IWR

efter putting in this lineD you n just use the nme oure insted of the fully spei(ed nme nd l will know wht you menF he import sttement in l is very )exile nd powerfulF ou n use import nywhere you wnt nd it will e in e'et from tht point down to the end of the urrent sopeF o if it pper inside of urly resD it will only e in e'et inside those urly resF sn mny instnesD you will wnt to import everything in pkge @or other strutureAF ou n tell l tht you wnt to do this y using n undersore s wild rdF por exmpleD this line would ring everything in the slFio pkge into sopeF

import scala.io._
ou n lso import severl things with single line y grouping wht you wnt to import in urly resF sf you wnted to hve the oure lss nd the fu'edoure lss from the slFio pkgeD ut no other lssesD you ould use line like thisF

import scala.io.{Source,BufferedSource}
here re numer of other possiilities for import in l tht we will onsider lter when they re signi(nt to usF fy defultD l lwys inludes three imports for every (leF

import java.lang._ import scala._ import Predef._


he (rst one eings ll the stndrd lsses from tv into sopeF his is the only defult import in the tv lngugeF st lso imports the si l pkge nd then ll the ontents of the ojet slFredefF his lst one is the reson you n use funtions like redsnt@A s esily s you nF he lst import demonstrtes something else out l pkgesD they re truly nestedF ht lst import ould lso e written in this wyF

import scala.Predef._
roweverD euse the line ove it imports the sl pkgeD tht n e left o'F he impliit import of sl lso mens tht we n refer to slFioFoure s just ioFoure in either n import or in norml usgeF feuse ioFoure relly isn9t tht muh longer thn oureD you might not even feel need to inlude the importF ou n see the full struture of pkges for l y looking t the es on the l wesite @httpXGGwwwFslElngForgGAF he es is very helpful resoure in generlF st lists ll of the methods on everything tht is in the stndrd lirriesF fy the time we re done with this ookD you should hve the ility to go to the es nd look up ny funtionlity tht you might needF por now there re quite few things tht won9t mke sense euse there is more for us to lernF

CHAPTER 9.

TEXT FILES

IWS

9.3 Reading from File


xow tht you hve seen pkges nd import sttements it is time to tully use slFioFoure to help us red informtion from soures other thn stndrd inputF here re other wys tht we ould red from (les tht use the tv lirriesD some of whih we will disuss lterD ut for now we will use oure euse it provides us with su0ient pilitiesF eny ode in this setion will ssume tht you hve done n import of slFioFoure so tht we n refer to it y the short nmeF here is n ojet lled oure tht hs methods we n ll to get ojets of type oure tht we will use to red from thingsF he simplest wy to red from (le is to use the frompile method of the oure ojetF

scala> val fileSource=Source.fromFile("ch8.txt") fileSource: scala.io.BufferedSource = non-empty iterator


es you n see from this outputD the ojet we got k ws spei(lly of the type slFioFfu'eredoureF he fu'eredoure type will provide etter performne for (les whih is why we were given thtF st hppens tht reding from hrd disk is one of the slowest things you n do on omputer nd ig prt of the slowdown is the result of hving to move to the right prt of the diskF es resultD it is muh fster to red unh of dt t oneD even if you don9t need it ll yetD thn to red eh little piee of dt one yte t timeF he fu'eredoure does extly thisF st reds in reltively lrge mount of dt into u'er nd then gives you tht dt s you request itF hen the u'er is emptiedD it will red ginF hen you re done with the oure ojetD you should ll lose on itF sn this se tht would look like the followingF

fileSource.close
here re mny resons you should rememer to do thisD ut two relly stnd outF he (rst is tht progrm is only llowed to hve ertin numer of (les open t given timeF sf you fil to lose (les for n extended period of timeD you n run out of ville (le desriptor nd then you will try to open (le nd hve it filF st lso signls to l tht you re done with the (le so tht it n len up things like the memory tht ws used for the u'erF

9.3.1 Iterators
hen the vlue of the fu'eredoure is printed ll it shows is nonEempty itertorF his is euse the fu'eredoureD nd the norml oureD re oth of more generl type lled n stertorF en stertor is muh like the erry nd vist types tht we sw previouslyF sn ftD virtully ll the methods tht we ould ll on the erry nd the vist re ville on n stertorF he di'erene is tht si stertor n only e used oneF he erry nd the vist re sid to e sterle whih mens tht they n give us multiple stertors to use to

CHAPTER 9.

TEXT FILES

IWT

ll those methods over nd over ginF sn the se of n stertorD one you ll method tht runs through the whole thingD it is spent nd you n9t use it ginF

scala> fileSource.mkString res0: String = This is a sample text file that I've written to use for chapter 8. There really isn't all that much to this file. It is simply supposed to be used to illustrate how we can read from files. scala> fileSource.mkString res1: String = scala> fileSource res2: scala.io.BufferedSource = empty iterator
he (rst ll to mktring gives us k string tht hs the ontents of the (leF he seond ll gives us k nothingF he reson for this is ler if we look t the vlue of (leoureF efter reding through the (le the (rst timeD it hs gone from nonEempty itertor to n empty itertorF here is nothing left for us to redF he oure type provides something tht you don9t get in most stertorsD method lled reset tht will tke it k to the eginning of the dt soureF et fundmentl levelD the stertor type is sed on two methodsX hsxext nd nextF he hsxext method returns foolen nd tells you whether or not there is something more in the stertorF he next method will give you tht next thingF ou should e le to piture how these two methods n e used in either while loop or with reursion to let you run through the entire ontents of the stertorF he reson the fu'eredoure is just n itertor isn9t hrd to understndF ememerD reding (les is extremely slowF ou should do it one nd get the informtion you wnt tht timeF eding it over nd over gin would e ine0ientF o help fore you towrd e0ienyD you would hve to expliitly open the (le k up to iterte through it ginF ith the vist nd erry typesD you sw tht they were prmetriF e ould mke vistsnt or visttringF his is lso true of stertorsF he oure nd fu'eredoure types re spei(lly stertorghrF his mens tht they operte nturlly on individul hrtersF sf you ll funtions like mp or (lterD or if you onvert the itertor to list or rryD the result will e unh of hrtersF hile tehnilly ll the dt tht you wnt is in the form of hrtersD it n e it di0ult to operte with it in tht formtF por this resonD there is method lled getvines tht will give you k di'erent itertorF his new stertor is of the type stertortring nd eh element is full line in the (le without the newline hrter t the endF

9.3.2 String Split Method


iven lines ren9t lwys ll tht useful euse there might e multiple piees of dt on eh lineF here re mny wys tht you n split up tring into

CHAPTER 9.

TEXT FILES

IWU

di'erent pieesF he simplest of these is the split methodF he split method tkes single rgument tht is tring whih should e the delimiter etween the piees you wnt split upF st will then return n errytring with everything tht ws seprted y tht delimiterF rere is simple exmpleF

scala> "This is a test.".split(" ") res4: Array[java.lang.String] = Array(This, is, a, test.)


he tringD his is testFD is split up using single spe s the delimiterF he result hs eh word from the tring s seprte elementF ehnillyD the rgument to split is regulr expressionF e won9t go into the detils of regulr expressions until ghpter QHF here re just few things tht re worth mentioning t this pointF he regulr expression n hve more thn one hrterF elsoD the hrters 9C9 nd 9B9 hve speil meningsF he 9C9 sys tht the hrter efore it n our one or more times while the 9B9 sys tht it n our zero or more timesF his is worth mentioning t this point euse it is not unommon for inputs to potentilly hve multiple spes etween wordsF o hndle thisD you will often ll split with the string  C insted of just speF xow we wnt to put the split method into tion with the ility to red the (le lineEyElineF ht we wnt to do is rete ode tht will red in numeri dt from (le into PEh dt strutureF sn this seD we will rete PEh rry euse the diret ess pility is useful for most of the pplitions we would wnt to use this inF e9ll do this in two di'erent wysF e9ll rek this up into two funtionsF he (rst funtion will work with ny stertortring nd give us k the erryerryhoule tht we wntF he stertortring is helpful euse tht is wht getvines will give us nd tht is more )exile thn foring it to e (leF he seond funtion will tke (le nme nd return the erryerryhouleF st won9t do muh itself other thn use oure to red the (le nd pss tht itertor to the (rst funtionF foth funtions will lso tke delimiter for split so tht the person lling them n hoose wht we split onF

def dataGrid(lines:Iterator[String],delim:String):Array[Array[Double]] = { (lines.map(s => s.split(delim).map(_.toDouble))).toArray } def fileToDataGrid(fileName:String,delim:String):Array[Array[Double]] = { dataGrid(Source.fromFile(fileName).getLines,delim) }


xow we n demonstrte how this works y lling it on (le lled numersFtxt tht we hve retedF he (le hs the vlues for QxQ identity mtrix with the vlues seprted y omms s shown hereF

1.0, 0.0, 0.0 0.0, 1.0, 0.0 0.0, 0.0, 1.0

CHAPTER 9.

TEXT FILES

IWV

he hoie of formt is prtiulr euse this is wht you would get if you hd ixel write out g formt with only numersF g stnds for gomm eprted luesF st is more omplex if we inlude nonEnumeri dtF enything tht isn9t numeri is put inside of doule quotes in g (leF e9ll ignore tht for now nd only del with numersF e n red in this (le nd see the result in the ivF

scala> fileToDataGrid("numbers.txt"," *, *") res0: Array[Array[Double]] = Array(Array(1.0, 0.0, 0.0), Array(0.0, 1.0, 0.0), Array(0.0, 0.0, 1.0))
iverything here should e pretty ler with the possile exeption of the deE limiterF por this (leD it would hve worked to use the delimiter D F roweverD tht delimiter isn9t ll tht roustF sf there were ny extr spes either efore or fter the omm it would filF st would lso fil if spe ws left out fter the ommF iven with this delimiterD the dtqrid method leves some things to e desiredF e ren9t trying to mke it del with strings so we don9t onsider it prolem if this funtion rshes when there is string in the (le tht isn9t numerF wore prolemti is the ft tht it lso doesn9t del well with lnksF sn g (le there re two types of lnks tht n ourF yne is when there re two omms with nothing etween them nd one is when there is ompletely lnk lineF sf either of these ours in the (le right nowD our ode will not respond wellF e ould (x this in our urrent version y dding some extr logiD ut s long s we re good with just skipping the lnksD it is esier to do this with for loops nd if gurdsF

def dataGrid(lines:Iterator[String],delim:String):Array[Array[Double]] = { (for(l <- lines; if(!l.trim.isEmpty)) yield { for(n <- l.split(delim); if(!n.trim.isEmpty)) yield n.trim.toDouble }).toArray }
he if gurds mke it esy to skip things tht don9t (t wht we wntF sn this seD wht we wnt is tring tht isn9t emptyF he trim method on tring gives k new tring with ll leding nd triling white spe removedF

9.3.3 Reading from Other Things


yne of the nie things out the slFioFoure ojet is tht it hs more thn just the frompile method for us to use in reding (lesF sndeedD there re quite few di'erent methods tht strt with from in slFioFoureF e9ll only onsider one of them here though you n ertinly go to the es to look t othersF he one you might (nd most interesting is the fromv@sXtringA methodF v stnds for niform esoure votor nd they re the things tht

CHAPTER 9.

TEXT FILES

IWW

you type into the ddress r of we rowserF ou ll this method pssing it v s tringD very muh like wht you would put in the we rowserF his mkes it remrkly esy to hve your progrm red informtion o' of the weF por exmpleD exeuting the following line will give you k the ontents of my we pge s tringF

Source.fromURL("http://www.cs.trinity.edu/~mlewis/").mkString
ou n do everything with this oure tht you would do with oure from (leF vike with the (leD the oure is n stertor so you n only red through it one without lling resetF his lso mkes sense euse if there is nything slower on modern omputer thn reding from hrd diskD it is reding informtion from the weF

9.3.4 Other Options (Java Based)


he dvntge of using slFioFoure with getvines is tht you get l sed itertor tht hs ll the methods you hve gotten used to in working with the vist nd erry typesF roweverD tht doesn9t men tht oure is lwys your est optionF por mny situtionsD you might (nd tht the jvFutilFnner lss is etterF he jvFutilFnner lss hs methods for reding spei( types of dt s well s for heking if there re spei( types of dt villeF rere is smpling of the methods tht re villeF

hsxext@AXfoolen E ghek to see if there is nother wordF hsxexthoule@AXfoolen E ghek to see if there is houle redy to redF hsxextsnt@AXfoolen E ghek to see if there is n snt redy to redF hsxextvine@AXfoolen E ghek to see if there is line of text redy to redF next@AXtring E ed the next wordF nexthoule@AXhoule E ed the next houleF nextsnt@AXsnt E ed the next sntF nextvine@AXtring E ed the next line of textF usehelimiter@ptternXtringA E ghnge the pttern used for the delimiterF
his list should e firly selfEexplntoryF he only think one might wonder out is why word is in quotesF he reson for this is re)eted in the lst method listedF hen you wnt to red word with nnerD it will red up to the next delimiterD whtever tht hppens to eF fy defult it is ny grouping of white speF sn order to use nnerD you hve to mke oneF o do this you proly wnt to import jvFutilFnner nd use the following expressionF

CHAPTER 9.

TEXT FILES

PHH

new Scanner(file )
he le needs to e n expression tht hs the type jvFioFpile whih we will lso mke with new expression nd proly lso wnt to importF utting this togetherD you ould put something like this into progrm to red nd print unh of sntsF

import java.util.Scanner import java.io.File val sc=new Scanner(new File(numbers.txt)) while(sc.hasNextInt) { println(sc.nextInt()) }
he hoie of printing here omes from the ft tht the nner doesn9t niely produe l olletionF ou n get the vlues into olletionD ut it will typilly tke it more e'ortF ou should lso rememer to lose your nners when you re done with themF sf they link to (leD they re holding onto vlule resouresF

9.4 Writing to File


l doesn9t provide ny funtionlity for writing to (leF ht is something tht is lredy well supported y tv nd dding l lirries hs not yet een seen s providing signi(nt ene(tF here re mny wys to set up (le to write to in tvF he esiestD nd the one tht we will useD is the jvFioFrintriterF e n mke new rintriter with new nd telling it the nme of the (le we wnt to write to s the only rgumentF o we n get rintriter tht we n use for doing output with this odeF

import java.io.PrintWriter val pw=new PrintWriter(output.txt)


xow we ould ll methods on pw tht will use things to e written to tht (leF ou n use print nd println methods to print to the (le in muh the sme wy tht you hve een using those funtions in l to print to stndrd outputF sing this we ould write the following ode to print IHH rndom points with x nd y vlues etween H nd I with the following odeF

for(i <- 1 to 100) { pw.println(math.random+ +math.random) } pw.close


he lst line is ritil euse the rintriter is lso u'eringD just like the fu'eredoureF roweverD it holds things in memory until there is enough to

CHAPTER 9.

TEXT FILES

PHI

mke it worth writing to the diskF sf you don9t lose the (leD the text in the u'er won9t hve een written outF sf you ren9t done with the (leD ut you wnt to mke sure tht wht you hve written goes into the (leD you n use the )ush methodF

pw.flush
hen you ll thisD nything in the u'er will e written outF his wy if the omputer rshesD loses powerD or something else goes wrongD tht informtion will e out of the voltile memoryF

9.4.1 Appending to File


greting rintriter in the wy just desried hs the side e'et tht it will either rete new (le or delete nd existing one nd write over itF sf there is n existing (le nd you wnt to ppend to the end of it insted of overwriting itD there is one more step tht needs to e ddedF snsted of simply tell the rintriter wht (le nme to useD we tell it jvFioFpileriter to useF hen we rete pileriter we n tell it the (le nme nd lso give it foolen vlue tht tells it whether or not to ppendF sf the foolen vlue is trueD the ontents of the existing (le will e left in ple nd nything else written will go to the end of the (leF sf it is flse it will ehve like wht we hd eforeF o if you wnted to ppend to the outputFtxt (le you ould do the followingF

import java.io.{FileWriter,PrintWriter} val pw=new PrintWriter(new FileWriter(output.txt,true))

9.5 Use Case: Simple Encryption


o demonstrte the use of (lesD we will write some very si enryption nd deryption sriptsF et this point we won9t e using ny serious ryptogrphy methodsF yver time we n uild our wy up to thtF por now we will work with some simpler methodsF hey will proly stop others from reding your stu'D ut you wouldn9t wnt to use them to ess your nk ountsF

9.5.1 Command Line Arguments


he pproh tht we re going to tke is to write sripts tht llow us to speify ll the informtion neededD inluding the nmes of the input nd output (lesD on the ommnd lineF sn order to do this we need to disuss how we n get the ommnd line rguments into our progrms in lF hen you run progrm s sript in lD nything tht ppers on the ommnd line fter the nme of the sript (le is ville in the progrm s n element of the rry rgsD whih hs the type errytringF e n get the vlues out of this rry the sme wy we would ny other rryF ou n refer to rgs@HA to get the (rst rgument fter the (le nmeD rgs@IA to get the

CHAPTER 9.

TEXT FILES

PHP

seondD nd so onF e simple exmple to illustrte the use of rguments would e sript tht onverts two rguments to doules nd dds themF

println(args(0).toDouble+args(1).toDouble)
sf we put this into (le lled ddFsl we ould ll it with the following ommnd on the ommnd lineF

scala add.scala 88 12
his would print IHHFH s the sumF he deiml point ppers euse the strings were onverted to houle nd so the sum is houle nd prints s houleF

9.5.2 Mapping a File


o strt o' withD we will write sript tht uses two ommnd line rguments for the input (le nme nd the output (le nmeF he hert of the sript is funtion tht will red (le nd write modi(ed (le using funtion tht is pssed in s prmeter to mp from the hrter red to the one printedF o mke it so tht the formtting is resonleD the trnsform funtion will only e lled for hrters tht re in the lphetD whether they re upperse or lowerseF his will leve white spe nd puntution inttF uh funtion ould e written in the following wyF

def mapFile(inFile:String,outFile:String,trans:Char=>Char) { val pw=new PrintWriter(outFile) val in=Source.fromFile(inFile) for(c <- in) { pw.print(if(c>='a' && c<='z' || c>='A' && c<='Z') trans(c) else c) } in.close pw.close }
wke sure you do the two loses t the end to len up things efore the funtion exitsF foth pw nd in re lol vriles so if you get out of this funtion you won9t hve ny wy to mnully lose themF his funtion ould e invoked with simple identity funtion to mke opy of (leF

mapFile(args(0),args(1),c=>c)
he funtion ab simply returns whtever is pssed into itF sf you put this in (le tht hs imports for oure nd rintriterD you n ll it from the ommnd line speifying two (le nmesD one tht exists nd one tht doesn9tD nd the ontents of the (le tht exists will e opied to the new (le nmeF

CHAPTER 9.

TEXT FILES

PHQ

9.5.3 Character Oset


e simple wy to mke it muh hrder for nyone to red wht it in your (le is to tke the hrters nd o'set them y spei(ed mount in the lphetF he simplest ode for doing this might look like the followingF

val offset=args(2).toInt mapFile(args(0),args(1),c=>(c+offset).toChar)


rere we onvert the third rgument to n integer nd then dd it to whtever hrter we re enryptingF his hs to e turned k into ghr with toghr euse doing rithmeti with the ghr type impliitly results in n sntF his is simple enough nd works well for oth enoding nd deodingF o deode messgeD simply use n o'set tht is the dditive inverse of wht you used originllyF he only thing lking in this is tht letters n e shifted out of the lphet mking them look it odd when the text is printedF his prolem n e resolved y hving the hrters wrp round the end of the lphetF o if the o'set would move the letter eyond 9z9D it is wrpped k to 99F imilrlyD we need to hndle the se where the o'set is wrpped efore 99F he esy wy to do this is with modulo opertorF he following ode will work for ny o'set lrger thn EPTF

val offset=args(2).toInt mapFile(args(0),args(1),c=> { if(c.isLower) ('a'+(c-'a'+offset+26)%26).toChar else ('A'+(c-'A'+offset+26)%26).toChar })


his ode is it more omplex euse it hs to di'erentite etween lowerse nd upperse letters so tht it knows wht to sutrt from the hrter to get vlue tht we n tke the modulo ofF his ode lso does something tht might look it odd to you t (rstF he funtion literl now inludes urly resF ememer tht the urly res just mke ode lok whih is n expression whose vlue is the vlue of the lst sttement in the ode lokF his lok only hs one sttementD n if expressionD ut putting it in lok helps to set it o' nd mke it esier to redF

9.5.4 Alphabet Flip


e slightly di'erent wy to lter the letters is to )ip the lphet roundF o 9z9 will eome n 99D 9y9 will eome 99D nd so onF his enoding doesn9t need n extr rgument for something like the o'setF s lso hs n interesting side e'et tht the trnsformtion is its own inverseF he ode to do this might look like the followingF

mapFile(args(0),args(1),c=> { if(c.isLower) ('a'+(25-(c-'a'))).toChar else ('A'+(25-(c-'A'))).toChar })

CHAPTER 9.

TEXT FILES

PHR

his hs the sme si struture of the norml o'set versionF st just doesn9t need to get n o'set nd it uses n djustment of PS minus the hrters position in the lphetF

9.5.5 Key Word


foth of the methods desried ove re fundmentlly esy to rk ssuming someone hs some ide out wht you re doingF por the o'set method they just need to know wht o'set you used nd they n proly (gure tht out if they get to look t deent smple of enoded textF por the lphet )ipping model ll they need to know is wht you re doing nd they n derypt ny messge you sendF o mke things little hrderD you n use key string to provide vrile o'setF he enoding strts with the (rst letter in the key string nd o'sets the messge hrter y the numer of positions tht hrter is ove 99F st then uses the seond letter in the key string to o'set the seond hrter in the messgeF his repets until the end of the key string is rehed s whih point it wrps k round nd strts using hrters t the eginningF gode tht does this is shown hereF

val key=args(2) val factor=args(3).toInt var keyIndex=0 mapFile(args(0),args(1),c=> { val offset=factor*(key(keyIndex)-'a')+26 keyIndex=(keyIndex+1)%key.length if(c.isLower) ('a'+(c-'a'+offset+26)%26).toChar else ('A'+(c-'A'+offset+26)%26).toChar })
his method needs oth key nd ftorF he ftor is requiredD euse deoding is done y pplying the sme key string with the negtive of the ftorF wost of the time the ftor should e either I or EIF he wy this ode is writtenD the key should only inlude lowerse lettersF efter it uses two rguments to rete the key nd the ftorD it then mkes mutle vrile for the index in the key string whih egins t zeroF he trnsforming funtion lultes n o'set using the vlue of the key t the index nd then inrements the index using modulo so tht the vlue wrps k round to zeroF he ode for lulting the new hrter is the sme s tht used for the (rst o'set methodF

9.5.6 Putting it Together


o mke more useful sriptD ll three of these pprohes n e put into single sript tht tkes n extr rgument to speify the style to e usedF he full ontents of suh sript re shown here inluding the imports nd repet of the mppile funtionF

CHAPTER 9.

TEXT FILES

PHS

import scala.io.Source import java.io.PrintWriter def mapFile(inFile:String,outFile:String,trans:Char=>Char) { val pw=new PrintWriter(outFile) val in=Source.fromFile(inFile) for(c <- in) { pw.print(if(c>='a' && c<='z' || c>='A' && c<='Z') trans(c) else c) } in.close pw.close } args(2) match { case "copy" => mapFile(args(0),args(1),c=>c) case "offset" => val offset=args(3).toInt mapFile(args(0),args(1),c=> { if(c.isLower) ('a'+(c-'a'+offset+26)%26).toChar else ('A'+(c-'A'+offset+26)%26).toChar }) case "flip" => mapFile(args(0),args(1),c=> { if(c.isLower) ('a'+(25-(c-'a'))).toChar else ('A'+(25-(c-'A'))).toChar }) case "key" => val key=args(3) val factor=args(4).toInt var keyIndex=0 mapFile(args(0),args(1),c=> { val offset=factor*(key(keyIndex)-'a')+26 keyIndex=(keyIndex+1)%key.length if(c.isLower) ('a'+(c-'a'+offset+26)%26).toChar else ('A'+(c-'A'+offset+26)%26).toChar }) }
his sript uses the third ommnd line rgument to tell it wht type of trnsE form funtion to useF eny informtionD like n o'set or key nd ftorD should e spei(ed in the rguments fter thtF

9.5.7 Primes and Real Cryptography


he type of ryptogrphy tht you would wnt for your (nnil trnstions involves signi(ntly more mth thn wht we hve just overedF sn prtiulrD rel ryptogrphy mkes extensive use of onepts from numer theoryF o

CHAPTER 9.

TEXT FILES

PHT

understnd nd write ryptogrphy lgorithms doesn9t require tht you hve full nd omplete knowledge of numer theoryF here re some key onepts tht you will need to understnd thoughF e9ll strt developing those little here nd dd onto it in future hpters with the ojetive tht you will e le to write ode for the e puliEkey enryption nd deryption system lter in the ookF he (rst onept we need to over is tht of prime numersF e prime numer is numer tht is only divisile y one nd itselfF o the sequene of primes egins s PD QD SD UD IID IQD IUD FFF ell the vlues tht were skipped in this sequene hve other divisorsF por exmpleD ll even numers greter thn two re divisile y two nd re therefore not primeF here re n in(nite numer of primes s you n esily prove tht there is no lrgest primeF his is done using proof y ontrdition where we strt y ssuming tht there is lrgest prime numerD ll it pn F sf tht is the lrgest prime then we ould list ll of the primes s p1 D p2 D p3 D FFFD pn F xow onsider this numerF
n

P =1+
i=1

pi = 1 + p1 p2 p3 ... pn

his numer is not divisile y ny of the pi vluesF o see thisD think of the vlue P 1 nd where other multiples of the primes re reltive to itF he nerest multiples of P will e P 2 nd P + 2F he nerest multiples of Q will e Q wy nd so forthF es suhD P will not e divisile y ny of the pi vlues nd must therefore e primeF ine P > pn the originl ssumption tht pn is the lrgest prime must e flseF xow tht we hve hd little refresher on primesD we n write some ode tht dels with primesF por this setion it will e su0ient to just write funtion lled isrime tht tells us whether or not numer is primeF hnks to the nge type nd the higherEorder methods present in lD this n e done in one lineF

def isPrime(n:Long):Boolean = (2L until n).forall(n%_!=0)


his ode tkes ll the numers etween P nd nEI nd heks whether n is divisile y ny of themF sf divides evenly into then 7aaHF es long s tht isn9t true for ny of the vlues etween P nd nEI then the numer is primeF his ode uses the type vong euse we relly wnt to hve the ility to use it on very lrge numersF hile this ode is esy to writeD it is lso somewht ine0ientD prtiulrly in the ses where n is primeF he reson is tht we relly don9t need to go up to nEIF sf there isn9t divisor less thn the squre root of nD there n9t e one ove thtF sf n were relly lrgeD the di'erene etween n nd the squre root of n would e signi(ntF e more e0ient funtion n e written in the following wyF

def isPrime2(n:Long):Boolean = {

CHAPTER 9.

TEXT FILES

PHU

var i=2 while(i*i<n+1 && n%i!=0) i+=1 n%i!=0

e nge type ould hve een used with squre root funtionD ut the mthFsqrt funtion works with houles tht introdues di0ulties we didn9t wnt to del with hereF yther improvements ould e mde to this funtion to speed it upF roweverD none of them would e fst enough to work with the truly huge numers tht rel ryptogrphy is done withF hnkfully we will see lter tht mthemtiins hve ome up with methods of testing if numer is prime tht re muh fster nd n e used on extremely lrge numersD inluding those muh lrger thn wht we n store in vongF

Self-Directed Study
inter the following sttements into the iv nd see wht they doF ome will produe errorsF ou should try to (gure out whyF ry some vritions to mke sure you understnd wht is going onF

scala> def succ(n:Int):Int = n+1 scala> succ(1)


333

Exercises
IF ixerise PF sf you did projet UFSD you n now modify it so tht it doesn9t hve to use input rediretionF wke funtion tht reds in the ditionry of words nd then write sript tht will llow the user to input rle letter sets until they enter speil vlue to stop the progrmF

Projects
IF here is utility in vinux lled w tht stnds for word ountF ou n run it on one or more (les nd it will tell you how mny linesD wordsD nd hrters there re in the (lesF por this ssignment option you will do the sme thingD only s lso wnt you to ount how mny time eh letter ours in eh (le @regrdless of seAF he (les you should work on will e spei(ed on the ommnd lineF our progrm should red through eh (le nd ount up how mny hrtersD wordsD nd lines there re s well hs how mny times eh letter oursF ou will print this informtion for eh (le followed y grnd totl for ll the (lesF our progrm might e invoked s 4sl wFsl BFtxt4D whih would go through ll the Ftxt

CHAPTER 9.

TEXT FILES

PHV

(les in the urrent diretoryF ou will onsider ny string tht is etween whitespes to e wordF o mke the ounting of letters esier try doing thisX deFmp@ ab E99A to see wht it does nd think out how tht n help youF PF fk in setion WFS we went through few simple forms of enryptionF hese might keep most people from reding your (lesD ut you wouldn9t wnt to mke hnges to your nk ount using themF he enryption tehniques tht re used for sending truly sensitive messges rely hevily on numer theoryF he most ommon systems tody re wht re lled puliEkey ryptosystemsF sn this type of systemD eh user hs oth some informtion tht they mke puliD the puliEkeyD nd some informtion they keep privteD the privteEkeyF por this projetD you will implement simple version of the e ryptosystemF he wy the e ryptosystem works is the followingX @A elet two prime numers p nd q suh tht p = q F he level of seurity of the system is dependent on how ig p nd q reF por good seurity you wnt them to e SIPEIHPR it numersD fr lrger thn wht you n store in n snt or even vongF sf you did exerise VFW you n use tht to generte lrge primesF ytherwise use two primes the multiply to give you numer etween IPV nd PSTF @A gompute n = pq F @A elet n smll odd integerD e,tht is reltively prime to (p 1)(q 1)F @dA gompute dD the multiplitive inverse of eD modulo (p 1)(q 1)F he tehnique for (nding this is desried in exerise VFIHF @eA he pir (e, n) is the e puliEkeyF ou nyone who wnts to send you messge know these vluesF @fA he pir (d, n) is the privteEkeyF ou need to know this to deode messge nd you don9t wnt nyone else to hve itF @gA o enode messgeD M D the sender uses P (M ) = M e mod nF por this to work you need to rek up the messge into hunks tht n e enoded into numersD M D tht re less then nF @hA o deode the messge you use S (C ) = C d mod nD where C is the enrypted messge you got from the senderF

Chapter 10

Case Classes
yne of the things tht you should hve notied t this point is tht there re times when it n e helpful to group piees of dt togetherF e hve seen two wys tht we n do thisF sf ll the dt is the sme typeD you ould use something like n rry or listF he down side of this is tht the ompiler n9t relly hek to mke sure tht you hve the right numer of elementsF por exmpleD if you wnt point in QEh with xD yD nd z oordintes then you would need n erryhoule tht hs three elements in itF rving more or less ould use the ode to rek nd l wouldn9t e le to hek for tht until the progrm ws runningF he lterntiveD whih lso works if the types of the vlues re di'erent is to use tupleF ht sme QEh point ould e represented s @houleD houleD houleAF hile this works resonly well for QEh pointD it too hs some signi(nt limittionsF he min limittion is tht eing @houleD houleD houleA doesn9t tell you nything out wht those three houles men or how it should e usedF o illustrte thisD onsider some di'erent things tht ould e represented s three houlesF yne is point in QEhF enother losely relted one is vetor in QE hF iither the vetor or the point ould e represented in grtesin oordintesD ylindril oordintesD or polr oordintes nd the tuple won9t tell you whih it isF he three houles though ould lso represent three suEverges for students grde in lssF por exmpleD they might e the testD quizD nd ssignment vergesF he tuple doesn9t tell you whih it is nd doesn9t help you t ll with keeping things strightF ht is moreD the tuple lks some )exiility nd the syntx for getting things out of them is less thn idelF glling the I nd P methods ll over the ple n mke ode di0ult to redF smgine if insted you wnted to represent full student in lssF hen the tuple might hve tring nd lrge numer of grdesD ll of the sme typeF ueeping trk wht numers re ssoited with wht grdes would very quikly eome very prolemtiF o get round these limittionsD we9ll onsider the use of se lsses in this hpterF

PHW

CHAPTER 10.

CASE CLASSES

PIH

10.1 User Dened Types


ht we relly need to rek wy from the limittions of using tuples to del with meningful groupings of dt is the ility to de(ne our own types tht hve meningful nmesF uples de(nitely hve their ple nd re very useful in those plesF roweverD there re mny times when it would e hndy to rete type spei(lly for prtiulr purposeF hen we ould give the type nme tht indited its purpose nd hve the ompiler hek for use tht we were using tht type in the proper wyF ser de(ned types re ommon feture in modern progrmming lnguges nd hve een for dedesF l provides three onstruts for reting user de(ned typesX lssesD tritsD nd singleton ojetsF por this hpterD in order to keep things simpleD we will only onsider spei( type of one of theseD the se lssF he others will e overed in detil when we onsider ojetEorienttion in fullF fk in UFS we de(ned type s olletion of vlues nd the opertions tht n e performed on themF he user de(ned types typilly tke the form of eing olletions of other typesF his mkes them fundmentlly similr to just using tupleF here they prove to e more thn just tuple is the ontrol they give you in determining wht n e done with the typesF e will remin somewht limited in this regrd for nowD ut even with those limittions you should (nd tht our user de(ned types provide signi(nt oost to our progrmming pilitiesF

10.2 Case Classes


he simplest wy to strt with user de(ned types in l is with se lssesF erhps the est wy to introdue them is to show some exmplesF e9ll strt with two tht were mentioned oveX QEh point nd student with some grdesF

case class Point3D(x:Double,y:Double,z:Double) case class Student(name:String,assignments:List[Double],tests:List[Double], quizzes:List[Double])


he (rst one delres type lled ointQh tht stores inside of it three di'erent houles tht re nmed xD yD nd zF he seond delres type lled tudent tht hs nme s tring nd three di'erent lists of houle to use s grdesF here n e more to the delrtion of se lssD ut for now we will limit ourselves to this syntx tht egins with the keywords se lssF efter tht is the nme you wnt to give the typeF his ould e ny vlid l nmeD ut it is ustomry to egin type nmes with upperse letters nd use mel nming so ll susequent words lso egin with upperse lettersF efter tht is list of nmeD type pirs in prenthesesF he formt of these is just like the rguments to funtionF he elements of this list give the nmes nd types of the vlues stored in this new typeF

CHAPTER 10.

CASE CLASSES

PII

10.2.1 Making Objects


efter you hve delred typeD you need to e le to rete ojets of tht typeF ith se lssD you n do this with n expression tht hs the nme of the lss followed y n rgument listD just like funtion llF he two lsses listed ove ould e reted nd stored in vriles with the following lines of odeF

val p=Point3D(1,2,3) val s=Student("Mark",Nil,Nil,List(89))


he (rst line mkes point tht hs xaID yaPD nd zaQ nd stores referene to it in vrile nmes pF he next line mkes student with the nme wrk who hs no ssignment or test grdesD ut who hs n VW on one test nd stores referene to it in vrile nmed sF ou ould insert the word new nd spe fter the equls signs so tht these lines look like the followingF

val p=new Point3D(1,2,3) val s=new Student("Mark",Nil,Nil,List(89))


he result of this would e extly the smeF he (rst syntx is shorter nd works for ll se lsses so we will stik with tht in our smple odeF

10.2.2 Accessing Elements


sn order to e le to use these ojetsD we must e le to ess the di'erent elements in themF his is very simple to doD just use the dot nottion to ess the elementsF o if you wnt the x vlue in the ointQh p tht we mde ove you would just do thisF

scala> p.x res1: Double = 1.0


o get the nme of the student you would do thisF

scala> s.name res2: String = Mark


he dot nottion in l simply mens tht you re using something from inside of n ojetF st ould e method or vlue tht is stored in the ojetF por now we will only e onerning ourselves with the vlues tht we store in our se lssesF e ould put this to use y writing funtion to (nd the distne etween two pointsF st might look something like thisF

def distance(p1:Point3D,p2:Point3D):Double = { val dx=p1.x-p2.x

CHAPTER 10.

CASE CLASSES

PIP

val dy=p1.y-p2.y val dz=p1.z-p2.z math.sqrt(dx*dx+dy*dy+dz*dz)

e ould lso use it to lulte nd verge for student with ode like thisF

def classAverage(s:Student):Double = { val assnAve=if(s.assignments.isEmpty) 0.0 else s.assignments.sum/s.assignments.length val quizAve=if(s.quizzes.length<2) 0.0 else (s.quizzes.sum-s.quizzes.min)/(s.quizzes.length-1) val testAve=if(s.tests.isEmpty) 0.0 else s.tests.sum/s.tests.length 0.5*assnAve+0.3*testAve+0.2*quizAve }
he if expressions here prevent us from doing division y zeroF yne of the things to note out se lsses is tht the elements in them re vlsF es suhD you n9t hnge wht they refer toF sf you try to mke suh hnge you get something like the followingF

scala> p.x=99 <console>:8: error: reassignment to val p.x=99 ^


hether you n hnge nything in n ojet reted from se lss depends on whether the things in it re mutle or notF sn our two exmplesD ll of the ontents re immutleF es resultD the se lss s whole is immutleF yne you rete ointQh or tudentD the ojet you rete n not hnge its vlue in ny wyF roweverD if one or more of the (elds in the se lss were n rryD then the vlue in the rry would e mutleF ou wouldn9t e le to hnge the size of the rry without mking new ojetD ut you ould hnge the vlues stored in the rryF

10.2.3 Copy Method


he ft tht you n9t mutte the vlues in se lss mens tht it would e helpful to hve wy to mke new se lss ojets tht re only slightly hnged from othersF o see thisD onsider wht hppens when you wnt to dd new grde to tudentF he grdes re in lists so it is esy to dd to listD ut tht doesn9t mutte wht is in the ojetD it just gives us new list tht inludes the new vlues s well s wht ws lredy thereF o help get round this prolemD se lsses ome with opy methodF he opy method is intended to e used with the nmed rguments tht were disussed in setion RFUF he rguments to opy hve the sme nmes s the

CHAPTER 10.

CASE CLASSES

PIQ

(eldsF sing nmed rgumentsD you only provide the ones you wnt to hngeF enything you leve out will e opied stright over to the new ojetF o using the student ojet we gve the nme s oveD we ould use opy to do the followingF

val ns=s.copy(tests=99::s.tests)
his gives us k new tudent who is the sme s the one we hd in sD only it hs test grde of WW in ddition to the quiz grde of VW it hd originllyF ou n speify s mny or s few of the (elds in the se lss s you wntF htever (elds you give the nmes of will e hnged to the vlue tht you speifyF sf you leve the prentheses emptyD you will simply get opy of the ojet you hve originllyF

10.3 Mutable Classes


gse lsses ren9t the only option you hve when reting lssesF e will go into the full detil for lsses in hpter IUF here re some pplitions for whih you don9t need the full power the lsses n provideD ut you would like to hve (elds in the lss tht re mutleF emeer tht every (eld in se lss is like vl so the se lss is itself immutleF he only wy the vlue of something in se lss n hnge is if one of the (elds referenes mutle vlue like n rryF hen you wnt to mke ojets with mutle (eldsD you need to leve o' the se keyword nd just de(ne lssF o e le to use the (eldsD given wht you urrently knowD eh one will need to e preeded y either vl or vrF sf you put vl efore (eld its vlue won9t e llowed to hngeF sf you use vrD the (eld will e llowed to hngeF o if you hve ojets tht turly need to e ltered euse they hnge very rpidly nd modi(ed opies ren9t e0ientD you n mke lss using vr for eh (eld tht needs to hngeF xote tht y leving o' the se keywordD you do more thn just llow for vr (eldsF ou lso lose the opy method nd you lose some other fetures of se lsses tht won9t e ddressed until lterF sn generlD there re mny ene(ts to immutility so you shouldn9t tke this pproh without good resonF

10.4 Putting it Together


xow we wnt to use se lss long with other things tht we hve lerned to rete smllD text sed pplitionF he pplition tht we will write will use the tudent tht we de(ned erlier long with the lsseverge funtion nd other funtions tht we will write to mke grde ookF his progrm will e run from text menu nd give us vrious options similr to wht ws done in setion VFPF he progrm will lso use the (le hndling pilities tht we hve lerned so tht the grdes of the students in the ourse n e sved o' nd then e

CHAPTER 10.

CASE CLASSES

PIR

loded k in when we restrt the progrmF he menu for the progrm will hve the following optionsX IF edd est qrde PF edd essignment qrde QF edd uiz qrde RF rint everges SF ve nd uit hen progrm will tke ommnd line rgument for the (le to lod inF sf none is givenD the user will e sked how mny students re in the setion nd their nmes long with the (le nme to sve it underF hen one of the (rst three menu options is seletedD the progrm will list eh student9s nme nd sk for their grdeF he rint everges option will print out the nmes of eh student long with their grdes in eh reD their verge in tht reD nd their totl vergeF here is quite it to this progrm so it is worth reking it up into di'erent funtions nd then writing eh of thoseF o do this we n outline wht will hppen when we run the progrm nd use the outline to rek things down then ssign funtion nmes to thingsF

trtup

 lod (le @lodetionA  or rete setion @reteetionA


win menu @minwenuA

 print the menu @printwenuA  t on the seletion



dd test grde @ddestA dd n ssignment grde @ddessignmentA dd quiz grde @dduizA print the verges @printevergesA

ve when done @sveetionA


xow tht we hve (gured out roughly wht we need to doD we n write these funtions in ny order tht we wntF sn generl the proess of writing funtions like this n e very nonElinerF ou should not feel ny reson why you would hve to go through the funtions in ny prtiulr orderF yften in rel projet you would do things in ertin order s you (gure out how to do themF he more experiene you ginD the more omfortle you will e in writing ode nd then you might deide to pik ertin funtions euse they will give

CHAPTER 10.

CASE CLASSES

PIS

you funtionlity tht you n testF yne of the dvntges of hving the iv to fll k on is tht we n lod in our (le nd test funtions one y oneD seeing the results long the wyF ithout thtD the printeverges funtion would prove to e extremely importnt to us s it would e the only wy tht we ould see wht ws going onF por our purposes we will strt with reteetion nd sveetionF hese two funtions pir well together nd re losely relted euse we hve to deide how we re going to represent setion oth in the memory of the omputer nd in the (leF e9ll strt with reteetion nd the wy in whih things re represented in the memory of the omputerF e hve lredy reted se lss lled tudent tht n e used to represent one student in the setionF e just need unh of themF e lso need to relize tht they will hnge over time s grdes re ddedF st would proly e su0ient to just keep n errytudentF here re ene(ts to tully wrpping the rry inside of di'erent se lss like thisF

case class Section(students:Array[Student])


yne dvntge for our purposes here is tht this is hpter on se lsses nd this provides yet nother exmple of oneF sn generlD this n lso provide greter )exiilityF e might deide t some point tht we wnt to tth dt for ourse nmeD semesterD instrutorD etF to eh etionF hose things n9t e dded to simple erryF roweverD they ould esily e dded to the se lssF st lso hs the dvntge of providing extr meningF his isn9t just rndom olletion of studentsD it represents setion of lssF xow tht we know thisD we n write the reteetion funtionF his funE tion will prompt the user for the informtion tht is needed to rete the setionF por now tht is (le nme to sve it toD the numer of studentsD nd the nmes of the studentsF he funtion will return the (le nme nd the etionF

def createSection:(String,Section) = { println("What file would you like to save this as?") val fileName=readLine() println("How many students are in the class?") val numStudents=readInt() println("Enter the student names, one per line.") (fileName,Section(Array. fill(numStudents)(Student(readLine(),Nil,Nil,Nil)))) }
he (rst (ve lines of this funtion re firly selfEexplntory with prompts eing printed nd vlues eing redF efter tht is the return tuple whih inludes ll to erryF(llD whih hs redvine in the pssEyEnme prmeterF his mens tht it not only mkes the return vlueD it lso inludes the input of the nmesF xow tht we hve reted new setionD we n onsider wht it will look like in (leF here re mny di'erent wys tht the (le ould e formttedF

CHAPTER 10.

CASE CLASSES

PIT

he mnner tht we will pik here strts with the numer of students in the lss on lineF efter tht there re four lines for eh studentF hey re the student9s nme followed y line eh with ssignmentD testD nd quiz grdesF his funtion n e written s followsF

def saveSection(fileName:String,section:Section) { val pw=new PrintWriter(fileName) pw.println(section.students.length) for(s <- section.students) { pw.println(s.name) pw.println(s.assignments.mkString(" ")) pw.println(s.tests.mkString(" ")) pw.println(s.quizzes.mkString(" ")) } pw.close() }
he funtion tkes the (le nme nd the setionF st then mkes rintriter with the (lexmeD whih is losed t the end of the funtionD nd prints the needed informtionF he use of mktring on the di'erent lists mkes the ode for doing this muh shorterF es you re writing these funtionsD you need to test themF yne wy to do tht is to lod them into the iv nd ll themF enother wy is to end the sript with lls to themF et this pointD the end of the sript might look something like the followingF

val (fileName,section)=createSection saveSection(fileName,section)


his omes fter the de(nition of oth the se lsses nd the di'erent funE tionsF sf you run the sript with this in itD you should e prompted for the informtion on the setion nd fter you enter the the sript should stopF ou n then look t the (le tht you told it to sve s nd mke sure it looks like wht you would expetF e9ll hold the lodetion funtion until the end nd go into the min funE tionlity with minwenu nd printwenuF ou n write them in the following wyF

def printMenu { println("""Select an option: 1. Add Test Grade 2. Add Assignment Grade 3. Add Quiz Grade 4. PrintAverages 5. Save and Quit""") } def mainMenu(section:Section) {

CHAPTER 10.

CASE CLASSES

PIU

var option=0 do { printMenu option=readInt() option match { case 1 => addTest(section) case 2 => addAssignment(section) case 3 => addQuiz(section) case 4 => printAverages(section) case 5 => println("Goodbye!") case _ => println("Invalid option. Try again.") } } while(option!=5)

ou n9t test this ode yet euse minwenu lls four other funtions tht hven9t een written yetF yne we hve those writtenD we n put ll to minwenu t the end of the sript right efore the ll to sveetionF he three di'erent dd funtions will ll look pretty muh the smeF e9ll only show the ddest funtion nd let you (gure out the othersF st is worth thinking it out how tht funtion will work thoughF he tudent type is immutleF ell the (elds in the se lss re vls so they n9t e hngedF he tring nd the three di'erent vistsnt vlues re ll immutle so one tudent is retedD it is set foreverF he etion type stores the students in n rry thoughF o we n hnge wht student ojets re eing referred toF e n use the opy pilities of the se lss to mke new instnes tht re lmost the sme exept for smll vritionsF sing thisD the ddest funtion ould e written in the following wyF

def addTest(section:Section) { for(i <- 0 until section.students.length) { println("Enter the grade for "+section.students(i).name+".") section.students(i)=section.students(i). copy(quizzes=readInt()::section.students(i).quizzes) } }
his ode works just (neD ut it is it verose euse we hve to type in setionFstudents@iA so mny timesF e hve to hve the index euse we need to e le to do the ssignment to n element of the rryF he setionFstudents@iA efore the equls sign in the ssignment is hrd to get rid of euse we hve to mutte tht vlue in the design of this odeF he ode ould e shortened with pproprite use of importsD ut there is notherD more interesting solutionF

def addTest(section:Section) { for((s,i) <- section.students.zipWithIndex) { println("Enter the grade for "+s.name+".")

CHAPTER 10.

CASE CLASSES

PIV

section.students(i)=s.copy(tests=readInt()::s.tests)

his version uses zipithsndex nd pttern on the tuple to give us oth short nme for the studentD sD nd n index into the rryD iF foth of these re eqully orret so use the one tht mkes more sense to you nd duplite it for ssignments nd quizzesF he next funtion in the menu is printevergesF e very si implementtion of this would just print student nmes nd the ourse vergeF roweverD it ould e helpful to see ll the grdes nd the prtil verges s wellF ht is wht is done in this versionF

def printAverages(section:Section) { for(s <- section.students) { println(s.name) val assnAve=if(s.assignments.isEmpty) 0.0 else s.assignments.sum/s.assignments.length println(s.assignments.mkString("Assignments:",", "," = "+assnAve)) val quizAve=if(s.quizzes.length<2) 0.0 else (s.quizzes.sum-s.quizzes.min)/(s.quizzes.length-1) println(s.quizzes.mkString("Quizzes:",", "," = "+quizAve)) val testAve=if(s.tests.isEmpty) 0.0 else s.tests.sum/s.tests.length println(s.tests.mkString("Tests:",", "," = "+testAve)) println("Average = "+(0.5*assnAve+0.3*testAve+0.2*quizAve)) } }
his funtion uses the ode from the erlier lss verge funtion nd inserts some print sttementsF he only thing in here tht might seem odd is the use of mktring method tht tkes three rguments insted of just oneF ith this longer versionD the (rst string goes efore ll the elements nd the third one goes fter ll the elementsF he rgument in the middle is the delimiter s it hs een in previous usgeF

def loadSection(fileName:String):(String,Section) = { val src=Source.fromFile(fileName) val lines=src.getLines val section=Section(Array.fill(lines.next().toInt)(Student( lines.next(), lines.next().split(" ").filter(_.length>0).map(_.toDouble).toList, lines.next().split(" ").filter(_.length>0).map(_.toDouble).toList, lines.next().split(" ").filter(_.length>0).map(_.toDouble).toList ))) src.close (fileName,section) }

CHAPTER 10.

CASE CLASSES

PIW

his funtion inludes three lines for hndling the (leF he met of the funtion is in the delrtion of the setion vrile whih lls linesFnext@A nytime tht it needs new line from the input (leF he (rst time is to red how mny students re in the setion for uilding the rryF ih student pulls in four lines for the nme nd three di'erent grde typesF he lines of grdes re splitD (lteredD nd them mpped to houles efore they re onverted to listF he (lter is required for the sitution where you hven9t entered ny grdes of prtiulr typeF ou might wonder why the return type of this funtion inludes the (lexme tht ws pssed inF ehnilly this isn9t requiredD ut it mkes this funtion integrte muh more niely t the ottom of the sriptF

val (fileName,section)=if(args.length<1) createSection else loadSection(args(0)) mainMenu(section) saveSection(fileName,section)


rving reteetion nd lodetion return the sme informtion gretly simE pli(es this prt of the ode s they n e lled together in simple if expresE sionF ht is everythingF ou now hve full little pplition tht ould e used to store grde ook for some ourseF ry putting this ode in nd plying with it whileF

10.5 Tuple Zipped Type (Advanced)


omething tht you need to do firly frequently is to run through two olletions t the sme timeD pulling items from the sme lotion of ehF yne wy to do this is to use the zip method to zip the olletions together into new olletion of tuplesF hile this works well if you hve two olletionsD espeilly if you use forEloopD it doesn9t work s well for three or more olletions nd it is fundmentlly ine0ient euse the zip method will go through the e'ort of reting rel olletion with unh of tuples in itF o get round these limittionsD eh tuple type hs type ssoited with it lled ippedF he sole purpose of the ipped type is to let you get the ene(ts of running through zipped olletion without tully doing the zippingF o get n instne of the ipped typeD simply mke tuple tht hs ll the olleE tions you wnt in it nd ll the zipped methodF he ipped type hs some of the min higher order methods tht you re used to using on olletionsF

exists (lter )twp forll

CHAPTER 10.

CASE CLASSES

PPH

foreh mp
he di'erene is tht in the ipped type they tke multiple rgumentsF peifE illyD they tke s mny rguments s there re elements in the tupleF his is signi(nt euse if you ll funtion like mp tht is mpping olletion of tuples the funtion hs to tke one rgument nd go through some e'ort to pull the elements out of the tupleF ith the ipped type you don9t hve to do tht s the funtion literls re supposed to tke multiple rguments insted of single tuple with the multiple vluesF e omprison of the two pprohes is shown hereF

val l1=List(1,2,3) val l2=List(4,5,6) l1.zip(l2).map(t => t._1*t._2) (l1,l2).zipped.map((v1,v2) => v1*v2)
por this exmple the (rst one is it shorterD ut tht typilly won9t e the seF wore importntlyD the (rst one relies on the I nd P methods whih will mke the ode hrd to red nd understnd for nything with more logiF o get the ene(t of esy to red nmes using zip you would hve to do the followingF

l1.zip(l2).map(t => { val (v1,v2)=t v1*v2 })


st remins n exerise for the reder to see wht hppens if you wnt to iterte over three or more olletions using zipF o onsider the ipped type when you need to iterte over two or more olletions t the sme timeF

Self-Directed Study
inter the following sttements into the iv nd see wht they doF ome will produe errorsF ou should try to (gure out whyF ry some vritions to mke sure you understnd wht is going onF

scala> def succ(n:Int):Int = n+1 scala> succ(1)


333

Exercises
IF ixerise

CHAPTER 10.

CASE CLASSES

PPI

PF eEwrite the grde ook progrm in ompletely funtionl wy so tht it hs nor vrs or mutle ojetsF QF ly with zip using QC olletionsF

Projects
IF his is n extension on projet WFQF xow tht you hve rrysD you n do it more with the ueplerin simultorF sn tht progrm ll you hd ws one ody in motion out 4entrl mss4 tht wsn9t relly moving t llF xow you n store nd work with the positions nd veloities of mny odies euse you n store their omponent dt in rrys or se lssesF ht is to sy you n hve n rry for x positions s well s yD vx nd vyD or n rry of some se lss tht stores those vluesF his llows you to simulte the motions of mny prtiles t the sme time whih is muh more funF irlier you only hd to lulte the elerE tion due to the entrl prtileF xow you wnt to lulte elertions due to ll intertions etween ll the prtilesF e n lso mke the entrl prtile one of the prtiles in our rryF @sf we were doing glti dynmis we wouldn9t hve entrl odyD ut tht9s di'erent issue ll togetherFA ith multiple prtilesD we need to hve nested loop @or for loop with two genertorsA tht lultes the elertions on eh prtile from ll the others nd dds them ll upF ueep in mind tht if prtile i pulls on prtile j then prtile j pulls k on i just s hrdD ut in the opposite diretionF ht doesn9t men the elertions re the sme thoughF he elertion is proportionl to the mss of the puller euse the mss of x the pullee is neled out y its inertiF irlier we hd ax = d 3 nd y ay = d3 F hen the prtile doing the pulling isn9t t the originD d is the distne etween the prtiles nd x nd y re the distnes etween them in x nd y diretionsF e lso need ftor of m for the mss of the pullerF ou wnt to dd up the elertions from ll other prtiles on eh one nd store tht into rrys so

ax (i) =
j

(xj xi ) mj d3 ij

here is similr formul for yF he dij vlue is the distne etween prtile i nd prtile jF elso note tht given vlueD vD the est wy to ue it is vBvBvD not mthFpow@vDQAF hen you write your formul in the odeD think it out itF his formul uses prolem if we relly use d euse prtiles n get too lose to one notherF s suggest you mke dasqrt@dxBdxCdyBdyACsomething smllF ou n ply with how smll you wnt it to e euse tht depends on the sle of your proE lemF s lso reommend tht you hve your integrtor not use the norml

CHAPTER 10.

CASE CLASSES

PPP

iuler method whih lultes elertionsD then updtes positionsD then veloitiesF wke sure tht it does the elertions on veloities efore pplying the veloities to the positionsF ueep in mind tht you wnt to rek this up into funtions tht (t together niely nd re helpfulF st will hurt your rin more if you don9tF

he input for the progrm will hve (rst line tht is the numer of odE iesD timestepD stopping timeD nd the numer of steps etween outputsF his will e followed y lines with the xD yD vxD vyD nd mss vlues for eh prtileF e smple input (le n e found t httpXGGwwwFsFtrinityFeduG~mlewisGlfookGghpterIHGph xote tht the entrl mss hs mss of I nd ll the others re muh smllerF es outputD you should write out the positions of ll the prtiles in your simultion to (le one for every n steps where n is vlue given on the (rst line of the inputF sf you do this then you n run gnuplot nd give it the ommnd plot 9output9 nd it will mke little stter plot showing you the pths of the prtiles in the simultionF e smple output is vilE le t httpXGGwwwFsFtrinityFeduG~mlewisGlfookGghpterIHGphysisFoutF PF his projet uilds on top of projet VFIF ou hve likely een using tuples or seprte vlues to represent the geometry elements in your ry trerF his is informtion tht is muh more nturlly represented s se lssF por this projet you should go through nd edit your existing ode so tht it inludes three di'erent se lssesD one for spheresD one for plnesD nd one for sene whih hs vistphere nd vistlneF QF his is the (rst instllment for you uilding your own text dventureF our progrm will red in from mp (le tht you will write y hnd nd let the user run round in tht mp y using ommnds like 4north4 to move from one room to notherF he mp (le will hve firly simple formt right now nd you will rete your own mp (le using viF wke sure when you turn in this progrm you turn in oth the sript nd the mp (le so it n e tested with your mpF he formt of the mp (le should strt with line telling the numer of rooms then hve something like the followingF ou n hnge this some if you wnt to use slightly di'erent formtX roomnumer roomnme long line of room desription numeroflinks diretionI destintionI diretionP destintionP FFF his is repeted over n overF @he numer of rooms t the top is helpful

CHAPTER 10.

CASE CLASSES

PPQ

for storing things in n erry so tht you know how ig to mke itFA ih room should hve unique room numer nd they should strt t HF he reson is tht you will e putting ll the room informtion into rrysF here is link elow to smple mp (leD ut you don9t hve to stik extly to tht formt if you don9t wnt toF ou might devite if you re thinking out other options you will dd in lterF ydds re good you will e reftoring your ode for lter projetsF he interfe for your progrm is quite simpleF hen you run the progrm it should red in the mp (le nd keep ll the mp informtion stored in n erryoom where oom is se lss you hve mde to keep the signi(nt informtion for eh roomF ou will strt the user in room H nd print the desription of tht room nd the di'erent diretions they n go s well s where those exits led toD then follow tht with promptF ou ould just use 4b4 s the prompt to strt withF st might get more omplex lter on when you hve rel gme funtionlityF o when the user strts the gme it might look something like this if you red in the smple mp (leF rlsell PPV ou re stnding in room full of omputers nd omfy hirs with gint ir onditioning unit hnging from the eilingF hile the surroundE ings re serine enoughD you n9t help feeling ertin mount of dredF his isn9t just fer tht the ir onditioning unit is going to fll eitherF omething in you tells you tht this room is regulrly used for strnge rituls involving tortureF ou n only wonder wht hppens here nd why there isn9t lood ll over the pleF our unesyness mkes you wnt to leve quiklyF he hllwy is estF b he user must type in either diretion to move or 4quit4F sf nything else is entered you should print n pproprite error messgeF e smple mp (le n e found t httpXGGwwwFsFtrinityFeduG~mlewisGlfookGghpterIHGmpFtxtF

Chapter 11

GUIs
o frD ll of the progrmming tht we hve done hs een prt of text interE feF he progrms print informtion to terminl window nd to give them input we enter textF hese types of progrms hve their ple in omputingD ut these dys very few people tully use suh progrmsF hey typilly run in the kground insted doing things tht people don9t seeF he progrms tht you re likely used to working with re more grphilF hey open up windows nd you n intert with them through mouse liks s well s typingF his type of progrm is sid to e qs @qrphil ser snterfeAF sn this hpter we will look t how we n write qss in l nd get them to intert with the userF

11.1 GUI Libraries and History


here re resons why we egn doing our progrmming with the onsoleF here re ertin omplitions involved in progrmming qssF ome of tht is inE herent to the mediumF sn lD some of tht is due to historyF l relies on the underlying virtul mhine nd the lirries for it to do lot of the work in qsF l simply dds things on top when it is possile to improve them in signi(nt wy y doing soF sn the implementtion of l tht we re usingD this mens tht there is dependene on the tv qs lirriesF hen tv ws originlly relesedD there ws one qs lirry lled the estrt indowing oolkitD eF he e lirry mkes diret lls to the operting system or windowing environment for uilding elements of the qsF his gve the e signi(nt ene(t in speedF roweverD it lso provided signi(nt limittionF hue to the rossEpltform nture of tvD they only inluded elements in the e tht were present on virtully ll pltformsF hey re the most fundmentl prts of qs onstrution like windowsD uttonsD text oxesD etF hese elements were drwn y the underlying pltform nd lwys looked like the underlying pltformF foth the restrition in pperne nd the limited numer of omponent PPR

CHAPTER 11.

GUIS

PPS

types led to the retion of seond qs lirry for the tv stndrdF his seond lirry ws lled wing nd it ws pure tv lirryF ht mens tht ll the ode in wing ws written in tvF st uses lls to e to mke things hppenD ut doesn9t diretly ll nything tht isn9t in tv itselfF he wing lirry inludes lot of di'erent qs elements tht re more powerful nd )exile thn wht ws provided in eF st lso inludes the ility to hve elements of the qs rendered in di'erent wys so they don9t hve to look just like the underlying systemF yriginlly this )exiility me t signi(nt ost in speedF yver time vrious optimiztions hve een mde nd now wing runs perfetly (ne ssuming the progrmmer doesn9t do nything silly to slow it downF l hs its own lirry tht is wrpper round wingF st is mking lls to wing nd we will ll it wingD ut we get to intert with it in wy tht is unique to lF his mkes things simpler nd is ig prt of the reson tht qss re inluded this erly in the textF he wy tht the vrious qs lirries re uilt on top of one nother mkes it so tht we will e using little it from eh oneF he l wing lirry is where we will fous most of the timeF he types we use for it re in the slFswing nd slFswingFevent pkgesF ivery so often we might hve to go k down to the tv wing lirries whih re found in jvxFswing1 nd vrious pkges under itF here will even e need to go down to e osionllyF e9ll e working with fir numer of e types in the next hpterF hose will ome from the jvFwt pkge nd its supkgesF

11.2 GUI Components


he onstrution of qss is very modulrF hey re onstruted y putting together di'erent piees lled gomponentsF he spei( types tht we useD suh s futtonD re sutypes of the more generl gomponent typeF utyping ws disussed rie)y in setion UFSFQ nd will e disussed in more detil in hpter IUF

11.2.1 Frames and Windows


o disply qs we need to strt y ringing up windowF here is more thn one type of windowF he type tht we will use s min window for n pplition is lled winprmeF yther options inlude regulr prme nd hilogF he dvntge of the winprme is tht it termintes the progrm when it is losedF he following is little sript tht you n run to ring up windowF

import scala.swing._
1 You might wonder about the javax in the package name.
There are several libraries in Java that begin this way. These are libraries that started o as extension packages that weren't part of the standard libraries. When they were brought into the standard libraries the original name was kept so as not to break existing code that used them.

CHAPTER 11.

GUIS

PPT

pigure IIFIX his is smple window rought up y simple sriptF he window is SHHxSHH pixels nd hs the title pirst qsF hen you lose the windowD the sript will exitF

val frame=new MainFrame { title="First GUI" size=new Dimension(500,500) } frame.visible=true while(true) {}


hen you run this it should pop up window tht looks like (gure IIFIF here re quite few things in this sript tht re worth desriingF e strt with n import sttementF he undersore is wild rd tht tells l to import everything in the slFswing pkgeF e don9t hve to do tht hereD ut it will e more useful s we go on euse we will use lot of di'erent types from this pkgeF felow the import we mke the prme nd store it in vl nmed frmeF he syntx here n e red in the following wyF e re mking new prme ojet nd the urly res do round stu' tht we wnt to put into this ojetF snside the urly res we re hnging some things so they won9t e the defults

CHAPTER 11.

GUIS

PPU

used for prmeF he (rst is to set the titleF his ppers on the top of the windowF efter tht we set the sizeF he size hs type himension @tehnilly it is jvFwtFhimensionAF sn this sript we mke new himension ojet with width nd height oth set to SHHF efter the retion of frmeD there is line tht sets the visile vlue in frme to e trueF his uses the window to pop up nd e visileF efter tht line is something else tht might look oddX while@trueA {}F st is n intentionl in(nite loopD something tht you normlly try to void in your odeF o see why this is thereD try ommenting it out nd running the sriptF sf you do thtD you will see the window )sh up nd then dispperF ht is euse the window is losed nd everything stops when we get to the end of the sriptF he in(nite loop prevents the sript from ending in norml wyF snstedD this sript ends when you lose the windowF ou ould lso reple the while loop with redvineF he ll to redvine will lok the sript from ompleting until the user hits enter in the onsoleF his pproh hs the ene(t of providing di'erent wy to exit the sriptF st lso hs the downside tht if the user identlly hits enter in the onsoleD the sript will loseF

11.2.2 Components
sn order to mke qs do somethingD we need to dd other omponents into itF here re mny di'erent omponents in the slFswing pkgeF e prtil list is shown here with rief desriptionsF

futton E e stndrd utton tht you lik to mke things hppenF grete y lling futton@textXtringA@tion X ab nitAF ghekfox E e leled ox tht you n selet or deEseletF grete with new ghekfox@lelXtringAF gontins seletedXfoolen tht will tell you if the ox is urrently seletedF gomofox E his is dropEox tht llows the user to selet from one of severl optionsF grete with new gomofox@itemsXeqeAF rs n ojet in it lled seletion tht dels with the seletionF se seletionFindex to get the index of the urrent seletionF iditorne E e omplex text element tht displys multiple lines nd formttingF grete with new iditorne@ontentypeXtringDtextXtringAF pormttedextpield E e single line text (eld tht does formttingF grete with new pormttedextpield@formtXtringAF rs (eld lled textXtring tht will tell you the text tht is urrently enteredF vel E e simpleD intiveD lelF grete with new vel@textXtringAF vistiew E e disply of list of informtion tht is seletleF grete with new vistiew@itemsXeqeAF rs n ojet lled seletion in it to

CHAPTER 11.

GUIS

PPV

del with mking seletions on the listF ou n use the olletion seleE tionFindies to intert with the index vlues tht re seletedF

sswordpield E e text (eld tht hides the dt input into itF grete with new sswordpield if there is no defult of new sswordpield@textXtringA if you wnt to strt with defultF rs (eld lled textXtring tht will tell you the text tht is urrently enteredF rogressfr E e grphil disply for progressF rs (elds lled minXsntD mxXsntD nd vlueXsnt tht re used to ontrolGred the progress displyF diofutton E e seletle utton tht n e put in futtonqroup so only one n e seleted t timeF rs (eld lled seletedXfoolen tht will tell you if this urrently seletedF rollfr E e horizontl or vertil r intended for srollingF he rollE fr hs minimumD mximumD nd vlueD whih re ll sntsD tht let you set or inspet where it isF pew pplitions will use rollfr diretly hs the funtionlity you generlly wnt is prt of the rollne desried in the next setionF lider E e horizontl of vertil omponent tht n slide to selet vlueF rs (elds for minD mxD nd vlueF le E e tle for displying dtF grete new one with new E le@rowhtX erryerryenyD olumnxmesX eqenyAF extere E e multiEline text disply nd inputF rs textXtring (eld tht will let you know wht hs een enteredF extpield E e single line text disply nd inputF rs textXtring (eld tht will let you know wht hs een enteredF
es you n seeD there re quite few di'erent options for uilding qss in lF st is not the purpose of this ook to doument the use of ll of the di'erent qs elementsF he es n help you with thtF e will just onsider few in this hpter so tht you will get generl understnding of the oneptsF he esiest one to demonstrte is the futtonF he line elow n e dded into the ode lok for the new prme will use it to hve single utton in it tht sys ress meF

contents=Button("Press me"){ println("Button pressed") }


hen you press the utton the progrm prints out futton pressedF row the utton looks depends it on where you put this lineF sf you put it efore the line tht sets the sizeD the window is still SHHxSHH nd the utton tkes up the whole enter reF yn the other hndD if you put it fter the size lineD hnging the ontents uses the prme to resize itself to n optiml size for the ontentsF sn tht seD the utton is just ig enough to look nie with the text in it nd the window is just lrge enough to hold the uttonF

CHAPTER 11.

GUIS

PPW

o wht does this line doc he prme only gets to hold one thing nd tht one thing is determined y whtever we set ontents to e equl toF sn this seD it is eing set to new futtonF here re severl wys to mke new futtonF his one is the most diret for our purposesF e re mking ll to the futton type nd giving it rguments telling it the detils we wnt for the new futtonF he rguments re gurried nd the seond one is pssed yEnmeF his is very similr to the wy you ll erryF(llF he (rst rgumentD whih is in its own rgument listD is tring tht is the text on the uttonF he seond one is ode tht you wnt to hve hppen ny time the utton is likedF he seond rgument is put inside of urly res hereF his is just shortut tht l llowsF gurly res re required if there re multiple sttements ut not in this seF ou n put prentheses round the urly res if you wntF his ode works (neD ut it hs signi(nt limittionX we n only put one omponent in the frmeF el qss ren9t mde from single omponentF sn order to inlude multiple omponentsD we need to lern just it moreF

11.2.3 Panels and Panes


here re other types of omponents tht weren9t onsidered ove tht t s ontiners for holding multiple other omponentsF hese re lled pnels nd pnesF sf we wnt the prme tht we reted to hve multiple omponents displyed in itD we put either pnel or pne in the prme nd then dd things into itF hile it is possile to spei(lly ple omponents in qsD suh prtie is generlly disourgedF he min reson is tht doing so leds to qss tht ren9t )exileF ou n9t esily hnge the size of windowsD ftor tht ould e very limiting if you wnt to move to di'erent pltforms or just use omputers with di'erent sized sreensF snstedD there re omponents tht n hold mulE tiple other omponents nd whih ontrol how things re lid outF hese n e nested inside of one nother to give the overll e'et tht the progrmmer wntsF he simple ontiner omponentsD whih just position nd size their ontentsD re lled pnelsF here re lso more omplex ontiners tht provide some user intertion s wellF hese re lled pnesF he list elow shows the di'erent pnels nd pnes tht re prt of slFswingF

fordernel E gn hold up to (ve di'erent omponents in the northD southD estD westD nd enter positionsF he omponents re dded to the lyout of the fordernel s tuple of @gomponentDositionAF he ositions re prt of fordernelFosition @eFgF fordernelFositionFxorthAF foxnel E gn hold vrile numer of omponents oriented either verE tilly or horizontllyD eh tking the spe it needsF hen you mke new foxnel you pss it n orienttion @eFgF new foxnel@yrienttionFertilAAF he omponents n e dded one t time to ontents @eFgF onE tentsCafutton@textA@tionAAF

CHAPTER 11.

GUIS

PQH

plownel E gn hold multiple omponents tht re lid out from left to right wrpping when it gets to long like text in word proessorF ou n pss vrile length list of omponents s n rgument t onstrution or dd the omponents to ontentsF qridfgnel E e )exile nd powerful ontiner tht holds ontents in vrile sized gridF he omponents re dded dded to the lyout s tuple of @gomponentDqridfgnelFgonstrintsAF his pnel is more omplex nd won9t e used in this hpterF qridnel E rolds regulr grid of omponentsF ou speify how mny rows nd olumns the grid hs t retion @eFgF new qridnel@QDRAAF he omponents inside re dded to the ontents of the pnelF rollne E e pne tht holds single omponent whih n e pssed in s n rgument t onstrutionF sf the ontent omponent is lrger thn wht this n displyD sroll rs re utomtilly dded so the user n sroll roundF plitne E e ontiner tht holds two omponentsF hey re sepE rted y r tht the user n move s desiredF et onstrution you should provide nd orienttion nd the two hildren @eFgF new plitE ne@yrienttionFrorizontlDleftgompDrightgompAAF edne E his n hold multiple di'erent omponentsF ynly one omponent is shown t timeD ut ts re lwys shown for ll of themF he user n lik t to ring one to the frontF ou n dd omponents to the edne y dding them to the pge ojet inE side of the edneF ht you dd to it re ge ojetsF ih ge ojet is onstruted y giving it tring for the t lel nd gomponent tht should go under tht t @eFgF pges Ca new ge@e DtgomponentAAF
xone of these lone is su0ient to rete omplex qsF snstedD it is ustomry to nest pnels nd pnes one inside of nother to rete the desired e'etF o illustrte thisD we will ly out the qs for little progrm tht we will onstrut in this hpterF he progrm is going to e something like digitl reipe ookF he progrm should e le to store multiple reipesF por eh reipeD it should llow the user to speify ingredients with mounts s well s hve written desription of the ooking diretionsF he qs should give the user the ility to dd nd remove reipesF hey should e le to selet reipes nd edit the vrious informtion tht we hve on themF et this point in the design you would proly wnt to sketh out little piture of wht you wnt the qs to look likeF ht is done for this qs in (gure IIFPF he left side is tken up y list tht shows ll the reipesF hen the user liks on reipeD the informtion for it should e shown on the rightF ht inludes list of ll the ingredients nd the diretionsF he ingredients n lso e edited nd there need to e some uttons to help with thisF he

CHAPTER 11.

GUIS

PQI

Menu Bar Recipe List


Ingredient Buttons

Ingredient Settings

Ingredient List Recipe Directions

pigure IIFPX his shows possile lyout for the qs tht we wnt to uild for editing reipesF options for dding nd removing reipes will e in the menusD whih will e disussed in the next setionF he question is how we should ly this outF eny qs n e uilt in mulE tiple di'erent wys using the di'erent pnel nd pne options tht were listed oveF por exmpleD the seprtion etween the reipe list nd the informtion out the seleted reipe ould e reted y fordernelD foxnel with horizontl orienttionD or plitneF hih of these you pik will normlly e determined y the wy in whih the pnels would size things or whether you wnt to give the user the ontrol of plitneF e will use fordernel for the top level splitF e9ll then use plitne to seprte the diretions from the ingredient informtionF e9ll use two fordernels for the ingredient informtion nd the uttons will e uilt using qridnelF he settings re will lso need to e re(ned it moreF st proly just needs the nme of the ingredient long with the mount neededF ht n e lid out using omintion of fordernel nd qridnelF he ode to do this is shown elowF st is the full sript nd it is firly longF

import scala.swing._ val recipeList=new ListView(List("Pop Tarts")) val ingredientList=new ListView(List("Pop Tarts")) val directionsArea=new TextArea("Toast the poptarts ...\nor don't.") val ingredientNameField=new TextField("Pop Tart")

CHAPTER 11.

GUIS

PQP

val amountField=new TextField("1 packet") val frame=new MainFrame { title="Recipe Book" contents=new BorderPanel { layout += (new ScrollPane(recipeList) -> BorderPanel.Position.West) layout += (new SplitPane(Orientation.Horizontal, new BorderPanel { layout += (new BorderPanel { layout += (new GridPanel(1,2) { contents+=Button("Add") (println("Add ingredient")) contents+=Button("Remove") (println("Remove ingredient")) } -> BorderPanel.Position.North) layout += (new ScrollPane(ingredientList) -> BorderPanel.Position.Center) } -> BorderPanel.Position.West) layout += (new BorderPanel { layout += (new GridPanel(2,1) { contents += new Label("Name") contents += new Label("Amount") } -> BorderPanel.Position.West) layout += (new GridPanel(2,1) { contents += ingredientNameField contents += amountField } -> BorderPanel.Position.Center) } -> BorderPanel.Position.Center) }, new ScrollPane(directionsArea)) -> BorderPanel.Position.Center) } size=new Dimension(800,600) } frame.visible=true while(true) {}
he intertive elements were stored s vlues with nmes t the eginningF he purpose of tht will eome ler in setion IIFQF sndenttion hs een used to indite the nesting of pnels nd pnesF elterntelyD eh di'erent prt ould hve een given nme s vlue nd the then the prts ould hve een put togetherF he hoie etween these options is n issue of styleF his exmple is just ig enoughD nd the pnels nested just deep enough tht it ould e worth onsidering reking it up some with nmed onstruts for some of the more deeply nested setionsF rere is di'erent version tht uses tht pprohF

import scala.swing._

CHAPTER 11.

GUIS

PQQ

val val val val val val

} val ingredientDataPanel = new BorderPanel { layout += (new GridPanel(2,1) { contents += new Label("Name") contents += new Label("Amount") } -> BorderPanel.Position.West) layout += (new GridPanel(2,1) { contents += ingredientNameField contents += amountField } -> BorderPanel.Position.Center) } val frame=new MainFrame { title="Recipe Book" contents=new BorderPanel { layout += (new ScrollPane(recipeList) -> BorderPanel.Position.West) layout += (new SplitPane(Orientation.Horizontal, new BorderPanel { layout += (ingredientListPanel -> BorderPanel.Position.West) layout += (ingredientDataPanel -> BorderPanel.Position.Center) }, new ScrollPane(directionsArea)) -> BorderPanel.Position.Center) } size=new Dimension(800,600) } frame.visible=true while(true) {}

recipeList=new ListView(List("Pop Tarts")) ingredientList=new ListView(List("Pop Tarts")) directionsArea=new TextArea("Toast the poptarts ...\nor don't.") ingredientNameField=new TextField("Pop Tart") amountField=new TextField("1 packet") ingredientListPanel = new BorderPanel { layout += (new GridPanel(1,2) { contents+=Button("Add")(println("Add ingredient")) contents+=Button("Remove")(println("Remove ingredient")) } -> BorderPanel.Position.North) layout += (new ScrollPane(ingredientList) -> BorderPanel.Position.Center)

his seond version would likely e preferred euse the deepest nesting hs een ut down two levels nd the nmed vlues n help reders (gure out wht di'erent prts of the ode re doingF his n e tken further if you desireF

CHAPTER 11.

GUIS

PQR

pigure IIFQX his is the window produed y the ode to do the initil lyout of the reipe ookF hen you run either of these sripts you get window shown in (gure IIFQF sn the ode you might notie tht eh of the vistiews nd the lrge extere re put inside of rollnesF his is to mke it so tht if the lists get lrge or the diretions get longD sroll rs will e dded to llow the user to sroll round nd see everything they need toF

11.2.4 Menus
ell we lk in the pperne of the qs now is the menusF he winprme hs (eld lled menufr tht we n set to e n ojet of type wenufrF he wenufr type hs ontentsD like the pnels nd pnesD ut you should only dd ojets of the wenu type to wenufrF he wenu ojets re reted with new nd should e pssed tring tht you wnt s the title of the menuF he ontents of wenu n e of one of (ve typesF

wenustem E his is the most ommon thing you will put in menuF ou rete them with new nd the esiest pproh is to give them n etion ojetF he etion ojet n e mde like futton with

CHAPTER 11.

GUIS

PQS

tring nd n tion tht is pssed yEnmeF por exmple new wenuE stem@etion@ixitA@exit@HAAAF

wenu E ou n dd wenu to wenuF his will pper s sumenu when you run the progrmF ghekwenustem E wenus n lso hve options on them tht re seletedF o do this use the type ghekwenustemF ou mke these with new nd pss in tring for the text to displyF diowenustem E sf you hve multiple vlues nd you only wnt to llow one to e seleted use diowenustemF hese re mde like ghekweE nustemsF ell the diowenustems nd you wnt to hve grouped together should e dded to single ojet of the futtonqroup typeF eprtor E his is simple omponent used to spe items out to improve pperne nd usilityF
e n set up simple menu system for our reipe sript y dding the following ode inside the winprme right efore we set the sizeF

menuBar=new MenuBar contents += new contents += contents += contents += contents += } contents += new contents += contents += } }

{ Menu("File") { new MenuItem(Action("Open")(openFile)) new MenuItem(Action("Save")(saveFile)) new Separator new MenuItem(Action("Exit")(exit(0))) Menu("Recipe") { new MenuItem(Action("Add")(addRecipe)) new MenuItem(Action("Remove")(removeRecipe))

sn order to get this to runD we hve to put delrtions of the four funtions tht re lled in the sript efore we mke frmeF por now these n e left ompletely emptyF

def } def } def } def }

openFile { saveFile { addRecipe { removeRecipe {

ith these dditions we now hve sript tht will ring up firly omplete qsF nfortuntelyD it still doesn9t do nything yetF e9ll get to tht soon enoughF

CHAPTER 11.

GUIS

PQT

11.2.5 Tooltips
ou hve proly seen qss whereD if you leve the mouse hovering ove something for whileD messge will pop up telling you something out wht it doesF hese re lled tooltipsF ell the omponents hve (eld in them lled tooltip tht is tringF ou n set the tooltip to e messge tht you wnt to pop upF his will hppen utomtilly if the user leves their mouse pointer over tht omponent for period of timeF

11.3 Basic Interactivity


he qs tht we hve reted for our reipe ook looks (ne nd hs ll piees tht we needF nfortuntelyD it doesn9t tully do nything t this pointF sn order to mke it intertiveD we need to ode tht inF sntertivity in qss is signi(ntly di'erent from tht in onsole progrmsF por onsole progrmD the only rel input is to hve the user type in informtionF e were le to red tht informtion using funtions like redsntD redvineD redhouleD etF imilrlyD the only output ws to print things k to the onsoleF sn dditionD while the user ws typing stu' in the progrm ws supposed to e pusedF e desrie this y sying tht user input is lokingF o nothing else ws hppening when we lled redvineF ht ll would lok the exeution nd it wouldn9t ontinue until the user hd entered somethingF e you move to qs environmentD ll the rules of intertivity hngeF here re now multiple omponents tht the user n intert withF ih one might respond in di'erent wysF por exmpleD utton n just e likedF yn the other hndD text (eld n hve the user type into it nd you need to know when they re doneF ih di'erent omponent hs di'erent wys you n intert with them nd eh of them needs to e witing for the user to intertF xo single omponent n lok exeution while it wits for the userF hey ll hve to e tive t the sme timeF his setion looks t the wy we do user input in qs uilt with the slFswing lirryF

11.3.1 Partial Functions


here is one feture of the l lnguge tht we hven9t tlked out efore tht is required for doing intertions in qssX the prtil funtionF he ide of prtil funtion omes from mthemtisF st is funtion tht n only operte on ertin vlues of the rguments nd is unde(ned for other rgumentsF he syntx for prtil funtions in l is silly like hving mth expresE sion without the rgument nd the mthF ou simply hve urly res with di'erent ses inside of themF

case 1 => // code goes here case 2 => // code goes here

CHAPTER 11.

GUIS

PQU

}
his exmple prtil funtion would operte on n sntD ut would only e de(ned if the rgument ws I or PF his is more useful when we use more of the options for ses nd the pttern mthing they doD whih we won9t disuss in detil until hpter IRF por now it will su0e to introdue the pility to mth on di'erent typesF sf the se inludes nme tht egins with lowerse letterD it will use tht s vrile nme to store the vlue of the mth inF

{ }

case v => println(v) // this will happen for everything

sing the olon syntx tht you hve een using ll long to speify the types of rguments to funtions nd the (elds in se lssesD you n lso speify tht nmed vlue in se hs to hve spei( typeF

case i:Int => println(Partial functions called on an Int +i) case d:Double => println(Partial functions called on a Double +d) case s:String => println(String = +s)

his exmple prtil funtion is only de(ned for sntD houleD nd tringF sf you pss in ny other typeD it will filF sf you ll it with one of those typesD it will give tht vlue to the nme iD dD or sD then print the pproprite outputF

11.3.2 Publishers and Reactors


he model for hving users intert with qss in the slFswing lirry is sed on types lled ulisher nd etorF he ide is tht the omponents in qs re ulishersF hen something hppens to themD let9s ll it n eventF he ulisher will pulish tht eventF gode n e set up in etor to py ttention to prtiulr ulisher nd then it n ret to these events in the proper wyF here is type lled ivent tht represents something tht n hppen in the qsF here re lots of di'erent sutypes of ivent tht re prt of the slFswingFevent pkgeF es we sw oveD you don9t hve to do this for uttons euse when you rete futtonD there is simple syntx for providing the ode tht will e exeutedF xot everything is so simple thoughF por mny omponents there re severl di'erent possile events tht you might ret to or there is other informtion tht you need to know when the intertion oursF o see thisD onsider the exmple of vistiewF wo of these were pled in the qs for the reipe ookF hen the user liks on something in the vistiewD the progrm needs to e le to disply the pproprite informtion in other (eldsF o illustrte how this worksD we will strt with simpler exmple tht

CHAPTER 11.

GUIS

PQV

ontins only list nd extpieldF hen the user selets n item from the listD the text (eld should e set to the vlue of wht ws likedF his exmple n e set up with the following odeF

import scala.swing._ import scala.swing.event._ val options="A list of words".split(" ") val list=new ListView(options) val field=new TextField val frame=new MainFrame { title="First GUI" contents=new BorderPanel { layout+=(list -> BorderPanel.Position.Center) layout+=(field -> BorderPanel.Position.South) } size=new Dimension(500,500) } frame.visible=true while(true) {}
o mke this intertive we need to tell the frme to listen to the seletion ulisher in the list nd then give it prtil funtion to hndle the events tht we re interested inF his n e omplished y dding the following text inside the lok of ode for uilding the frmeF

listenTo(list.selection) reactions+={ case e:SelectionChanged => field.text=list.selection.items.mkString("; ") }


he (rst line of ode hs the frme listen to the seletion ulisherF sf you lter deided tht you didn9t wnt to listen to tht nymoreD you ould ll defo on the frmeF efter thtD prtil funtion is dded to the retions of the frme tht hs single se for hndling the eletionghnged eventF he seletion (eld of list hs olletion in it lled items tht ontins ll the items tht re seleted from the listF his is olletion euse the vistiew llows multiple items to e seleted t timeF he text for the (eld is set to e ll of the items seprted y semiolonsF he type eletionghnged is prt of the slFswingFevent pkgeF here re lrge numer of di'erent event types in this pkge for ll the di'erent things tht n hppen in qsF he list is long enough tht they won9t e put in hereF eders n go to the l es to see the list of di'erent eventsF e will introdue few more in this hpter for the reipe ook exmpleF sn generlD your prtil funtion for the retions will hve more thn one seF his exmple simply didn9t need thtF

CHAPTER 11.

GUIS

PQW

11.3.3 Mnemonics
st is often helpful to put keyord shortuts into qss so tht the user n exeute ertin ommnds without hving to go over to the mouse to do soF hese shortuts re referred to s mnemonis nd the di'erent omponents in slFswing tht hve simple modes of intertionD like uttonsD menu itemsD nd hek oxes hve (eld lled mnemoni tht n e set to the keystroke tht you wnt people to useF he following exmple demonstrtes dding mnemonis to short menuF

menuBar=new MenuBar { contents+=new Menu("File") { mnemonic=Key.F contents+=new MenuItem(Action("Exit")(exit(0))) { mnemonic=Key.X } } }


his n e dded into the simple qs reted ove to dd pile menu tht you n ring down with eltEp nd n ixit item tht n e exeuted y hitting when the menu is downF

11.4 File Chooser


here is t lest one other option in the qs lirry tht is worth pointing out euse it is used so frequentlyD the (le hooserF wny progrms hve open nd sve options in their menuF hen these options re seletedD the progrm will typilly pop up dilog ox tht llows the user to nvigte through the diretory struture nd pik (lesF ou ould write your own dilog to do thisD ut it would tke signi(nt mount of e'ort nd it is suh ommon tsk tht it hs een dded to the lirryF he pileghooser type is used to disply (le seletion dilogF ou n mke new pileghooser with or without single rgument for strting diretoryF sf you omit the strting diretory it uses defult diretory to strt inF here re three di'erent methods in pileghooser tht ll strt with show whih n e used to pop up dilog oxX showhilogD showypenhilogD showvehilogF ell three tke (rst rgument of the omponent you wnt the dilog to pop up overF sf you pss null for tht rgumentD the dilog will pper in the middle of the sreenF he showhilog method lso tkes seond rgument tht is tring tht will e displyed on the pprovl uttonF hese methods will return one of the followingX pileghooserFesultFepproveD pileghooserFesultFgnelD or pileghooserFesultFirrorF sf it gives k epproveD then the pileghooser will hve vlid vlues in the seletedpile nd seletedpiles (eldsF o help understnd thisD onsider the following exmple of n ypen option dded to the menu tht ws reted in the lst setionF his option ould e dded to the menu y dding the following ode in the lok for the menu rF

CHAPTER 11.

GUIS

PRH

contents+=new MenuItem(Action("Open")(openFile)) { mnemonic=Key.O }


o mke this workD we need n openpile funtionF his n e de(ned in the following wy nd pled fter the delrtions of list nd (eld nd efore tht of frmeF

def openFile { val chooser=new FileChooser if(chooser.showOpenDialog(list)==FileChooser.Result.Approve) { list.listData=Source.fromFile(chooser.selectedFile).getLines.toList } }


his ode retes pileghooser nd displys n open dilogF sf the user selets (leD tht (le is used to open oure nd the lines from tht soure re onverted to vist whih is set to e the dt for the vistiewF

11.5 Tables
yne of the more omplex qs elements in wing is the leF he nme does good jo of desriing wht this element doesF st presents PEh grid of dt ells the user n intert withF hile the slFswingFle type n give you si funtionlity esilyD there is lot more the jvxFswingFle type n do tht requires you to go into the originl tv lirriesF por tht resonD this setion is devoted to this omponentF hen you mke slFswingFleD there re three options for rguments you pss to itF ou n tell it how mny rows nd olumns to put in the tle s two snt rgumentsF his will mke simple tle of the spei(ed size where ll the elements re lnkF ou n ply with this y entering ode like the following into the ivF

val frame = new Frame { title="Table Test" contents = new Table(3,4) } frame.visible = true
his ode will pop up window with tle with Q rows nd R olumns with ll the ells lnkF his exmple uses prme insted of winprme euse it is intended to e done in the ivF sf you use winprmeD when you lose the windowD the entire iv will e termintedF ou n lso pss in the rguments rowhtX erryerryenyD olumnE xmesX eqF his will mke tle tht hs the size of the rowht nd

CHAPTER 11.

GUIS

PRI

strts with those vluesF ememer from (gureUFUFI tht eny is type in l whih n represent ny other typeF our tle doesn9t hve to hve strings of dt in itF hey n e fr more omplexD ut we won9t e going into ll of those detils hereF he seond rgument is sequene tht hs the vlues you wnt to pper t the tops of olumns leling themF hese lels will only pper if the tle is nested in rollneF o test how this worksD try entering the following into the ivF

val data = Array(Array(1,2,"hi"),Array(3,4,"bye")) val colHeads = Seq("Num","Num","Word") val frame = new Frame { title = "Table Test" contents = new Table(data,colHeads) } frame.visible = true
his will ring up smll window with tle tht hs two rows nd three olumnsF xote tht the olumn heders don9t pper in this versionF o get the olumn hedersD hnge the line of ode setting the ontents of the frme to the followingF

contents = new ScrollPane(new Table(data,colHeads))


xow when you mke the frme visile you get muh lrger window with the sme tle exept tht now the olumn heders re visileF he third wy to uild tle doesn9t pss ny rguments in t llF sf you pik this optionD you will need to do more work setting things up so for now we will fous on the other optionsF sf you plyed with the tles tht you rought up in the ivD you proly found tht you n selet ellsD move round with the rrow keysD nd even edit the vlues in ellsF o work with the tle in odeD we need to hve nme to refer to the tle yF e n get this y modifying the ode slightly so we hve vrile lled tleF

val table = new Table(data,colHeads) ... contents = new ScrollPane(table) ...


o get vlues out of the tleD simply index it with row nd olumnF o if you were to do the following line in the iv you would see the vlue of the topEleft ellF

println(table(0,0))
sf you did this immeditely fter reting the tle you would get k the vlue IF roweverD if you edit tht ell in the tle mnully then print itD you will see the modi(ed vlueF

CHAPTER 11.

GUIS

PRP

ou n modify vlues in the tle in the sme mnnerF imply do n ssignment into the tle indexed y row nd olumnF ry this y doing the following in the ivF

table(1,1) = "New text"


ou will see tht the vlue in ell IDI of the tle is updted grphilly to re)et the hngeF his pproh n only e used to modify ells within the norml ounds of the tleF sf you go eyond the size set when you (rst reted the tle you will get n errorF sf you try entering tle@HDHA into the iv you will get k result with the type enyF his n e it of prolem euse there ren9t mny things tht you n do with the eny typeF por exmpleD you might try doing the followingF

table(0,0)+table(1,0)
eddition like this would work just (ne for ny numeri type or the tring type s ll of those types hve the method C de(ned for themF roweverD if you try to do this you would get the following error messgeF

<console>:12: error: type mismatch; found : Any required: String table(0,0)+table(0,0) ^


ht is euse the type eny doesn9t hve C methodF his mkes sense s there re some types tht qulify s eny tht you shouldn9t e le to use C withF o do nything with the vlues we get from the tle we hve to ll methods tht exist on enyF he hllenge is tht there ren9t very mny of theseF ou n hek for equlity or inequlityD do opertions ssoited with multithreding tht will e disussed in hpter PID hek the tul type of the ojetD or onvert the ojet to tringF he lst two n provide the funtionlity tht we wntF e will fous on the lst one euse it uses only methods tht we hve seen eforeF o onvert ny ojet to tring ll the totring methodF ou n try to following to see how this worksF

table(0,0).toString
yne you hve done this you n use C to do tring ontentionF sf you wnt to do numeri opertions on the vlues in tle you n use tosnt or tohoule on the tringF o if you wnt to multiply two tle vlues you ould do thisF

table(0,0).toString.toDouble*table(1,0).toString.toDouble

CHAPTER 11.

GUIS

PRQ

his is it veroseD ut it is the prie we py for eing le to put ll types of di'erent things in leF sf you ply round with this enough you will proly stumle orss the primry downfll of this pprohD if the ontents of the ell ren9t numer this will filF o get round thisD you would need to use the tryEth onstrutF e will disuss tryEth in detil in setion PPFPPFPF por now we9ll give rief introdutionF ou might hve seen tht when something goes wrong with sttement the error messge you get typilly strts y giving you type nme tht inludes the word ixeptionF en exception is n ojet tht indites prolem nd when something goes wrong the ode will throw n exeptionF sf you know this might hppen nd you wnt to del with itD you tell l you wnt to try some ode nd then catch the exeption if one oursF he exeptions you n th re spei(ed with sesD just like mth expressionF he tryEth in l n e used s n expressionF sf there is no exeption you get the vlue of the ode you tried to doF sf there is n exeption you hs mthing seD the vlue will e wht hppens in tht seF o help you understnd thisD onsider the following funtionF

def asDouble(a:Any):Double = { try { if(a==null) 0.0 else a.toString.toDouble } catch { case e:NumberFormatException => 0.0 } }
his funtion tkes n eny ojet nd returns numer for itF sf the vlue is null it returns zeroF ytherwiseD it uses the FtotringFtohoule method shown oveF roweverD in this funtion tht is put inside of try tht will th xumerpormtixeptionF es the nme impliesD this is n exeption tht ours when you try to mke numer of something tht doesn9t hve the right formtF sf tht hppensD the se gives k the vlue HFHF he sum ove ould now e expressed in this wyF

asDouble(table(0,0))+asDouble(table(1,0))
his ode is more roust in tht if tle ell ontins something tht isn9t numerD insted of stopping with n exeptionD the ode uses HFH for tht ellF

11.5.1 Table Actions


ou now know how to set up tles s well s how to red nd lter the vlues in themF por mny pplitions this will e su0ientF he tions in qs n very often e initited y hving the user lik utton or selet menu item nd hve the ode initited y tht tion utilize the vlues in the tleF here re some pplitionsD howeverD when you need to tully respond to events

CHAPTER 11.

GUIS

PRR

tht our with the tle itselfF sn this sitution you need to listen to the tle or possily the seletion ojet in the tleF here is signi(nt list of events tht n hppen with tlesF ou n look in the es for omplete informtionD ut here is list of the min onesF

leghnged E sndites tht the struture of the tle styed the smeD ut nything else ould hve hngedF legolumnseleted E sndites hnge in the olumn@sA urrently seletedF leowsedded E his event ours when dditionl rows re dded to the tleF leowsemoved E his event ours when rows re removed from the tleF leowseleted E sndites hnge in the row@sA urrently seletedF letrutureghnged E his event indites the most generl type of hngeF enything in the tle ould hve hnged inluding row nd olumn ountsF lepdted E sndites tht vlues in spei(ed prt of the tle hve hngedF
o get the events tht indite hnges in the seletion you listen to tleFseletionF o get the others simply listen to the tleF sf ll tht you re interested in is knowing when the vlue in ell hs een hngedD you n use ode like the followingF

import scala.swing._ import scala.swing.event._ val sumLabel = new Label("0.0") val table = new Table(8,5) def asDouble(a:Any):Double = { try { if(a==null) 0.0 else a.toString.toDouble } catch { case e:NumberFormatException => 0.0 } } val frame = new MainFrame { contents = new BorderPanel { layout += sumLabel -> BorderPanel.Position.North layout += table -> BorderPanel.Position.Center } size = new Dimension(500,400) listenTo(table)

CHAPTER 11.

GUIS

PRS

} frame.visible = true readLine()

reactions += { case e:TableUpdated => val sum = (for(i <- 0 until table.rowCount; j <- 0 until table.model.getColumnCount) yield { asDouble(table(i,j)) } ).sum sumLabel.text = sum.toString }

his ode strts with n empty tle nd lel tht shows HFHF ivery time tht the user edits ellD the ode runs through ll the ells nd dds up the vlues in ehD using zero if there isn9t vlid numerF st hnges the lel to re)et this sumF inter this ode into (le nd run it s sriptF wke hnges to see wht else you n doF

11.5.2 Table Models


ghnging size is it more di0ult thn simply hnging vluesF rt of the )exiility of les omes from the ft tht you n hnge how the dt ehind them is modeledF he full detils of this re eyond the sope of this ookD ut to hve full ontrol over tle you need to hve t lest some knowledge of how to utilize thisF fig hnge with new model edding rows with hefultlewodel 333

11.6 Putting it Together


e n now put together ll of the vrious spets of qss into the reipe ook sriptF irlier we hd uilt qs nd dded menus to itF roweverD the qs wsn9t intertiveF gliking on vrious elements didn9t do nything to other elements of the qsF xow tht we know how to mke qss intertive we n dd the proper funtionlity to this sriptF sn order to e le to do thisD we need to dd some groundwork (rstF sn prtiulrD we need good wy to store the informtion ssoited with reipeF his lls for some se lssesF e de(nitely wnt se lss to represent reipeF he ft tht reipe n ontin multiple ingredients mkes it dvntgeous to hve se lss for tht s wellF his leds to something like the followingF

case class Ingredient(name:String,amount:String) case class Recipe(name:String,ingredients:List[Ingredient],directions:String)

CHAPTER 11.

GUIS

PRT

ou n put this ner the top of the sript s mny other prts of the sript will e referring k to itF e lso need to hve wy to store multiple reipesF e will do this with vrile delrtion of n rry of reipesF yne ould lso hoose to use vrile listD ut some of the intertions will require swpping out vlues nd others might require doing diret essF foth of those will e esier nd more e0ient with n rryF he dding of new reipes would e esier with listD ut tht opertion will proly our less frequently nd n e done lmost s esily with n rryF

var recipes=Array(Recipe("Pop Tarts",List(Ingredient("Pop Tart","1 packet")), "Toast the poptarts ...\nor don't.")) val recipeList=new ListView(recipes.map(_.name)) val ingredientList=new ListView(recipes(0).ingredients.map(_.name)) val directionsArea=new TextArea(recipes(0).directions) val ingredientNameField=new TextField(recipes(0).ingredients(0).name) val amountField=new TextField(recipes(0).ingredients(0).amount)
his ode inludes delrtion of the rry s well s revisions of the tive omponent delrtions tht use the one eipe in the rryF xow tht we hve this set upD we n strt with the esy prt of ompleting the funtions tht re lled from the menusF e9ll strt with the svepile funtion s tht de(nes the formt tht we will use in the (le nd it is it esierF

def saveFile { val chooser=new FileChooser if(chooser.showSaveDialog(recipeList)==FileChooser.Result.Approve) { val pw=new PrintWriter(chooser.selectedFile) pw.println(recipes.length) for(r <- recipes) { pw.println(r.name) pw.println(r.ingredients.length) for(ing <- r.ingredients) { pw.println(ing.name) pw.println(ing.amount) } pw.println(r.directions) pw.println(".") } pw.close() } }
his funtion llows the user to selet (leD then writes the size of the rry to the (leF efter the size it writes eh reipeF he formt of the reipes is firly

CHAPTER 11.

GUIS

PRU

simple with nmeD then the numer of ingredients nd lternting lines of ingredient nmes nd mountsF he only thing tht might seem it odd is the line with period fter the diretionsF his is required euse the diretions n e multiple lines long nd we hve to hve wy to know when to stop reding themF efter we hve written sve nd de(ned the formt of the (leD we n write the openpile funtionF his is slightly more omplexD primrily euse we hve to del with the diretionsF

def openFile { val chooser=new FileChooser if(chooser.showOpenDialog(recipeList)==FileChooser.Result.Approve) { val src=Source.fromFile(chooser.selectedFile) val lines=src.getLines recipes=Array.fill(lines.next.toInt)(Recipe( lines.next, List.fill(lines.next.toInt)(Ingredient(lines.next,lines.next)), { var dir="" var line=lines.next while(line!=".") { dir += (if(dir.isEmpty) "" else "\n")+line line=lines.next } dir } )) src.close() recipeList.listData=recipes.map(_.name) recipeList.selectIndices(0) setFields(recipes(0)) } }
he ode isn9t ll tht di'erent from sve other thn it uses soure nd uilds n rry to store in reipes with (llF e fir it of the length of the method omes from the lok of ode tht is used to red the diretionsF his lok is used s n expressionF st uilds up the diretions in vrile nmed dir nd uses while loop to ontinue reding until line is rehed tht ontins only single periodF efter the oure is losedD there re two more linesF he (rst one hnges to ontents of the reipevist so tht it mthes wht hs just een red inF he seond lls yet unde(ned funtion nmed setpields tht is supposed to set the other elements of the qs to vlues for prtiulr reipeF his funtion ould e written in the following wyF

def setFields(r:Recipe) {

CHAPTER 11.

GUIS

PRV

ingredientList.listData=r.ingredients.map(_.name) directionsArea.text=r.directions if(r.ingredients.isEmpty) { ingredientNameField.text="" amountField.text="" } else { ingredientNameField.text=r.ingredients.head.name amountField.text=r.ingredients.head.amount }

his funtion will e useful lter on when we inlude the ode to let the user selet di'erent elements from the reipevistF xow we n turn to the funtions to dd reipes or remove reipesF he dd reipe funtion might look like thisF

def addRecipe { val name=javax.swing.JOptionPane.showInputDialog(null, "What is the name of this recipe?") recipes=recipes :+ Recipe(name, List(Ingredient("ingredient","amount")),"Directions") recipeList.listData=recipes.map(_.name) recipeList.selectIndices(recipes.length-1) setFields(recipes(recipes.length-1)) }
his retes new reipe rry tht inludes new defult reipeF his uses n opertor tht we hven9t seen eforeF he XC opertor n e used to dd things to the end of n rry or listF his isn9t something tht you wnt to use in loops tht our lot euse it is ine0ient for either of these typesD ut this only hppens when the user selets n option from the menu so it n9t hppen ll tht oftenF his lso uses prt of the jvxFswing lirryF he jvxFswingFtyptionne lss hs methods tht n e used to ring up simple input dilog oxesF por most of theseD there is similr funtionlity in the slFswingFhilog ojetF he input dilog tht llows the user to type in tring isn9t mirrored in the l lirry so we use the one from tvF he removeeipe funtion needs to tke out the item from the reipe list tht the user hs seletedF es prt of this it needs to hek if nything is seletedF he ode ould e written like thisF

def removeRecipe { if(!recipeList.selection.items.isEmpty) { recipes=recipes.patch(recipeList.selection.leadIndex,List(),1) if(recipes.isEmpty) { recipes=Array(Recipe("New recipe", List(Ingredient("ingredient","amount")),"Directions")) }

CHAPTER 11.

GUIS

PRW

recipeList.listData=recipes.map(_.name) recipeList.selectIndices(0) setFields(recipes(0))

rere too there is one element tht might stnd out s oddF snsted of hving simple remove method to remove the item t prtiulr indexD the l olletions hve pth method tht is fr more )exileF he pth method n reple prt of olletion with some other olletion eginning t ertin indexF hen lled with n empty olletionD it will remove the spei(ed numer of elements t the spei(ed lotionF his ode lso hs hek to see if the lst element ws removed nd if soD it dds in defult elementF o the reipe ook n never e emptyF ith this writtenD the qs now hs the ility to ret to ll of our menu optionsF ht it lks is the ility to disply informtion out di'erent reipes or edit tht informtionF por the (rst prtD we need to e listening to the vistiew to (nd out when seletions re hngedF e lso need to ret to it when it is hngedF rving lredy written the setpields funtion mkes the seond prt of this firly esyF

listenTo(recipeList.selection) reactions+={ case e:SelectionChanged => if(!recipeList.selection.items.isEmpty) { setFields(recipes(recipeList.selection.leadIndex)) } }


his ode ould e dded into the lok of the frme to give us the desired ehviorF ell tht remins is hving the ility to edit the reipesF his requires reting to the di'erent events tht n hppen with the pnels ssoited with the ingredientsF his ode n go in numer of di'erent lotionsF here re two styles tht n mke senseF yne is tht you put the ode in single lotion in the progrm so it is esy to (nd ll the di'erent retionsF e seond pproh is to put the retions lose to the ode tht dds those elements into the qsF he dvntge of this seond pproh is tht everything ssoited with given omponent tends to sty in ertin prt of the odeF e will dopt the seond style hereF he uttons for dding nd removing ingredients hd erlier just printed lines sying they were likedF hose need to e hnged so tht they ll funtions tht do wht we wntF ell of the funtions tht edit the ontents of reipe n only work if there is reipe seleted in the reipevistF o the (rst things tht hppens is hek to mke sure tht something is seletedF sf nothing is seletedD nothing will e done euse we don9t know wht reipe we

CHAPTER 11.

GUIS

PSH

would e editingF qiven thisD the ddsngredient funtion nd helper it uses ould e written in this wyF

def setIngredients(ingr:Ingredient) { ingredientNameField.text=ingr.name amountField.text=ingr.amount } def addIngredient { if(!recipeList.selection.items.isEmpty) { val index=recipeList.selection.leadIndex val oldIngrs=recipes(index).ingredients val newIngr=Ingredient("Stuff","Some") recipes(index)=recipes(index).copy(ingredients=oldIngrs:+newIngr) ingredientList.listData=recipes(index).ingredients.map(_.name) ingredientList.selectIndices(recipes(index).ingredients.length-1) setIngredients(recipes(index).ingredients.last) } }
his ode heks tht something is seletedD (nds the index of the seletionD retes new defult ingredientD then mkes n ltered reipe nd djusts the qsF he removesngredient funtion is similrD ut it lso needs to hek if the is n ingredient seleted from tht listF

def removeIngredient { if(!recipeList.selection.items.isEmpty && !ingredientList.selection.items.isEmpty) { val rIndex=recipeList.selection.leadIndex val iIndex=ingredientList.selection.leadIndex val shortIngr=recipes(rIndex).ingredients.patch(iIndex,List(),1) recipes(rIndex)=recipes(rIndex).copy(ingredients=shortIngr) ingredientList.listData=recipes(rIndex).ingredients.map(_.name) ingredientList.selectIndices(0) setIngredients(recipes(rIndex).ingredients.head) } }
es we hve seen erlierD this ode uses some lol vriles to store vlues re re used frequentlyF st lso tkes dvntge of the pth method to remove element from the listF he only things tht re left re hving it so tht editing the text (elds or the text re lters the dt stored in the reipes rry nd seleting ingredients hnges wht is displyedF he esiest (eld to hnge is the diretions euse it is (eld of the reipe itselfF wking this hppen requires listening to something tht hppens with the diretionsereF hen users enter text in extere or extpieldD it (res lueghnged eventF roweverD we don9t relly wnt to hnge things for every single hrterF e only need to know when they

CHAPTER 11.

GUIS

PSI

re done editingF por text elementD the user is done editing it when heGshe moves fous to di'erent prt of the qsF por tht resonD we will listen for the pousvost eventF e9ll lso need to strt listening to the di'erent text elementsF felow is wht we need to hnge our listening nd retion ode to in the frmeF

listenTo(recipeList.selection,ingredientList.selection, directionsArea,ingredientNameField,amountField) reactions+={ case e:SelectionChanged => if(e.source==recipeList) { if(!recipeList.selection.items.isEmpty) { setFields(recipes(recipeList.selection.leadIndex)) } } else if(e.source==ingredientList) { if(!recipeList.selection.items.isEmpty && !ingredientList.selection.items.isEmpty) { val rIndex=recipeList.selection.leadIndex val iIndex=ingredientList.selection.leadIndex setIngredients(recipes(rIndex).ingredients(iIndex)) } } case e:FocusLost => val rIndex=recipeList.selection.leadIndex if(e.source==directionsArea) { recipes(rIndex)=recipes(rIndex). copy(directions=directionsArea.text) } else if(e.source==ingredientNameField) { if(!recipeList.selection.items.isEmpty && !ingredientList.selection.items.isEmpty) { val rIndex=recipeList.selection.leadIndex val iIndex=ingredientList.selection.leadIndex changeIngredientName(rIndex,iIndex) } } else if(e.source==amountField) { if(!recipeList.selection.items.isEmpty && !ingredientList.selection.items.isEmpty) { val rIndex=recipeList.selection.leadIndex val iIndex=ingredientList.selection.leadIndex changeAmount(rIndex,iIndex) } } }
his ode works for the diretionsere nd seleting ingredientsF st lso sets up things for the two di'erent text (elds so ll we hve left is writing two funtionsF sn the se for pousvostD the ode heks the soure of the eventF he soure

CHAPTER 11.

GUIS

PSP

of n event is the omponent tht it me fromF sf it is the diretions reD it lters the reipe in the wy shown hereF he ltering of the ingredients is done with these funtionsF

def changeIngredientName(r:Int,i:Int) { val ing=recipes(r).ingredients(i) recipes(r)=recipes(r).copy(ingredients={ recipes(r).ingredients.patch(i,List(Ingredient( ingredientNameField.text,ing.amount)),1) }) ingredientList.listData=recipes(r).ingredients.map(_.name) ingredientList.selectIndices(i) } def changeAmount(r:Int,i:Int) { val ing=recipes(r).ingredients(i) recipes(r)=recipes(r).copy(ingredients={ recipes(r).ingredients.patch(i,List(Ingredient( ing.name,amountField.text)),1) }) }
th is used gin hereD ut this time the pthing list is one tht ontins revised ingredientF ell of these di'erent piees go together into single sriptF o help you see how they ll (t togetherD this is the full sriptF

import scala.swing._ import scala.swing.event._ import java.io.PrintWriter import scala.io.Source case class Ingredient(name:String,amount:String) case class Recipe(name:String,ingredients:List[Ingredient],directions:String) var recipes=Array(Recipe("Pop Tarts",List(Ingredient("Pop Tart","1 packet")), "Toast the poptarts ...\nor don't.")) val recipeList=new ListView(recipes.map(_.name)) val ingredientList=new ListView(recipes(0).ingredients.map(_.name)) val directionsArea=new TextArea(recipes(0).directions) val ingredientNameField=new TextField(recipes(0).ingredients(0).name) val amountField=new TextField(recipes(0).ingredients(0).amount) def setFields(r:Recipe) { ingredientList.listData=r.ingredients.map(_.name) directionsArea.text=r.directions if(r.ingredients.isEmpty) { ingredientNameField.text="" amountField.text="" } else { ingredientNameField.text=r.ingredients.head.name

CHAPTER 11.

GUIS

PSQ

} def setIngredients(ingr:Ingredient) { ingredientNameField.text=ingr.name amountField.text=ingr.amount } def addIngredient { if(!recipeList.selection.items.isEmpty) { val index=recipeList.selection.leadIndex val oldIngrs=recipes(index).ingredients val newIngr=Ingredient("Stuff","Some") recipes(index)=recipes(index).copy(ingredients=oldIngrs:+newIngr) ingredientList.listData=recipes(index).ingredients.map(_.name) ingredientList.selectIndices(recipes(index).ingredients.length-1) setIngredients(recipes(index).ingredients.last) } } def removeIngredient { if(!recipeList.selection.items.isEmpty && !ingredientList.selection.items.isEmpty) { val rIndex=recipeList.selection.leadIndex val iIndex=ingredientList.selection.leadIndex val shortIngr=recipes(rIndex).ingredients.patch(iIndex,List(),1) recipes(rIndex)=recipes(rIndex).copy(ingredients=shortIngr) ingredientList.listData=recipes(rIndex).ingredients.map(_.name) ingredientList.selectIndices(0) setIngredients(recipes(rIndex).ingredients.head) } } val ingredientListPanel = new BorderPanel { layout += (new GridPanel(1,2) { contents+=Button("Add")(addIngredient) contents+=Button("Remove")(removeIngredient) } -> BorderPanel.Position.North) layout += (new ScrollPane(ingredientList) -> BorderPanel.Position.Center) } val ingredientDataPanel = new BorderPanel { layout += (new GridPanel(2,1) { contents += new Label("Name") contents += new Label("Amount") } -> BorderPanel.Position.West) layout += (new GridPanel(2,1) { contents += ingredientNameField contents += amountField

amountField.text=r.ingredients.head.amount

CHAPTER 11.

GUIS

PSR

} -> BorderPanel.Position.Center) } def openFile { val chooser=new FileChooser if(chooser.showOpenDialog(recipeList)==FileChooser.Result.Approve) { val src=Source.fromFile(chooser.selectedFile) val lines=src.getLines recipes=Array.fill(lines.next.toInt)(Recipe( lines.next, List.fill(lines.next.toInt)(Ingredient(lines.next,lines.next)), { var dir="" var line=lines.next while(line!=".") { dir += (if(dir.isEmpty) "" else "\n")+line line=lines.next } dir } )) src.close() recipeList.listData=recipes.map(_.name) recipeList.selectIndices(0) setFields(recipes(0)) } } def saveFile { val chooser=new FileChooser if(chooser.showSaveDialog(recipeList)==FileChooser.Result.Approve) { val pw=new PrintWriter(chooser.selectedFile) pw.println(recipes.length) for(r <- recipes) { pw.println(r.name) pw.println(r.ingredients.length) for(ing <- r.ingredients) { pw.println(ing.name) pw.println(ing.amount) } pw.println(r.directions) pw.println(".") } pw.close() } } def addRecipe { val name=javax.swing.JOptionPane.showInputDialog(null,"What is the name of this rec

CHAPTER 11.

GUIS

PSS

} def removeRecipe { if(!recipeList.selection.items.isEmpty) { recipes=recipes.patch(recipeList.selection.leadIndex,List(),1) if(recipes.isEmpty) { recipes=Array(Recipe("New recipe", List(Ingredient("ingredient","amount")),"Directions")) } recipeList.listData=recipes.map(_.name) recipeList.selectIndices(0) setFields(recipes.head) } } def changeIngredientName(r:Int,i:Int) { val ing=recipes(r).ingredients(i) recipes(r)=recipes(r).copy(ingredients={ recipes(r).ingredients.patch(i,List(Ingredient( ingredientNameField.text,ing.amount)),1) }) ingredientList.listData=recipes(r).ingredients.map(_.name) ingredientList.selectIndices(i) } def changeAmount(r:Int,i:Int) { val ing=recipes(r).ingredients(i) recipes(r)=recipes(r).copy(ingredients={ recipes(r).ingredients.patch(i,List(Ingredient( ing.name,amountField.text)),1) }) } val frame=new MainFrame { title="Recipe Book" contents=new BorderPanel { layout += (new ScrollPane(recipeList) -> BorderPanel.Position.West) layout += (new SplitPane(Orientation.Horizontal, new BorderPanel { layout += (ingredientListPanel -> BorderPanel.Position.West) layout += (ingredientDataPanel -> BorderPanel.Position.Center) },

recipes=recipes :+ Recipe(name, List(Ingredient("ingredient","amount")),"Directions") recipeList.listData=recipes.map(_.name) recipeList.selectIndices(recipes.length-1) setFields(recipes.last)

CHAPTER 11.

GUIS

PST

} listenTo(recipeList.selection,ingredientList.selection,directionsArea,ingredientNam reactions+={ case e:SelectionChanged => if(e.source==recipeList) { if(!recipeList.selection.items.isEmpty) { setFields(recipes(recipeList.selection.leadIndex)) } } else if(e.source==ingredientList) { if(!recipeList.selection.items.isEmpty && !ingredientList.selection.items.isEmpty) { val rIndex=recipeList.selection.leadIndex val iIndex=ingredientList.selection.leadIndex setIngredients(recipes(rIndex).ingredients(iIndex)) } } case e:FocusLost => val rIndex=recipeList.selection.leadIndex if(e.source==directionsArea) { recipes(rIndex)=recipes(rIndex).copy(directions=directionsArea.text) } else if(e.source==ingredientNameField) { if(!recipeList.selection.items.isEmpty && !ingredientList.selection.items.isEmpty) { val rIndex=recipeList.selection.leadIndex val iIndex=ingredientList.selection.leadIndex changeIngredientName(rIndex,iIndex) } } else if(e.source==amountField) { if(!recipeList.selection.items.isEmpty && !ingredientList.selection.items.isEmpty) { val rIndex=recipeList.selection.leadIndex val iIndex=ingredientList.selection.leadIndex changeAmount(rIndex,iIndex) } } } menuBar=new MenuBar { contents += new Menu("File") { contents += new MenuItem(Action("Open")(openFile)) contents += new MenuItem(Action("Save")(saveFile)) contents += new Separator contents += new MenuItem(Action("Exit")(exit(0))) } contents += new Menu("Recipe") {

new ScrollPane(directionsArea)) -> BorderPanel.Position.Center)

CHAPTER 11.

GUIS

PSU

} frame.visible=true while(true) {}

} } size=new Dimension(800,600)

contents += new MenuItem(Action("Add")(addRecipe)) contents += new MenuItem(Action("Remove")(removeRecipe))

ke some time to run through this ode nd mke sure you understnd ll of the piees of itF he wy it ws presented in this setion re)ets how you might write itF riting ode is very nonEliner proessF ou n9t expet to write progrm from top to ottom stright throughF ou will generlly jump from one prt of the ode to notherD hitting on the res tht you need to ompleteF his ode mkes extensive use of funtions to rek things downF hoing this in your own ode will help you keep things orgnized nd mke it esier to understndF here re numer of di'erent spets of this ode tht re less thn idelF here re wys to put the qs into inonsistent sttesF st lso isn9t extly roust when it omes to the reding of (les nd you n mke it rsh if you ply with it someF pinding these shortomings nd (xing them is left s n exerise for the studentF

Self-Directed Study
inter the following sttements into the iv nd see wht they doF ome will produe errorsF ou should try to (gure out whyF ry some vritions to mke sure you understnd wht is going onF

scala> def succ(n:Int):Int = n+1 scala> succ(1)


333

Exercises
IF ixerise

Projects
IF rite funtionl lultor in qsF ou need to hve t lest the si four mth opertionsF peel free to put in other funtionlity s wellF PF sf you did projet VFS on prsing hemil equtionsD you might onsider doing this prolem s wellF he hemil prser isn9t required for this though so you n strt here if you wntF sn tht prolemD the hemil eqution ws onverted to system of liner equtionsF ystems of liner

CHAPTER 11.

GUIS

PSV

equtions n e represented s mtrix equtionsF por this prolem you will uild qs tht represents mtries s tles then lets you edit them nd do si opertions of ddition nd multiplitio on themF o keep things esyD the mtrixes will e squreF ou should hve menu option where the user n set the size of the mtriesF hey should e t lest PxPF he qs will disply three mtries tht we will ll eD fD d gF he user gets to enter vlues into e nd fF he vlue of g is set when the user selets menu options for dd or multiplyF QF rite qs to ply si minesweeper gmeF ou n use qridnel of uttons for the disply nd the user intertionF he hllenge in this prolem is deiding how to store the mines nd ssoite them with uttonsF here re mny wys to do thisF tudents should think out di'erent pprohes insted just rushing into oneF RF his projet ontinues the line of ry tring optionsF ou should uild qs tht lets you edit seneF ou should hve lists of spheresD plnesD nd light souresF ih one should hve the geometri settings s well s olor informtionF ou need to hve menu options to sve to (le or lod from (leF SF iditing rooms for the mp trversl in projet IHFQ using text editor in si text (le n e hllenging nd is error proneF por this resonD it ould e helpful to hve qs tht lets you edit the roomsF st n disply list of rooms tht you n selet from nd then other options for setting vlues on the seleted roomF ou need to hve menu options for loding (leD sving (leD nd dding roomF por little extr hllenge onsider putting in the option to remove roomF xote tht when you do thisD the indexes of ll the rooms fter tht one hngeF TF por this projet you will write qs tht lets users uild shedules of oursesF st should red informtion on the ourses tht re eing o'ered from (leF st needs to hve qs elements tht let you pik ourses you wnt to tke nd put them into di'erent listF ou should lso e le to remove ourses from tht listF qive the user menu options to sve nd lod the uild shedulesF ou don9t hve to del with on)its in times or even duplites of ourses right nowF tust let the user uild shedule from optionsF gonsider how to prevent di'erent types of on)its nd do tht if you wnt n extr hllengeF UF sn this projet you will write qs tht n e used to del with sttisE tis from your fvorite sportsF row this works will very lot etween sportsF ou need to hve user intertivity for loding in di'erent (les nd nrrowing down wht is displyed in some wyF VF wke progrm tht displys musi dtseF ou wnt to store signifE int informtion for di'erent songs inluding the nme of the songD the

CHAPTER 11.

GUIS

PSW

rtistD the lumD the yer relesedD nd nything else you (nd signi(intF he progrm should e le to disply the informtion for ll the songs s well s llow the user to nrrow it down to ertin rtistsD lumsD yersD etF

Chapter 12

Graphics
xot everything tht you might ever wnt to put into qs is prt of the stndrd qs lirryF hey hve only dded elements tht re used firly frequentlyF here re lso times when you wnt to disply your own grphisD something ompletely unique to your progrmD in qsF sn order to do thisD you hve to e le to write grphis odeF l does not hve its own grphis lirryF his is euse the one in tv is quite omplete nd works well in l styleF he grphis pilities of tv we will e using t olletively referred to s tvPh euse they re the PEh grphis lirries in tvF he types tht we will use re primrily loted in three di'erent pkgesX jvFwtD jvFwtFgeomD jvFwtFimgeF

12.1 Custom Drawn Panels


he (rst wy tht we will look t dding our own grphis to qs is y reting nel tht drws wht we wnt when it is displyed on the sreenF he method for doing this is to mke new nel nd then hnge the wy it is pinted to the sreenF he nel type hs method in it lled pint whih is pssed single rgument of type jvFwtFqrphisPhF e wnt to reple this method in our pnelF he t of hnging wht method does is lled overriding nd we will do it with the override keywordF he syntx for this looks like the followingF

val panel=new Panel { override def paint(g:Graphics2D) { // Draw to g } }


if you try this in your ode mke sure tht you import jvFwtFqrphisPh so tht it will know where to (nd tht typeF PTH

CHAPTER 12.

GRAPHICS

PTI

his pnel n then e dded to qs in the sme wy tht you would dd ny other pnel to qsF por this hpterD we will simply mke our ustom drwn pnel the entire ontents of our frmeF

12.2 java.awt.Graphics2D
he min pilities of the tvPh lirry re essed through the qrphE isPh lss in the jvFwt pkgeF his lss hs numer of di'erent methods tht we n rek into di'erent groupsF e list few of them hereF o see ll of them you would need to go to the tv esF

hrwGpill wethods

        

drw@sXhpeA drwvine@xIXsntD yIXsntD xPXsntD yPXsntA drwet@xXsntD yXsntD widthXsntD heightXsntA drwsmge@imgXenderedsmgeD xXsntD yXsntD osXsmgeyserverA drwsmge@imgXenderedsmgeD xXsntD yXsntD widthXsntD heightXsntD osXsmgeyserverA drwenderedsmge@imgXenderedsmgeD trnsXe0nernsformA drwtring@strXtringD xXsntD yXsntA (ll@sXhpeA (llet@xXsntD yXsntD widthXsntD heightXsntA

et wethods

    

setint@pintXintA settroke@strokeXtrokeA setrnsform@trnsXrnsformA setpont@fontXpontA setglip@lipXhpeA

qet wethods

    

getintXint gettrokeXtroke getrnsformXrnsform getpontXpont getglipXhpe

yther wethods

CHAPTER 12.

GRAPHICS

PTP

    

rotte@thetXhouleA rotte@thetXhouleD xXhouleD yXhouleA sle@sxXhouleD syXhouleA sher@shxXhouleD shyXhouleA trnslte@txXhouleD tyXhouleA

he drw nd (ll methods tully do the drwingF he set methods hnge how things re drwn while the get methods let us sk out the urrent settingsF he other methods lso impt the wys in whih things re drwnF o illustrte how this works we n put the reple the omment in the pint method with single line tht does the simplest drwing possileF

g.fillRect(20,20,200,200)
his line drws retngle whose top left orner is PH pixels right of the left edge nd PH pixels down from the topF st lso hs width nd height of PHH pixelsF he result of dding this line is shown in (gure IPFIF ou ould mke similr lls to drwvine nd drwetF hese methods tht you ll e pssing in oordintes re prt of the tv grphis lirry tht predtes tvPhF hile they re simple to useD they lk )exiility nd powerF

12.2.1 Shapes
he tvPh lirry dded signi(nt level or strtion with hving (ll method tht tkes hpeF his one method is remrkly powerfulD ut we will only see little it of tht power in this hpterF sn order to use this method or the losely relted drw methodD we hve to e le to rete ojets of the hpe typeF he jvFwtFetngle type is hpeF sn dditionD most of the jvFwtFgeom pkge is dedited to providing you with di'erent types of shpesF rere re few of the ones you n hoose from nd how you would go out mking themF sf you re going to e using these you proly wnt to hve import jvFwtFgeomF in your odeF

erPh E his is n r of n ellipseF st n e reted s n open r or it n e losed either s pie slie or using hordF ou ould reE te one with new erPhFhoule@xXhouleD yXhouleD wXhouleD hXhouleD strtXhouleD extentXhouleD typeXsntAF he type n e erPhFyixD erPhFgryhD or erPhFsiF ere E his is very generl shpe type tht you n initilly rete from ny other shpe with new ere@sXhpeAF he power of this type is tht you hve methods like ddD intersetD nd sutrt tht will omine res to rete ritrrily omplex shpesF guigurvePh E wkes urve desried y ui polynomils in xD yD nd zF ou n rete this y lling new guigurvePhFhoule@xIXhouleD yIXhouleD trlxIXhouleD trlyIXhouleD trlxPXhouleD trlyPXhouleD xPXhouleD yPXhouleAF

CHAPTER 12.

GRAPHICS

PTQ

pigure IPFIX he result of doing simple drwet inside of pintF

CHAPTER 12.

GRAPHICS

PTR

illipsePh E en ellipse tht you n mke using new illipsePhFhoule@xXhouleD yXhouleD wXhouleD hXhouleAF he spei(ed x nd y position is the top left orner of the ounding retngle for the ellipseF vinePh E e line tht you n mke with new vinePhFhoule@xIXhouleD yIXhouleD xPXhouleD yPXhouleA or new vinePhFhoule@pIXointPhD pPXointPhAF thPh E e generl pth in Ph spe tht you n uild s empty or using n existing shpeF ou n dd to the pth with methods like moveoD lineoD qudoD or urveoF ointPh E e point in Ph spe you mke with new ointPhFhoule@xXhouleD yXhouleAF udgurvePh E wkes urve desried y qudrti polynomils in xD yD nd zF ou n rete this y lling new udgurvePhFhoule@xIXhouleD yIXhouleD trlxIXhouleD trlyIXhouleD xPXhouleD yPXhouleAF etnglePh E epresents retngleF ou mke one with new etE nglePhFhoule@xXhouleD yXhouleD wXhouleD hXhouleA where @xD yA spei(es the top left ornerF oundetnglePh E his is retngle with rounded ornersF ou mke one with new oundetnglePhFhoule@xXhouleD yXhouleD wXhouleD hXhouleD rwXhouleD rhXhouleAF
wost of these re firly strightforwrdF he exeptions re the ere nd thPh typesF snterested reders re direted to the tv es for more deE tils on these nd how to use themF por the types tht end with PhD they n e reted with either Fplot or FhouleF e hve used Fhoule in the list ove euse mkes things simpler for our purposes hereF e n demonstrte quite few of these in just few lines of odeF sn the ody of the pint method put the following lines insted of the ll to gF(lletF

g.fill(new g.draw(new g.fill(new g.draw(new

Rectangle2D.Double(20,20,50,80)) Ellipse2D.Double(0,200,500,300)) Arc2D.Double(250,0,250,250,45,270,Arc2D.PIE)) QuadCurve2D.Double(0,500,250,0,500,500))

hen you run this ode you will get window like tht shown in (gure IPFPF

12.2.2 Settings
hrwing shpes provides signi(nt mount of power nd )exiilityF roweverD there re some ler limittions tht re visile in (gure IPFPF he most signifE int of these is the ft tht everything is ppering in the sme olor on the defult light gry kgroundF enother limittion is tht the shpes re eing drwn with thinD single pixels linesF sn order to get round these limittionsD we need to e le to tell the qrphisPh ojet to drw things in di'erent wysF his is done y hnging vrious settingsF

CHAPTER 12.

GRAPHICS

PTS

pigure IPFPX e smple drwing showing retngleD ellipseD rD nd qudrti urve mde with lls to (ll nd drwF

CHAPTER 12.

GRAPHICS

PTT

12.2.2.1 Paint
he most signi(nt setting in most pplition is the pint settingF rior to tvPhD this ws simple olor settingF roweverD when you drw something there re lot more options thn just hving singleD solid olorF he int type is wy of representing these di'erent optionsD just like the hpe type is wy of generlly representing the di'erent types of things tht you might wnt to drwF he min options you n use for pint re listed hereF

golor E olid olors re still helpful nd the golor type represents theseF e lot of stndrd olors re prede(ned for youF o you n use golorFwhiteD golorFlkD golorFredD golorFgreenD golorFlueD etF ou n lso mix your own olors y omining di'erent mounts of redD greenD nd lue with either new golor@rXplotD gXplotD XplotA or new golor@rXsntD gXsntD XsntAF sf you use the plot versionD the vlues should e etween HFHf nd IFHfD inlusiveF sf you use the snt version they should e etween H nd PSSD inlusiveF e fourth rgument n e dded to either of these tht is the mount of lph whih represents opityF e zero lph vlue mkes the olor ompletely trnsprentF qrdient ints E here re numer of grdient pints you n use inluding these twoF

 vinerqrdientint E his pint llows the olor to hnge grdE

ully ross lineF ou n speify the endpoints of the line nd multiple olors tht you wnt nd where you wnt them on the lineF here is no vrition in olor long the diretion perpendiE ulr to the lineF ou n mke one of these with new vinerqrE dientint@strtXplotD strtXplotD endXplotD endXplotD frE tionsXerryplotD olorsXerrygolorAF he frtions should e eE tween HFHf nd IFHfD it should egin with HFHf nd end with IFHfD nd there should e s mny elements in frtions s there re in olorsF vry s you move outwrd rdilly from given lotionF ou n mke one of these using new dilqrdientint@xXplotD yXplotD rdiusXplotD frtionsXerryplotD olorsXerrygolorA or new E dilqrdientint@xXplotD yXplotD rdiusXplotD fxXplotD fxXplotD frtionsXerryplotD olorsXerrygolorD ylewethodXwultipleqrdientintFgylewethodAF he ltter form llows you to speify n o'Eenter fol pointF he yle method is desried nextF provide n extr rgument when you mke them speifying wht you wnt to hve hppen outside the norml ounds of the grdientF fy defult there is no yling so solid olor is used in these resF roweverD you n lso speify tht the olors repet or re)etF o do thisD use one of the following three onstntsF

 dilqrdientint E his pint style llows you to hve olors tht

 gyle yptions E por eh of the grdient pints listed ove you n

CHAPTER 12.

GRAPHICS

PTU

wultipleqrdientintFgylewethodFxyggvi wultipleqrdientintFgylewethodFiie wultipleqrdientintFgylewethodFipvig extureint E his will (ll the pinted re using spei(ed imge tht is strethed over n re nd repeted outside tht reF ou n mke one with new extureint@txtrXfu'eredsmgeD nhorXetnglePhAF he fu'eredE smge type will e desried in setion IPFQFIF
hese di'erent pint styles give us signi(nt mount of power nd ontrol over the oloring of things tht re drwnF e n use them to (ll our pnel with lnkD white kground then (ll in eh of the di'erent things we drew ove with di'erent type of pintF he following ode n e put in the pint method to illustrte the di'erent types of pints other thn the extureintF

g.setPaint(Color.white) g.fill(new Rectangle2D.Double(0,0,size.width,size.height)) g.setPaint(Color.red) g.fill(new Rectangle2D.Double(20,20,50,80)) g.setPaint(Color.blue) g.draw(new Ellipse2D.Double(0,200,500,300)) g.setPaint(new RadialGradientPaint(375,125,125,300,125, Array(0.0f,0.3f,0.8f,1.0f), Array(Color.yellow,Color.cyan,Color.magenta,Color.green), java.awt.MultipleGradientPaint.CycleMethod.REPEAT)) g.fill(new Arc2D.Double(250,0,250,250,45,270,Arc2D.PIE)) g.setPaint(new LinearGradientPaint(200,500,300,250, Array(0.0f,0.4f,0.7f,1.0f), Array(Color.white,Color.darkGray,Color.lightGray,Color.black))) g.draw(new QuadCurve2D.Double(0,500,250,0,500,500))
his ode will produe the output shown in (gure IPFQF ih of the di'erent shpes is drwn with the pint tht is spei(ed efore itF

12.2.2.2 Stroke
he min prolem with wht is shown in (gure IPFQ is tht you n9t relly tell wht olor the (gures tht were drwn reF his is euse they re drwn with lines tht re only single pixel in widthF o (x this we need to introdue the next setting on the qrphisPhD the strokeF here is only one type of stroke provided in tvF st is lled fsitrokeF he nme is it misleding though euse this one type of stroke hs ll the pilities you re likely to needF here re severl forms tht you n use to rete new fsitroke nd they rnge from simple djustment of the width to enling dotted lines with rounded endsF rere re the di'erent optionsF

CHAPTER 12.

GRAPHICS

PTV

pigure IPFQX his (gure shows wht we get when we dd some pint settings to the drwing of shpes tht we hd eforeF

CHAPTER 12.

GRAPHICS

PTW

new fsitroke@widthXplotA new fsitroke@widthXplotD pXsntD joinXsntA new fsitroke@widthXplotD pXsntD joinXsntD miterlimitXplotA new fsitroke@widthXplotD pXsntD joinXsntD miterlimitXplotD dshXerryplotD dshhseXplotA
hile the (rst one is rther strightforwrdD some of the settings in the others require some explntionF he p vlue spei(es the style in whih you wnt the ends of lines to e hndledF here re three options for this vlueF

fsitrokeFgef fsitrokeFgeyxh fsitrokeFgeei


he utt nd squre options oth produe squre endingF he di'erene is tht the squre p style extends the end hlf the width of the line eyond the end pointF he round p style puts irle on the end with rdius tht is hlf the width of the strokeF he join setting determines how the joints etween lines re drwnF o see why this is neededD simply piture two segments s retngles tht hve ommon midpoint on one edgeF sf nothing is done to (ll it inD there will e wedge missingF here re three options for how to (ll it inF

fsitrokeFtysxfiiv fsitrokeFtysxwsi fsitrokeFtysxyxh


he evel setting simply onnets the outer orners with stright lineF he round setting (lls in the missing piee with pie pieeF he miter setting extends the outer edges until they meet to mke shrp pointF yne potentilly prolem with the miter option is tht if the lines ome together t very smll ngleD the miter n grow to e very longF his is why you n speif miter limit to work s mximum length for the miterF he longest form of onstruting fsitroke llows you the ility to mke dshed or dotted linesF st tkes n rry of plots tht spei(es the dshing sequeneF he numers in the rry tell how long the line will e drwnD then notEdrwnD in repeting fshionF he dshhse llows you to hve the dshing strt somewhere in the middle of the sequeneF o illustrte some of these feturesD we9ll dd two lines to our smple odeF fefore the ellipse is drwn we dd this lineF

g.setStroke(new BasicStroke(6f))

CHAPTER 12.

GRAPHICS

PUH

pigure IPFRX his is wht the drwing looks like fter we hve dded some stroke settings for the two elements tht re drwn insted of (lledF his will mke the line tht is used for the ellipse y six pixels ross nd fr more visileF fefore the udgurve is drwn we insert this lineF

g.setStroke(new BasicStroke(4f,BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL,1f, Array(8f,8f,14f,14f),0f))


his mkes dshed line tht is four pixels thik with round ps on the end of segmentsF he result we get when these re oth dded is shown in (gure IPFRF

CHAPTER 12.

GRAPHICS

PUI

12.2.2.3 Font
hen you ll the drwtring methodD the text is written using the urrent font t the spei(ed lotionF st is worth noting wht tht lotion isF o help illustrte thtD we9ll dd the following ode to the end of the pint methodF

g.setPaint(Color.black) g.drawString("A test string to print.",20,20) g.setStroke(new BasicStroke(1.0f)) g.drawLine(20,20,200,20)


his sets the olor to lkD drws stringD then mkes the stroke nrrow gin nd drws line going from the sme position s the string nd to the leftF he result of dding this ode is shown in (gure IPFSF ht you n see from this is tht the position for string is not the top left orner s it is for most of the shpesF por stringD the position would e the eginning of the ottom line if the text were to e written on lined pperF o letters like 9g9 nd 9p9 dip elow the yEoordinteD ut most of the text is ove itF iverything goes to the right of the xEoordinteF ou n hnge the font tht is used y lling the setpont methodF his method tkes single rgument of the type jvFwtFpontF o uild font we simple ll new pont@nmeXtringD styleXsntDsizeXsntAF he nme n e ny vlid font tht the mhineF o e sfe there re few defults tht re provided in the pont lssF

pontFhsevyq pontFhsevyqsx pontFwyxyegih pontFexisp pontFisp


he style rgument n e omposed of the following vluesF

pontFfyvh pontFsevsg pontFvesx


ou n omine these with itwise orD |D whih ws disussed in setion SFVF he size should e point sizeF yne of the hllenges in working with drwing strings to grphis is (guring out how lrge the string will e when it is drwnF he simplest wy to do this is to use the gettringfounds@strXtringD frXjvFwtFfontFpontendergontextA method of the pont typeF sf you ren9t mking your own speil fontD you n ll the getpont@A method on the qrphisPh ojet to get the one tht is

CHAPTER 12.

GRAPHICS

PUP

pigure IPFSX e simple exmple of writing string to grphisF

CHAPTER 12.

GRAPHICS

PUQ

urrently eing usedF he simplest wy to get pontendergontext is to ll getpontendergontext@A on the qrphisPh ojetF qetting the ounds will return to you etnglePh tht will ound the drwing of the stringF ou n get the positionD widthD nd height of tht retngle to determine where you wnt to ple the string to mke it entered or whtever other e'et you desireF

12.2.2.4 Clip
xormlly the things tht you drw to qrphisPh will e ut o' y the either the edge of whtever it is drwing toF prom wht we hve done so fr tht edge would e the extent of the nelF st ould lso e the ounds of n imge s we will see in setion IPFQF roweverD there re times when you wnt the ounds to e rti(illy lipped down to something smllerF en exmple of this would e when you re drwing strings or imges tht re igger thn the re you hve lloted for them in your displyF snsted of hving them lek out into other resD you wnt to lip themF sn tvPhD you n set the lip to ny hpe ojetF his gives you signi(E nt )exiilityF wost of the time you might wnt to lip to retngleD ut you hve the option of using n illipsePhD oundetnglePhD or even something fr more omplex like n ereF woving the lip round while drwing the sme imge n produe some interesting e'etsF sf the lip is irle it will look like you re moving spotlight roundF wore omplex lips n produe otherD similr types of e'etsF

12.2.2.5 Transform
he lst setting tht we will onsider is tht of trnsformF he next setion is dedited entirely to the topi of trnsforms so this will e the rief introE dutionF hen you set the trnsform on qrphisPh ojetD it will impt ll susequent elements tht re drwnD inluding strings nd imgesF he trnsE formtions n e s simple s moving things round or rotting elements or they n e more omplex omintionsF e simple exmple of when you would wnt to use trnsform is to write text tht is oriented in some diretion other thn left to rightF

12.2.3 Ane Transforms


es ws just mentionedD the things you drw to qrphisPh ojet n e ltered y trnsformtionsF wore spei(llyD they n e drwn fter eing hnged y n 0ne trnsformF tvPh de(nes the jvFwtFgeomFe0nensform type to represent theseF en 0ne trnsform is one tht preserves prllel linesF o if two lines re prllel efore the trnsformtion is ppliedD they must e prllel fter it is pplied s wellF smpliit in this is tht lines re preserved s wellF here re four types of si 0ne trnsformtionsF

rnslte

CHAPTER 12.

GRAPHICS

PUR

otte le her
eny omintion of these is lso n 0ne trnsformtionF he e0nernsform is represented y QxQ mtrix in the omputerD the detils of whih we will generlly ignoreF snterested reders n look t the es pge for some detils or should onsider ourse in grphis whih should over the detils of mtrix trnsforms for pplition in oth PEh nd QEh grphisF hen you ll new e0nernsform@A you get n identity trnsformF his is trnsform tht doesn9t hnge nything nd is represented for the identity mtrixF here re options for pssing rguments tht will let you uild the trnsformtion mtrix in whtever mnner you desireF sn generl thoughD you don9t wnt to go down to the level of the mtrix elementsF xormlly you wnt to e le to speify how muh of rottion or trnsltion you wntF here re numer of methods tht you n ll to do extly thisF

e0nernsformFgetottesnstne@thetXhouleA e0nernsformFgetottesnstne@thetXhouleD nhorxXhouleD nhoryXhouleA e0nernsformFgetlesnstne@sxXhouleD syXhouleA e0nernsformFgethersnstne@shxXhouleD shyXhouleA e0nernsformFgetrnsltesnstne@txXhouleD tyXhouleA
hese methods return e0nernsform instnes tht produe the spei(ed trnsformtionsF por the rottionsD the ngleD thetD should e given in rdinsF e0nernsforms n e omined s wellF his n e done in generl wy with the ontente@txXe0nernsformA methodF here re lso methods to uild up more omplex trnsformsF

rotte@thetXhouleA rotte@thetXhouleD nhorxXhouleD nhoryXhouleA sle@sxXhouleD syXhouleA sher@shxXhouleD shyXhouleA trnslte@txXhouleD tyXhouleA
hese methods will lter the trnsform ojetD whih is mutleD to inlude this new trnsformF st should e noted tht the qrphisPh ojet s whole hd nerly identil methodsF glling those methods will pply these hnges to the e0nernsform tht is eing used for drwingF o illustrte wht trnsform n doD we9ll dd one line of ode into our running exmpleF

CHAPTER 12.

GRAPHICS

PUS

pigure IPFTX his (gure shows wht hppens when we do rottion efore drwing our stringF

g.rotate(math.Pi/4)
his line should e inserted fter the udgurve is drwn nd efore the tring is drwnF he result of dding this is shown in (gure IPFTF xotie how the orienttion of the string hs een hngedF his version of rotte does the rottion out the origin whih is t the top left orner y defultF e turned it through /4 rdins whih is the sme s RS degreesF

12.3 Images
hen we drw with qrphisPh ojetD we hve to e drwing to somethingF o fr tht something hs lwys een nel tht is displyed on the sreenF

CHAPTER 12.

GRAPHICS

PUT

ht isn9t the only optionD howeverD we n lso drw to imgesF he imge type in tv is very generl nd )exileD ut most of the time we will e using it to represent rster sed grphiF e rster is PEh rry of little points lled pixels @short for piture elementAF he term pixel is used rther rodly these dys s prt of the term megpixel tht n desrie the resolution of digitl mers or grphil displysF

12.3.1 BueredImage
he jvFwtFimgeFfu'eredsmge is the primry rster sed imge in the tv lirriesF o rete lnk imge you n ll new fu'eredsmge@widthXsntDheightXsntDimgeypeXsntAF he width nd height re mesured in pixelsF he imgeype n e ny of numer of di'erent vlues de(ned in fu'eredsmgeF por our purposes we will lwys use fu'eredsmgeFisxeqfF his types gives you rod olor rnge nd full trnspreny possiilities y pking lphD redD greenD nd lue vlues into single sntF ou n look in the es for the other types tht re ville s well s other onstrutors for fu'eredsmgeD ut in this ook we will limit ourselves to these possiilitiesF sing thisD we might rete SHHxSHH pixel imge with the following odeF

val img=new BufferedImage(500,500,BufferedImage.TYPE_INT_ARGB)


yne you hve n imge the next question is wht n you do with itF here re quite few di'erent methods you n lled on fu'eredsmgeF he ones tht we (nd to e most signi(nt re s followsF

reteqrphisXqrphisPh E eturns n ojet of type qrphisPh tht n e used to drw to this imgeF getreightXsnt E eturns the height of the imge in pixelsF getqf@xXsntD yXsntAXsnt E eturns pked eqf vlue for the pixel t lotion @xD yAF his is helpful for determining wht is t ertin lotions in the imgeF his vlue ould e ompred to n snt tht you pk yourself or hex literlF roweverD it n lso e ompred to the result of the get qf method in golorF getuimge@xXsnt yXsntD wXsntD hXsntAXfu'eredsmge E eturns new imE ge tht is pulled from retngulr region of this imgeF getidthXsnt E eturns the width of the imge in pixelsF setqf@xXsntD yXsntD rgXsntA E ill set the eqf vlue t the spei(ed @xD yA positionF ou n pk your own eqf vluesD use hexD or use the getqf method in the golor typeF o to turn the top left pixel lk you might do thisX imgFsetqf@HDHDgolorFlkFgetqfAF

CHAPTER 12.

GRAPHICS

PUU

he reteqrphis method is proly the most signi(nt s it gives you k qrphisPh ojet tht you n use to drw to the imge in the sme wy tht we hve een using them to drw to the pnel on the sreenF he getqf nd setqf methods n lso e very useful when you wnt to know extly wht is t pixel or hve full ontrol over wht olor pixel is drwn sF xote tht n eqf vlue of H is ompletely trnsprent lkF o if you set ll the pixels in n imge to e H the imge will e trnsprentF ht wy you n drw things on it nd not hve kground show up round them if you drw tht imge on top of something elseF

12.3.2 Reading and Writing Images


sn ddition to reting lnk imgesD you often wnt to e le to red imges from (lesF sn some situtions it n lso e nie to sve k imges to (leF foth of these tivities n e omplished esily with the jvxFimgeioFsmgesy typeF por redingD there re two methods tht re of interestF

smgesyFred@inputXjvFioFpileAXfu'eredsmge smgesyFred@inputXjvFnetFvAXfu'eredsmge
he (rst method should e pssed pile ojetD muh like wht we hve done previously with nnerF his will red in n imge enoded in stndrd formtD suh s tiqD qspD or xqD from the spei(ed (leF he seond method does silly the sme thingD ut not from (leF his method will red the imge dt from v so it n e loted ross the network on nother mhineF por ovious resonsD the v lss is prt of the jvFnet pkgeF ou n mke new v ojet with new v@speXtringAF he spe should e v formtted just s it would e in your rowserF yne you hve red in (leD you n drw it with qrphisPh ojet to inlude it in wht you re displying on sreenF ou n lso ll reteqrphis to get the qrphisPh ojet tht will llow you to drw on this imge to edit it in some wyF yne you hve edited itD you might wnt to write it k out to diskF ou n do this y lling smgesyFwrite@imXenderedsmgeD formtE xmeXtringD outputXpileAXfoolenF e fu'eredsmge is type of endered imE geF he formtxme is string with the informl nme of the formt type you wnt to use for the (leF o see ll the formts tht re supported y your omE puter nd instlled softwre you n run smgesyFgetpormtxmesXerrytringF

12.3.3 Double Buering


iven in situtions where you re drwing to pnelD it is often dvisle to use n imgeF he tehnique is lled doule u'ering nd it improves performne nd redues )iker in nimtionsF hen you drw to the qrphisPh ojet tht is pssed into the pint methodD the things tht you drwn re displyed on the sreenD one element t timeF xormlly it hppens so fst tht the user never notiesF roweverD if there re lrge numer of elements in the drwingD

CHAPTER 12.

GRAPHICS

PUV

or if you re repinting frequently for n nimtionD this n e visile nd n use )iker in the imgeF o speed things up nd eliminte the )iker you n rete n imge tht is the sme size s the pnelD do the drwing to the imgeD thn the drw tht imge to the pnelF he following ode shows wht suh pnel might look likeF

val panel=new Panel { var img:BufferedImage=null override def paint(g:Graphics2D) { if(img == null || img.getWidth < size.width || img.getHeight < size.height) { img=new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_ARGB) } val g2=img.createGraphics // Draw to g2 g.drawImage(img,0,0,null) } }
he (rst line in the nel retes new vrile to store imgesF he type fu'eredsmge is required here euse otherwise l will infer type of xullF sn the pint methodD the (rst thing tht hppens is hek to see if the imge hs een reted nd if it is lrge enough to over the pnelF sf notD new imge is retedF efter we re ertin tht we hve n imge of su0ient sizeD the ode gets the qrphisPh ojet for drwing to tht imge nd nything tht we wnt to drw is drwn to tht imgeF he lst thing to hppen in the method is to drw the imge to the pnel so it ppers on sreenF

12.3.4 Revisiting TexturePaint


xow tht we know out imges we n revisit one of the pint types tht ws disussed erlierD extureintF he ide of the extureint is to (ll in the drwnG(lled shpe with spei(ed imge tht it repeted on ertin gridF hen you mke extureint you provide it with n imge nd retngle tht is referred to s the nhorF he imge will pper inside of tht retngle nd will e repeted in tiling pttern round itF o illustrte thisD we n enter the following ode efore setting the olor to lue for the ellipseF

g.setPaint(new TexturePaint(ImageIO.read(new File("rtImg.png")), new Rectangle2D.Double(0,0,200,200))) g.fill(new Ellipse2D.Double(0,200,500,300))


his (lls in the sme ellipseD ut does so with texture of (le tht ws loded o' diskF he result using this prtiulr (le is shown in (gure IPFUF

CHAPTER 12.

GRAPHICS

PUW

pigure IPFUX his imge displys the use of extureintF he ellipse is (lled with tiling of n imge tht is loded from diskF

CHAPTER 12.

GRAPHICS

PVH

12.4 Other Events


he stndrd omponents in the wing lirry hd ode in them to pulish events tht were spei( to the wy you interted with then or to mke it very esy to provide the tions for those intertionsF he nel doesn9t hve ny stndrd modes of intertionF he wy in whih the user interts with it is ompletely up to youF es suhD you hve to hndle events s somewht lower levelF e need to listen to the mouse nd keyord tions diretly nd ret to them ppropritelyF

12.4.1 Mouse Events


he mouse if often the most nturl wy to intert with omponents of qsF et (rst you might think tht the only thing you wnt to respond to with the mouse is the liksF roweverD if you tke minute to think out it you will relize tht lot of progrms intert with the mouse in more omplex wys thn just when you likF here re eight di'erent types of events tht the mouse n (reF st is unlikely tht you will re out ll of them with ny single pnelD ut you might need to hndle severl of them in order to produe the e'et tht you wntF hese mouse events re ville on ll omponentsD even the stndrd ones tht lredy hndle things in their own wysF his llows you to inlude your own ustom ehviorF por this resonD ll the omponents ontin n ojet lled mouseF he mouse ojetD in turnD ontins three ulisher ojets lled liksD movesD nd wheelF ih of these di'erent ulishers will give you inE formtion out di'erent things the mouse is doingF ou need to listen to the one or ones tht produe the events you needF o if you only need to know when the mouse is likedD you would need to do listeno@mouseFliksAF sf you wnted to know where the mouse ws moving or eing drgged toD you would dd mouseFmoves to the list of things you re listening toF his is list of the di'erent events in slFswingFevent orgnized y whih of the ulishers produes themF

wouseivent E ell of the events listed elow re ll sutypes of wouseiventF mouseFliks

    

wousegliked wouseintered wouseixited wouseressed wouseelesed

mouseFmoves

 wousewoved

CHAPTER 12.

GRAPHICS

PVI

 wousehrgged
mouseFwheel

 wouseheelwoved
ell of the mouse events ontin pointD soureD nd modi(ers s (eldsF he point (eld is jvFwtFoint nd it hs (elds in it for x nd yF he soure is gomponent so tht you n (gure out wht in your qs the mouse is over when the event is produedF he modi(ers re stored in n snt nd n give you informtion out whih mouse utton or uttons re downF eny time mouse utton goes downD wouseressed event will (reF hen the mouse utton goes upD wouseelesed event will (reF he wousegliked event only (res if the mouse utton goes down nd k up without the mouse movingF sf the mouse moves while it is downD insted of getting wousegliked eventD you will get wousehrgged events through the movementF snside of the retion to the eventD you will likely hnge some mutle dt tht lters wht is drwnF his hnge would utomtilly e seen in the drwingD howeverF o mke tht hppen you need to tell the pnel tht it should redrw itselfF o do thisD you ll the repint@A method of the pnelF his method doesn9t do the drwingD insted it shedules the drwing to e done in the future when the progrm isn9t too usyF he ext nture of how this type of thing works will e disussed in hpter PIF por now you only need to know tht if you wnt pnel to e drwn gin you should ll repint@AF

12.4.2 Keyboard Events


ou might lso wnt to hve your qs respond to keys eing pressed on the keyordF en exmple of this might e to hve something in your grphi tht hnges with letters or moves when rrow keys re pressedF he keyord events re pulished y the keys ojet in omponentsF o if you wnt to hve retions to the keyord you dd listeno@keysA in the odeF tust like with the mouseD there re severl types of di'erent events tht n ome from the keyordF ell of them fll under the rod heding of ueyiventF

ueyivent ueyressed ueyelesed ueyyped


his is simpler thn the mouseF here re only three di'erent types of eventsF he like the mouseD there re seprte events for pressed nd relesedF he ueyyped event is similr to wouseglikedD ut there isn9t ny equivlent to the mouse not movingF sn this seD the ueyyped event only (res when the key is norml hrter keyF st should lso (re with the repet rte you normlly

CHAPTER 12.

GRAPHICS

PVP

get when key is held downF o if you wnt to ret to rrow keys or other nonEhrter keystrokes you need to use ueyressed nd ueyelesedF hen you re listening for ueyyped you n use the hrXghr (eld of the event to (nd out wht hrter ws typedF he ueyressed nd ueyelesed events n9t hve they key represented y simple ghr euse they n do things tht ren9t norml hrtersF hey hve (eld lled key tht hs vlue spei(ed in the slFswingFeventFuey ojetF o if you wnt to hek to see if the up rrow key ws pressed you ould put the following in your odeF

if(e.key==Key.Up) ...
his ssumes tht the ueyressed or ueyelesed vrile is lled eF he uey ojet hs (elds for ll the other keys tht you n get on the keyord s wellF por full list you should hek in the esF sf you put in ode tht listens to the keys ulisher nd then dd retion to hndle the events you re interested inD you will likely e quite disppointed when you run the progrm nd nothing hppensF essuming tht something is rokenD you will proly strt putting print sttements into the ode to try to (gure out wht is hppeningF ht you will (nd is tht you ren9t getting ny key events t llD despite the ft tht you re listening for them nd hve proper ode to ret to themF he prolem reltes to onept lled fousF he urrently seleted element in qs is sid to hve fousF ueystrokes only go to tht omponentF o understnd thisD simply piture qs with severl text (elds in itF hen you typeD the hrters should not go to ll the text (elds t oneF snstedD your typing only ppers in oneD the one with fousFo get your pnel to reeive the key strokes you hve to give it the fousF ou n do this y lling the requestpous method on the pnelF st doesn9t help to do this efore the pnel is displyed so you n put it fter you set the frme to visileF st is proly lso good ide to hve mouse event tht requests fousF hepending on the pplitionD you might wnt to do this in wousegliked event or wouseintered eventF he former will only get fous if the user liks on the pnelF he ltter will give it fous ny time the mouse enters the pnel reF

12.5 Animation with Timer


st is lso possile tht you wnt something to hppen without ny keys eing pressed or the mouse eing usedF en exmple of this would e nimtionsF sn order to omplish this you should use jvxFswingFimer ojetF imer ojets use ode to e exeuted t regulr intervlsF e uild timer with new imer@delyXsntD listenerXjvFwtFeventFetionvistenerAF he dely is vlue given in milliseondsF he etionvistener type is used in the tv version of wing s something tht rets to simple tion like liking uttonF hese re used so muh tht the l version of wing inludes simple method for mking themD wingFetionvistener@tionX @jvFwtFeventFetioniventA ab

CHAPTER 12.

GRAPHICS

PVQ

nitAF rere gin we see type from the tv lirriesF ou will rrely hve to use this type in your ode thoughF utting this ll togetherD you ould mke imer with the following odeF

val timer=new javax.swing.Timer(100,Swing.ActionListener(e => { // code to mutate values used in drawing. panel.repaint() }))
he ll to repint is needed for the sme reson tht ws disussed in setion IPFRFIF he user will only see tht hnges tht hve een mde fter the next time the sreen is pintedF he full nme for the imer ws used here insted of n import sttement euse it is quite possile tht this is the only ple it will e usedF sf you (nd yourself typing it in more thn one you would proly wnt to hve n import sttementF he imer hs strt nd stop methods tht llow you to do extly wht they sy to itF he imer will not e running initillyF ou hve to ll the strt method to get it goingF he stop method n pose n interesting prolem if the reson for stopping is prt of the tion tht is supposed to hppen in the imerF sing the style shown oveD the tion in the imer is uilt efore the timer vrile tully existsF es suhD you n9t ll timerFstop inside of the tion ode using this pprohF o get round thisD we n use slightly di'erent style of setting up the timer in whih we (rst give it null tionD then dd n etionvistener to itF gode using this pproh might look like the followingF

val timer=new javax.swing.Timer(100,null) timer.addActionListener(Swing.ActionListener(e => { // code that potentially includes timer.stop(). panel.repaint() })
his is little longer thn wht we did erlierD ut it will let you ll the stop method if you hve reson toF

12.6 Putting it Together


e (nish this hpter with n exmple progrm tht inludes getting input from the mouse nd keyord nd tht uses imer in order to updte things t regulr intervlsF 333 hve pnel tht drws three thingsF yne goes with the mouseD one is ontrolled y keysD nd one hses fter the one following the mouseF

CHAPTER 12.

GRAPHICS

PVR

Self-Directed Study
inter the following sttements into the iv nd see wht they doF ome will produe errorsF ou should try to (gure out whyF ry some vritions to mke sure you understnd wht is going onF

scala> def succ(n:Int):Int = n+1 scala> succ(1)


333

Exercises
IF ixerise PF gontrol movement nd hek intersetionF

Projects
IF sf you did projet IHFI you should hve notied tht looking t the numE ers to (gure out wht is going on is quite pinF o see if prtiles re moving properly it relly does help to hve plot of their motionF por this projet you will dd qs with ustom drwn pnel onto tht progrm so tht you n drw where prtiles re lotedF he only hllenge in doing this is getting from the oordintes tht your prtiles re t to oordintes tht (t in norml windowF here re two wys to do thisF yne is to do the mth yourselfF peify minimum nd mximum vlue for x nd y nd use liner equtions to trnsform from the rnge @minDmxA to @HDwidthA or @HDheightAF ou n lso do this with n e0nernsform using omintion of sle nd trnslteF here is ene(t to eh pproh nd neither is signi(ntly hrder thn the otherF o mke the qs more funtionl you ould inlude text (elds tht llow the user to hnge the vlues of Xmin D Xmax D Ymin D nd Ymax F ou ould lso inlude heox tht lets the user selet whether the kground is lered eh time prtiles re drwnF ithout leringD you will see the pths of the prtiles s they moveF ith lering you will only see whtever shpes you use to drw the prtilesF PF por this projet you should write sript tht reds in text (le of numers nd plots the dtF ou n pik wht style of plotting you wnt to enle nd wht formt the dt should e inF es with the previous projetD the min hllenge in this is to onvert from the oordintes tht the dt points re in to something tht ppers niely on sreenF QF he movie ron @httpXGGwwwFimdFomGtitleGttHHVRVPUGAD relesed in IWVPD inluded numer of di'erent erly rde style gmesF yne of theseD light

CHAPTER 12.

GRAPHICS

PVS

ylesD n e simpli(ed down to level where it is very esy to writeF por this projetD you will do just thtF sn the gmeD the plyers ride yles tht leve olored wlls ehind themF unning into wll kills the plyerF he lst plyer live winsF por your implementtionD the wlls will e lines of pixels in fu'eredsmge nd the yle will just e the end where the line is growingF ou don9t hve to grphilly represent the yleF wo humns n plyF yne uses rrow keys nd nother uses lettersF ynly two keys re needed for ehD one to turn left nd one to turn rightF se imer to mke it so tht the yles move forwrd t onstnt speedF ueep fu'eredsmge tht shows the ply reF ou n mke newD lnk fu'eredsmge with the followingX vl imganew fu'eredE smge@SHHD SHHD fu'eredsmgeFisxeqfAF his mkes n imE ge tht is SHH pixels in width nd SHH pixels in heightF ou n use imgFgetqf@xXsntD yXsntAXsnt to get the pked qf vlue t prtiuE lr lotionF ou n lso use imgFsetqf@xXsntD yXsntD rgXsntA to set single pixel in the imgeF o get the qf vlue for stndrd olor do something like golorFredFgetqfF sing the imge to silly store the wlls prevents you from hving to keep tht dt in seprte rryF por n extr hllengeD try putting in omputer ontrolled plyerF his isn9t relly ll tht hrdF he esiest one to write is virtully impossile for humn to et euse it hs perfet re)exesF hrow in osionl rndom turns to mke things more evenF RF e step up from the ron vight gyles gme is the nke gmeF sn this gme single person ontrols snke tht goes round eting pples or something elseF ih time one is etenD the snke grows longerF his onE tinues until the nke runs into itselfF he reson this is more hllenging thn vight gyles leve wlls tht n sty until the progrm is doneF he wlls n lso e single pixel wideF ith nkeD the ody prts tht follow the hed hve to move euse the snke doesn9t simply get longer ll the timeF

SF yne of the erly edutionl progrmming lngugesD lled vogoD mde grphis esy to use y implementing turtle grphis system @httpXGGenFwikipediForgGwikiGurtlegrph he ide of turtle grphis is tht you hve ursorD typilly lled the turleD tht hs positionD nd orienttionD nd pen settingsF he tutrle n turn nd moveF hen it movesD it n either drw or notF imple systems only llow the turtle to move long stright lines nd tht is wht you will do for this projetF e simple wy to enode instrutions for turtle is with tringF hifE ferent hrters tell the turtle to do di'erent thingsF e 9p9 tells the turtle to move forwrd while drwingF e 9f9 tells it to move forwrd without

CHAPTER 12.

GRAPHICS

PVT

drwingF he 9C9 nd 9E9 hrters tell it to turn to the left nd right reE spetivelyF yther hrters n e dded to give the system more power nd lter projets will give you the opportunity to do soF he mount tht the turtle moves or turns for eh hrter is onsidered to e (xed prmeterF sing this systemD one ould drw squre y setting the ngle to WH degrees nd using the string pCpCpCpF wo squres tht re seprted ould e mde with pCpCpCpfpCpCpCpF wke qs tht hs extpield where the user n enter stringF ou might lso hve (elds for segment length nd turn ngleF here should e pnel thtD when pintedD will drw the pproprite set of linesF imply ignore ny hrters tht ren9t 9p9D 9f9D 9C9D or 9E9F TF por this projet you will model the proess of rystl growthF his might sound like something of hllengeD ut it isn9t relly ll tht hrdF grysE tls grow when mteril dissolved in solution meets surfe of the rystl nd stiksF he dissolved mteril moves round due to frownin motion nd is silly rndom wlkF ou strt the proess y putting seed rystl in the solution for stu' to stik toF por our purposesD the rystl is simply represented s one olor on top of kground tht is nother olorF rojet Q desries how you n mke n imge nd oth red nd set pixels on itF his imge should e drwn on pnel tht is in the qsF sf the user liks on the pnel it should dd new seed t the lik lotion @simply set the olor t tht point in the imge to the rystl olorAF here should e either utton or menu option to relese more prtiE lesF hen prtile is relesedD it should strt t one of the edgesF ou just need to keep trk of the xD y lotion of itF sing while loopD hve the prtile move rndomly round until the move would put it on top of spot tht lredy hs rystlF et tht point you hnge the pixel t the lotion the prtile hd een to the rystl olorF o move the prtile rndomly you ould use utilFndomFnextsnt@RA to get numer in the HEQ rnge nd move either upD downD leftD or right depending on tht vlueF sf move would put prtile outside of the imgeD simply ignore tht moveF he menu option should proly run through loop tht drops IHH or so prtiles nd lets eh run until it stiksF ou only need to repint fter ll hve found their pleF xote tht espeilly erly on when the rystl seed is smllD it n tke long time for prtile to run round until it hits tht seedF UF sf you hve een doing ry tring options in erlier projetsD it is time for you to (nlly see somethingF ou n use the ode you wrote for projet IHFP tht mkes grid of prmeter vlues nd simply set olors

CHAPTER 12.

GRAPHICS

PVU

in fu'eredsmge sed on the prmetersF o do this you will proly wnt to uild your own olorsF ou n mke new golor ojet y sying new golor@rXsntD gXsntD XsntA where rD gD nd re in the HEPSS rngeF lues outside of tht rnge will use n errorF imply disply the imge in pnel tht you hve put in the qs to see depth informtion for your ry treF VF 333 PEh simple gme like thing with moving hrtersD mpsD nd interE setion heksF WF 333 sliding numers puzzleF

Chapter 13

Sorting and Searching


ome of the most fundmentl things tht we do on omputers re to order dt ording to ertin vlues nd to serh through dt for vrious thingsF

13.1 Basic Comparison Sorts


here re mny di'erent wys in whih to sort dtF he most generl ones don9t require muh of the dtF ell they require is the ility to ompre elements to see if one should ome efore notherF hese omprison sorts re the ones tht re used most frequentlyD minly euse they re so )exileF here re limits on how fst they n e euse they ren9t ustomized to the dtD ut typilly their generlity trumps speedF et this point we ren9t even going to onsider the fstest omprison sed sortsF snstedD we will strt with some of the oneptully simpler sortsF fefore we do tht thoughD you should tke seond to think out how you sort things s humnF here re some di'erent senrios you ould onsiderF hen you were youngerD odds re tht you were given ssignments in shool where you hd to sort list of words into lphetil orderF ht pproh did you tke to doing thtc gould you write down stepEyEstep proedure to explin to smll hild who ws doing it for the (rst time how heGshe might go out itc he proedure tht you use might vry depending on wht you hve to work withF sn the list of wordsD you might need to write it down s sorted list nd you don9t wnt to hve to erse nd move things round if t ll possileF ou might e sorting folders in (ling inetF he folders n slide kwrd nd forwrdF hey don9t hve ny set positionD nd moving folder isn9t ll tht hrd to doF yn the other hndD imgine the silly sitution of hving to sort rs in prking lot y their liense pltesF he rs don9t move esilyF ih move tkes e'ort nd they ertinly don9t slide roundF ke some time to onsider how you would sort in these di'erent senriosF row does the type of ojet impt your pprohc pe n lso e n issueF sf you re sorting folders in ig room you might pik di'erent pproh thn PVV

CHAPTER 13.

SORTING AND SEARCHING

PVW

if you re in smll loset with (le inetF por the rsD you might pik one pproh if you re moving the rs from one long row to ompletely di'erent row thn you would if there ws only one open spe for you to prk rs in s you move things roundF he sorts tht we re going to work with here not only work with si omprison opertionD they re lso intended to work with rrys nd n work in pleF his implies tht they n e done using just single rryF ou don9t hve to mke opyF xot ll sorts hve this propertyF o this is like the prking lot with only few open spesF

13.1.1 Bubble Sort


he (rst sort tht we will desrie is something of lssi in omputer sieneF st isn9t e0ientF sn ftD you would e hrd pressed to onvine ny person to use this sort methodF st works for omputers euse they will do whtever you tell them even if it is extremely repetitive nd pedntiF st is only tught rodly euse it is so remrkly simple to desrieF he si ide of the ule sort is tht you wnt to run through the rry nd look t items tht re next to one notherF sf two items re out of orderD you swp themF yne pss through the rry won9t get it sorted unless it ws very lose to sorted to egin withF roweverD if you repet this proess over nd overD the rry will eventully get to sitution where it is sortedF sing this desriptionD there re few wys in whih the ule sort n e writtenF hey ll hve n inner loop tht looks something like the followingF

for(i <- 0 until a.length-1) { if(a(i) > a(i+1)) { val tmp=a(i) a(i)=a(i+1) a(i+1)=tmp } }
he end index of this loop n hnge over di'erent itertions to mke it more e0ientD ut the ide is the smeF he vlue i runs through the rry ompring eh element to the one fter itF sf the (rst is lrger thn the seondD then they do swpF he swp ode is the three lines inside of the ifF o piture wht this is doingD imgine the nlogy of rs in prking lotF he tmp vrile is n extr spe where you n move one rF o you strt y moving the (rst r to the empty speF efter tht you move the seond r into the spe the (rst one hd een inF o (nish it o'D you pull the r from the extr spe into the seond spotF he r nlogy isn9t perfetF hen we move r from one spot to notherD the spot tht is vted is left emptyF hen we do n ssignmentD the vrile we re getting the vlue from doesn9t lose the vlueF snstedD we hve two memory lotions tht oth hve referenes to the vlueF

CHAPTER 13.

SORTING AND SEARCHING

PWH

ht would e like hving seond version of the rF wuh of the time this is only tehnilityD ut there re times when it n e signi(nt s those extr referenes n hold onto memory tht you relly ren9t using nymoreF sn order to do full sortD this loop needs to e repeted over nd over ginF row mny times must it e repetedc o nswer tht we n oserve tht eh time throughD the lrgest unsorted vlue is pushed ll the wy to where it elongsF sf there re n elements in the rryD then fter nEI psses everything will ertinly e in ple1 F sing this logiD we n write the following odeF

def bubbleSort(a:Array[Double]) { for(j <- 0 until a.length-1) { for(i <- 0 until a.length-1-j) { if(a(i) > a(i+1)) { val tmp=a(i) a(i)=a(i+1) a(i+1)=tmp } } } }
sn this odeD the outer loop exeutes nEI times s the vlue j ounts up from H to nEPF ou will notie one other hnge in the inner loopF he stopping vlue for i hve een hnged from FlengthEI to FlengthEIEjF his is sed on the oservtion tht fter one pss the lrgest element is in the right lotion t the endF efter two pssesD the seond lrgest element is lso in the right ple nd so onF por this resonD the inner loop n stop one spot erlier eh time through euse there is no need to hek those vlues tht we lredy know re sortedF he sort would still work (ne with sutrting o' jD ut it would do roughly twie s muh workF he other thing tht this full sort inludes tht wsn9t pprent from just the inner loop is tht this funtion hs een written to sort n rry of houlesF es writtenD this won9t work if you pss in nything other thn n erryhouleF sf you need to sort something elseD you hve to write di'erent sortF here re mny wys in whih this is less thn idelD espeilly onsidering tht evE erything exept the type delrtion would work eqully well for errysntD errytringD or n rry of nything else tht works with greter thnF e9ll tlk out how to get round this in hpter PHF ehnillyD this ule sort might get the dt sorted nd then keep working on itF mller elements only move forwrd one slot on eh pssF sf the dt isn9t too fr out of order so tht nothing hs to move ll tht fr forwrdD the sort might get the dt in order efore the nEI itertions re ompleteF por this resonD you might wnt to use )gged ule sortF his is smll vrition on the norml ule sort tht uses while loop for the outer loopF st exits
1 We
don't have to put n things in place because if there are only n places and n-1 are in the right place, the last one most also be in the right place as it is the only one left.

CHAPTER 13.

SORTING AND SEARCHING

PWI

fter nEI itertions or if it goes through pss of the inner loop without doing ny swps s tht implies tht everything is lredy sortedF

def flaggedBubbleSort(a:Array[Double]) { var flip=true var j=0 while(flip && j < a.length-1) { flip=false for(i <- 0 until a.length-1-j) { if(a(i) > a(i+1)) { val tmp=a(i) a(i)=a(i+1) a(i+1)=tmp flip=true } } j+=1 } }
his ode dds few more lines to del with the )g nd the ft tht we hve to do the ounting ourselves with while loopF he )g is lled )ip nd it strts o' s trueF roweverD efore the inner loop strts it is lwys set to flse nd only get set k to true when swp is doneF

13.1.2 Selection Sort (Min/Max)


he next swp we wnt to onsider is one tht humns re fr more likely to employD espeilly in sitution like sorting the rs where moving rs round tkes signi(nt mount of e'ortF he sort is the seletion sort nd it is lled this euse it runs through the vlues nd selets one nd ples it where it elongsF sn order for this to work you hve to know where the vlue should goF his is esy if the vlue is either the lrgest or the smllest in the olletionF es suhD the seletion sort is typilly implemented s either minimum sort @minortA or mximum sort @mxortAF sn theory one n lso write minE mx sort tht piks oth nd moves them to where they elongF e will write minort hereF st is firly trivil to onvert this to mxortF he inner loop of the minort will run through ll of the urrently unsorted olletion nd (nd the minimum element in thtF sf tht element isn9t lredy where it should eD it is swpped into pleF por n rryD the ft tht this is swp is signi(ntF o understnd thisD think out the rsF hifting ll the rs over one is hrdF wpping two is muh esierF he rry is like the prking lot with (xed lotionsF gertin other dt strutures ould t more similr to (le folders whih slide round esily nd might llow shiftingF sf you use n rry nd shift insted of swpD the ode you produe will e oth longer nd signi(ntly slowerF

CHAPTER 13.

SORTING AND SEARCHING

PWP

def minSort(a:Array[Double]) { for(j <- 0 until a.length-1) { var min=j for(i <- j+1 until a.length) { if(a(i) < a(min)) min=i } if(min!=j) { val tmp=a(j) a(j)=a(min) a(min)=tmp } } }
es with the stndrd ule sortD the outer loop hppens nEI times s it hs to swp nEI elements into the lotions they elongF he ontents of the inner loop here re quite shortD just hek tht hnges the min vrile if neededF he swp itself is longer thn the loopF he seletion sort isn9t relly more e0ient thn ule sort in generlF roweverD euse the swp is outside of the inner loopD this sort n e muh more e0ient in those situtions where the swps re expensiveF his sitution n9t hppen for rrys in lD ut it n e true for rrys in some other lnguges or if the vlues eing sorted re ontined in (le insted of the memory of the omputerF

13.1.3 Insertion Sort


he lst sort we will disuss in this setion is nother one tht humns might onsider usingF st is lled the insertion sort euse the wy it works is to uild up sorted group of elements t the eginning of the rry nd eh new element is inserted into the proper lotion in tht groupF he dvntge this sort is tht it n do less hekingF yne it (nds the ple to put the element it n stop nd move to the next elementF st is prtiulrly e0ient if the rry is firly lose to sorted s eh element typilly doesn9t hve to e moved very frF he ode for n insertion sort n e written in the following wyF

def insertionSort(a:Array[Double]) { for(j <- 1 until a.length) { var i=j-1 val tmp=a(j) while(i>=0 && a(i)>tmp) { a(i+1) = a(i) i -= 1 } a(i+1) = tmp

CHAPTER 13.

SORTING AND SEARCHING

PWQ

he outer loop here still exeutes nEI timesD ut in di'erent wy nd for di'erent resonF snsted of strting t H nd stopping one short of the lst elementD this loop strts t I nd goes to the lst element of the rryF he reson for this is tht n rry of one element n e viewed s sorted rryF o we tke the (rst element s eing where it should e in group of IF hen we strt with the seond element nd potentilly move it forwrd if neededF he ode inside the outer loop n use some explining s wellD s this is it di'erent from wht we sw with the other two sortsF st egins with the delrtion of the vrile i whih egins t jEIF his is the index of the next element tht we need to ompre to the one we re movingF e lso delre temporry vrile lled tmp tht stores the vlue in the rry tht we re moving forwrdF rving the temporry vrile here prevents us from doing full swps nd mkes the ode oth shorter nd fsterF o understnd thisD onsider gin the exmple of moving rs in prking lotF gonsider you hve ten rsD the (rst eight of whih re lredy sortedF ou need to move the ninth one forwrd to the ple it elongsD potentilly severl spots downF ou wouldn9t do this y swpping rs one fter the otherF snstedD you would pull tht r out nd put it in the one empty spot to the sideF hen you would move the sorted rs downD one t timeD until you hd lered out the proper spotF et tht point you would drive the r from the spot on the side into the lineF ht mentl imge is extly wht this is doingF he while loop exeutes s long s we hven9t gotten down to the eginning of the rry nd the element we re onsidering is greter thn the one we re insertingF es long s tht is trueD we move the element up nd shift our ttention down to the next elementF hen we re doneD we put the temporry vlue where it elongsF

13.1.4 Testing and Verifying Sorts


he lst three susetions simply presented sorts s working produtsF sn relityD sorts re like ny other ode nd hve to e testedF portuntelyD sorts re firly esy to testF efter the sort hs ompletedD you should e le to run through the elements nd mke sure tht eh element is less thn or equl to the one fter itF es long s this is true for ll of the elementsD the rry hs een properly sortedF en impertive pproh to doing this might look like the followingF

def isSorted(a:Array[Double]):Boolean = { for(i <- 0 until a.length-1) { if(a(i)>a(i+1)) return false } true }
his ode does something tht we hven9t seen eforeF st uses return stteE mentF e hve seen tht the normllyD the lst sttement in funtion should

CHAPTER 13.

SORTING AND SEARCHING

PWR

e n expression nd the vlue of tht expression is wht the funtion returnsF st is lso possile to fore funtion to return erlier using return sttement s is done hereF sf t ny point we (nd onseutive elements tht re out of orderD there is fored return of flseF sf it gets ll the wy through the rry it returns trueF his style is frowned on y some euse it omplites things for those reding the odeF xormlly when you see for loopD you know tht it will run through the entire olletion nd the ode will exit when it gets to the end of the olletionF he return sttement fores uses the for loop to exit erlier nd s suhD fores the reder to look more losely to (gure out wht is going on hereF gode tht ehves in slightly unexpeted wys like this is ommon soure of errorsD espeilly if the ode gets modi(ed lter onF ou ould get round hving the return sttement y using while loopF his would remove the requirement of return sttementD ut it doesn9t relly mke the ode more funtionl or esier to redF sf nythingD it might mke it it hrder to red nd del withF en lterntive to this is to use the forll method of olletionsF he only hnge in this is piking wy to ompre sequentil elements using forll s tht method only works on one rgument t timeF yne wy to get round this is to use forll on nge tht is the indexF his is logilly very similr to the originl for loop exept tht your prt of the ode is ompletely funtionlF

def isSorted(a:Array[Double]):Boolean = { (0 until a.length-1).forall(i => a(i) <= a(i+1)) }


e seond pprohD whih is lso funtionlD is to use forll on zipped tuple s is shown hereF

def isSorted(a:Array[Double]):Boolean = { (a,a.view.tail).zipped.forall(_ <= _) }


his ode is it shorterD ut signi(ntly more dvnedF sn ftD it uses dvned topis from setions VFT nd IHFSF he pproh here is to mke tuple tht ontins the originl elements (rst nd everything ut the (rst element seondF sf we zipped these to olletions with the zip methodD the result would e sequene of tuples with eh element nd the one fter it in tuple nd the (rst nd lst element pper only one in the (rst nd lst tuplesF ht zipped olletion ould then e delt with using forehF uh solution would e very ine0ient howeverD s it would tully onstrut lot of new ojets nd do lot of opyingF he dvned topis re used to mke it more e0ientF he (rst dvned topi is the view from setion VFTF e view is represenE ttion of olletion tht doesn9t mke full opy unless fored to do soF sn this odeD tking til of just would produe whole new rry nd opy lot of dt over into itF roweverD the til of the view is just smll ojet tht

CHAPTER 13.

SORTING AND SEARCHING

PWS

will intert with ode the sme wy the til wouldD ut through logi insted of mking rel opyF he seond dvned topi is the use of the tuple zipped method from setion IHFSF his is method of the tuple types tht llows you to more e0iently run ommon funtions tht need to go through two or more olletions t the sme timeF snsted of mking whole new zipped olletion of tuplesD this gives you k n ojet tht hs methods like mpD (lterD nd forll delred so they tke s mny rguments s re in the tupleF o we get version of forll tht needs funtion of two rguments tht we n esily provide using the shorthnd syntxF hihever pproh you hooseD you n test prtiulr sort with ode like the followingF

val nums=Array.fill(args(0).toInt)(math.random) flaggedBubbleSort(nums) assert(isSorted(nums))


his ode retes n rry of rndom houles with length determined y ommndEline rgumentF st then lls sort on tht rry nd then uses the ssert funtion is mke sure it is trueF essert is stndrd funtion in l tht n e lled with one or two rgumentsF he (rst rgument is foolen tht should e trueF sf it isn9t trueD n error results terminting the progrmF e seond rgument n e provided tht is pssed yEnme nd should provide useful messge if the ssert filsF he ssert funtion n e used generlly in your odeF here is lso require funtion tht performs similrlyD ut should e used for rgument vluesF o t the top of funtionD if the funtion will only work on ertin rgument vluesD you n use ll to require to mke it so the ode fils in n informtive mnner when d rguments re pssed inF

13.1.5 Sort Visualization


st n help you understnd sorts if you get to see them in tionF here re mny di'erent we sites tht hve nimtions tht will show you how these nd other sorts workF yne dvntge of hving lredy studied grphis is tht we n write our own ode to visulize wht the sorts re doingF his is prt of why the sorts ove were set up to work with the houle typeF st mkes it esy to generte with the ll to mthFrndom tht ws used ove nd to drw euse the rndom numers re uniformly distriuted etween HFH nd IFHF o set things up for the visuliztionD we will use the nums rry from ove nd put in some other ode efore the sort is lledF e9ll strt with the sisF

val img=new BufferedImage(nums.length,500,BufferedImage.TYPE_INT_ARGB) val panel=new Panel { override def paint(g:Graphics2D) { g.drawImage(img,0,0,null)

CHAPTER 13.

SORTING AND SEARCHING

PWT

} val frame=new MainFrame { title="Sort Animation" contents=panel resizable=false }

} preferredSize=new Dimension(img.getWidth,img.getHeight)

his retes n imge tht hs width of the numer of vlues we hve in the rry with height of SHHF st then mkes pnel tht drws the imge nd hs preferred size equl to the size of the imgeF vstlyD we mke frme nd dd the pnel into itF e lso use )g in the frme tht we hven9t used efore to mke it so the frme n9t e resizedF ith this frmework in pleD we n de(ne method tht will render n rry of houles to the imgeF he funtion should lso hve the ility to drw two mrker lines to help indite wht is hppening in seletion sort where we relly don9t move things very oftenD ut spend lot more time serhing through for the smllest elementF

def renderSort(a:Array[Double],m1:Int = -1,m2:Int = -1) { import java.awt._ val g=img.createGraphics g.setPaint(Color.white) g.fillRect(0,0,a.length,500) g.setPaint(Color.red) for(i <- 0 until a.length) { g.drawLine(i,500,i,500-(a(i)*400).toInt) } g.setPaint(Color.black) g.drawLine(m1,0,m1,50) g.setPaint(Color.green) g.drawLine(m2,0,m2,50) panel.repaint() Thread.sleep(20) }
trting from the topD this funtion tkes the rry nd two sntsF he sntsD lotions for the mrkersD hve defult vlues of EIF his men tht you n ll this funtion nd pss only the rry if you don9t need the mrkers nd they will e drwn out of oundsF he (rst line in the funtion is lol import of the jvFwt pkgeF vol imports re something tht l llows so tht you don9t hve to pollute the nmespe s muh importing everything t the top of the (leF snsted you n import wht you needD when you need itF he middle of the funtion is si drwingF st gets the qrphisPh for the imge nd lers the imge with whiteF hen it drws in red drwing one line

CHAPTER 13.

SORTING AND SEARCHING

PWU

for eh element of the rryF he lines go from the ottom up nd re tller for lrger vluesF efter drwing the rry vlues the mrkers re drwn in two di'erent olors nd the pnel is told to repintF he lst line of this method is something tht we hven9t seen eforeD ut whih is required if we wnt to tully e le to see wht is going onF he hredFsleep@millisXvongA method uses the urrent exeution to puse for the spei(ed numer of milliseondsF he numer PH ws hosen to give SH updtes every seondF his is slow enough you n see wht is going onD ut fst enough tht you n sort deent numer of elements in resonle mount of timeF e9ll tlk muh more out threds in hpter PIF xow ll tht remins is to dd some lls to renderort in the sort lgorithmsF utting them into the inner loop works estF por minort you need to pss i nd min s the mrker vluesF he others don9t need to drw the mrkersF

13.1.6 Order Analysis


e sid previously tht the sorts presented ove ren9t the most e0ient sortsF hese sorts re presented (rst euse they re firly simple nd strightforE wrdF roweverD it is resonle question to sk how fst they relly reF his is hllenging question to nswer euse speed n depend on mny difE ferent things inluding the omputer you re running on nd extly wht you re sortingF o ddress thisD lgorithms re generlly desried in terms of their order in prtiulr opertionF he order is rough funtionl desription of how the numer of opertions sles with the size of the inputF e9ll tlk in more detil out order in setion PRFQF por now we will use the term firly looselyF o the ide of order nlysis is to pik one or more opertions tht re prE tiulrly importnt to the lgorithm nd try to (nd funtion tht models how the numer of those opertions hnges with the size of the inputF sn the se of sortsD there re two opertions tht re prtiulrly signi(ntD omprisons nd ssignmentsF wost of the time we worry out omprisons nd for the ode we hve written hereD tht is ppropriteF o how mny omprisons does the full ule sort do on n rry with n elementsc ellD the (rst pss through the loop does nEI omprisonsF he seond pss does nEPF he third does nEQ nd so onF sn mth terms we n write the numer of omprisons in this wyX
n1

C=
i=1

i=

1 1 n(n 1) = n2 n 2 2 2

F his gives the ext numer of omprisons etween elements tht will e doneF st hppens to e e extly the sme for the seletion sortF e typilly refer to this s O(n2 )F por order nlysis we generlly ignore oe0ients nd everything exept the highest powerF his doesn9t provide perfet piture of performneD ut it works very well in generlD espeilly when you tlk out lrger inputsF

CHAPTER 13.

SORTING AND SEARCHING

PWV

he most importnt thing to note out n O(n2 ) lgorithm is tht if you doule the numer of elementsD there will e four times s mny omprisons doneF es resultD you n generlly expet the sort to tke four times longer on twie s muh stu'F he nture of the sling is wht we often re out the mostF hi'erent omputers might e fster or slowerD ut just knowing this sling nd run time for prolem of ertin size gives you good feel for wht the runtime will e if you hnge the size of the prolem2 F he numer of omprisons in the seletion sort nd the ule sort depends only on the size of the dt set eing sortedF st does not depend on the nture of the dtF his is not the se for the )gged ule sort or the insertion sortF his sorts n do very di'erent numer of omprisons depending on the dt tht is given to themF por exmpleD if you give )gged ule sort n rry tht is lredy sortedD it will only run through it oneD doing nEI omprisonsF e would ll tht O(n)F qrnted tht is estEse senrioF he estEse is rrely of interestF snstedD we typilly worry out vergeEse nd worstEse situtions3 F o wht re the verge nd worstEse ehviors of insertion sortc he outer loop lerly hppens nEI timesF o we n do summtion muh like wht we did oveF roweverD the inner loop hppens vrile numer of timesF sn the worst seD whih would e getting dt in reverse orderD the inner loop will run i times nd we get extly the sme ehvior s with the ule nd seletion sortsF sn the est seD whih is dt in the proper orderD the inner loop does only one hekF his gives liner performneD O(n)D euse
n1

C=
i=1

1=n1

F yn verge we expet something hlf wy etween these extremesD we expet the inner loop to do i/2 omprisonsF his gives
n1

C=
i=1

n(n 1) 1 1 i = = n2 n 2 4 4 4

F hile this is etter thn the ehvior of the other sorts y ftor of twoD it is still O(n2 )F his is euse douling the size of the input still mkes it tke four times longer nd tht is wht we generlly re out the mostF o how good or d is O(n2 )c puntions like this tht grow s polynomil funtion re referred to in very generl wy s eing trtle euse you n use them for firly lrge vlues of n nd still expet the lultion to (nish in resonle timeF e9ll see lter on tht not ll lgorithms hve this ehviorF roweverD O(n2 ) isn9t gret if the vlue of n gets extremely lrgeF e
2 Real 3 The
hardware can break down these scaling arguments at certain critical points. For example, if the input set becomes larger than the cache of the machine, you will typically see a slowdown that does not scale quite as produce best-case behavior.

O(n2 ).

exception to this is if we happen to know that we will very often have inputs that

CHAPTER 13.

SORTING AND SEARCHING

PWW

hve no prolem using these sorts for rrys with IHH or IHHH vluesF roweverD s you ontinue to dd zerosD these methods will prove to e too slowF ih ftor of IH in the size uses the progrm to do IHH times s mny omprisons nd generlly this leds to it tking IHH times longer to ompleteF es suhD these methods eome unusle if n gets ig enoughF portuntelyD there re lterntivesF

13.1.7 Shell Sort (Diminishing Gap Sort)


he (rst lterntive sort we will look t is the hell sortD lso lled the diminE ishing gp sortF his sort ws (rst proposed in IWSW y honld hell nd it ws one of the (rst sort lgorithms developed tht is fster thn O(n2 )D though some minor hnges hd to e mde in order to get tht performne for the worst seF he si ide of this sort is one tht might seem it ounter intuitiveF st performs n insertion sort repetedly on di'erent susets of the full rryF o strt withD the susets re tken to e groups of elements tht re widely spedF he sping etween the elements in eh suset is lled the gpF es the lternte nme impliesD the gp is then deresed in size for eh run through the sortF he ounter intuitive spet of this sort is tht performing insertion sort multiple times should sort the rry fster thn doing doing it outrightF his n work euse sort with smller gp size mintins the ordering t the lrger gp size so work isn9t undoneD nd the insertion sort is very e0ient on prtilly ordered dtF he sorts with lrge gps do very little work ompred to the smller gpsD ut one you get to the smller gps the dt is mostly sorted so you get lose to the estEse performne of the insertion sortF he sort lwys ends with gp size of ID whih is doing norml insertion sortD so you know tht the result is fully sortedF he only trik to the insertion sort is (guring out wht to do out the gpF he initil suggestion ws to strt t hlf the size of the rry nd derese it y ftors of PF his often works wellD ut spings tht re ftors of P prt will keep even nd odd susets seprte until you get down to gp of I nd in ertin ses tht n tully led to O(n2 ) ehviorF por this resonD we use slightly di'erent ftorF

def shellSort(a:Array[Double]) { var gap=a.length/2 while(gap>=1) { for(j <- gap until a.length) { var i=j-gap val tmp=a(j) while(i>=0 && a(i)>tmp) { a(i+gap) = a(i) i -= gap renderSort(a) }

CHAPTER 13.

SORTING AND SEARCHING

QHH

} gap=(gap/2.2).round.toInt

a(i+gap) = tmp renderSort(a)

his ode ws reted y de(ning the vr gp nd writing the while loopD then utting nd psting the insertion sort inside of the while loopF yne thereD ll the ples where i ws inremented or deremented y I were hnged so the I ws gpF he ftor of PFP gives etter spings though you do need to round nd onvert k to n integerF wo lls to renderort were left in this ode so tht you n esily visulize itF yf the sorts we hve disussed so frD this one is proly the most importnt to visulize to get grsp on wht it is doing nd why the proess of reduing the gp is signi(ntF he ext order of the hell sort is hrder to pin downF his is lrgely eE use it vries with the seletion of gp sling nd n rnge from O(n2 ) t the poor end ll the wy to O(n log2 n) t the good endF esonle implementE tions like the one shown here will tend to give O(n3/2 ) performneF his might not seem like tremendous improvementD ut if n gets lrgeD the di'erene n e quite drmtiF

13.2 Searching
hile sorting dt is something tht we do fir it with omputersD serhing for dt is fr more ommon tskF e lot of the things tht you do with omputers on regulr sis involve serhing for informtion either just to retrieve it or to modify informtion relted to wht is foundF his mkes sense s running through dt is something tht omputers do prtiulrly quikly nd e0ientlyF

13.2.1 Sequential Search (Linear Search)


he most si form of serh is the sequentil or liner serhF his involves running through dt one element t time nd heking eh one to see if it mthes wht you re looking forF sf it (nds wht you re looking for it either returns the dt or n index where it n e foundF sf it gets to the end without (nding itD it will return something to indite tht the dt wsn9t thereF he following ode is liner serh through n rry of integersF

def linearSearch(a:Array[Int],value:Int):Int = { var i=0 while(i < a.length && a(i)!=value) { i+=1 } if(i > a.length) -1 else i

CHAPTER 13.

SORTING AND SEARCHING

QHI

}
his serh returns the index of the (rst element in the rry whose vlue is the sme ws wht ws pssed inF st does this with while loop so tht it n stop erly if it is foundF he if sttement is needed euse the ommon idiom when returning n index is to return EI when the vlue isn9t foundF e n get rid of this onditionl t the end if we ount kwrdsF

def linearSearchForLast(a:Array[Int],value:Int):Int = { var i=a.length-1 while(i >= 0 && a(i)!=value) { i-=1 } i }


his modi(ed version of the ode strts t the end nd goes kwrdsF st is it simplerD ut it fundmentlly lters the desription of the funtion s we now (nd the lst ourrene insted of the (rstF here re quite few di'erent methods on the l olletions tht do serhingF por the olletions tht we hve lerned outD these re ll performE ing liner serhesF hey inlude the following s de(ned in eqeX

def (nd@pX @eA ab foolenAX yptione def (ndsndexyf@pX @eA ab foolenAX snt def indexyf@elemX eD fromX sntAX snt def indexyf@elemX eAX snt def indexhere@pX @eA ab foolenD fromX sntAX snt def indexhere@pX @eA ab foolenAX snt def lstsndexyf@elemX eD endX sntAX snt def lstsndexyf@elemX eAX snt def lstsndexhere@pX @eA ab foolenD endX sntAX snt def lstsndexhere@pX @eA ab foolenAX snt
wny of these methods ome in pirs where on of the two tkes n extr snt rgument for n index in the olletion tht it should strt working fromF ynly the (rst method returns n element from the olletionD ll the others return indiesF he one tht does return n element wrps it in n yption so tht if no mth is found it n return xoneF sf no mth is found for the methods tht return n indexD they will return EIF

CHAPTER 13.

SORTING AND SEARCHING

QHP

13.2.2 Binary Search


iven though omputers re very fstD liner serh is fr from idelD minly euse serhing is something tht is done so very frequentlyF sf the dt isn9t ordered in ny wyD liner serh is your only optionF o understnd thisD imgine you re hnded norml phone ook nd sked to (nd the person who hs given phone numerF hue to the ft tht phone ooks re not ordered y phone numersD your only reourse is to go through eh nd every line nd hek the numer there ginst wht you re looking forF sn ny resonly sized ity this is something tht no humn would tully undertkeF sf this were the only wy to look through telephone ook people wouldn9t other to keep themF roweverD people do keep telephone ooks euse they rrely look things up y numerF snstedD people normlly look things up y nme nd the telephone ook is sorted y nmeF his ordering of the elements n led to muh more e0ient serhesF ou might not e le to write good lgorithm for how you relly look things up in telephone ookD ut we n onsider you (rst step nd use tht s diretion for writing n e0ient lgorithmF qiven lrge phone ook nd nme you will open it up nd look t wht is on the pge you open toF ydds re good tht you won9t get extly the right pgeF roweverD ompring wht you re looking for to wht is on the pge gives you signi(nt piee of informtionF sf wht you re looking for omes erlier in the lphet thn wht is on the pge you will only look t other pges efore tht oneF ou silly throw everything fter tht pge out of your serh without even looking t itF imilrlyD if wht you re looking for omes fter the pge you hve opened to you will only onsider pges fter the urrent oneF ou will generlly repet this proess in mnner tht isn9t esy to desrie in n lgorithm just euse your method of piking pges might e impted y things like the inding of the ook nd whether one pge stiks out it further thn notherF he ide of looking t lotion nd only onsidering things efore or fter it sed on sorted order n e used to rete fst serhing lgorithmsF he most generl of whih is the inry serhF sn inry serhD you keep trk of rnge of elements tht you re onsidering y two integer indexesF e will ll them strt nd endF et ny given timeD you know tht the vlue you re looking forD if it is presentD will e n index in the rnge i [start, end)F es reminderD this nottion implies tht the rnge is inlusive for strt nd exlusive for endF o if we re serhing the whole rryD then initilly strt is H nd end is the length of the rryF e onsider the midpoint of the rngeD mid = (start + end)/2D nd hek if the element t tht index is wht we re looking forF sf it isD we return midF ytherwise we hek if wht we re looking for is greter or less thn the element t mid nd ut down our rnge ordinglyF o egin withD we will present n impertive version of this lgorithm tht uses while loop nd severl vr delrtionsFF

def binarySearch(a:Array[Int],value:Int):Int = {

CHAPTER 13.

SORTING AND SEARCHING

QHQ

var start=0 var end=a.length var mid=(end+start)/2 while(end>start && a(mid)!=value) { if(value < a(mid)) { end=mid } else { start=mid+1 } mid=(end+start)/2 } if(end<=start) -1 else mid

he while loop ontinues s long s the rnge inludes t lest one element nd the midpoint isn9t the vlue we wntF snside the loop hek is performed to see if the midpoint is less thn or greter thn wht we re looking forF sf it is lessD we set end = midF his works euse end is exlusive nd we hve just veri(ed tht the element isn9t t midF ytherwise we set start = mid + 1F he strt is inlusive so we hve to move it one element eyond the midF hen the loop is ompleted we return either the vlue of mid or EI sed on whether the element ws found or notF his version of the ode is firly strightforwrdD ut there is simpler pprohF finry serh hppens to e n lgorithm tht lends itself very niely to implementtion s reursive lgorithmF he following ode shows wht this might look likeF

def binarySearchRecur(a:Array[Int],value:Int,start:Int,end:Int):Int = { if(end <= start) -1 else { val mid=(start+end)/2 if(a(mid) == value) mid else if(a(mid) < value) binarySearchRecur(a,value,start,mid) else binarySearchRecur(a,value,mid+1,end) } }
glerly this ode is shorter thn wht we hd eforeF wost people would lso (nd this ode it esier to red thn the impertive versionF he only drwE k is tht the funtion hs two extr rgumentsF he norml wy to get round tht is to provide wrpper funtion tht only hs two rguments nd hve it ll this versionF en pproprite wrpper ould e written this wyF

def binarySearch(a:Array[Int],value:Int):Int = binarySearchRecur(a,value,0,a.length)


he logi of the reursive version is identil to the itertive versionF ynly the pproh hs hngedF

CHAPTER 13.

SORTING AND SEARCHING

QHR

n IDHHH IDHHHDHHH IDHHHDHHHDHHH IDHHHDHHHDHHHDHHH

log2 n IH PH QH RH

le IQFIX le of pproximte vlues of log2 n s funtion of nF e use the pproximtion tht 210 103 F he relity is tht 210 = 1024D ut this pproximtion is rther lose nd is good one to keep in your hed for quik pproximtions in mny prts of omputer sieneF xow tht we hve ode to do inry serhD it is interesting to sk wht order this funtion isF egin we sy tht the rry hs n elements in itF he worst se is the sitution when the element isn9t found nd we get down to one element in the rnge tht isn9t wht we re looking forF o we need to (gure out how mny omprisons hppen to nrrow the rnge down from n to IF efter one omprison the rnge is ut to n/2F efter two omprisions it is n/4F sn generlD fter t omprisonsD there re roughly n/2t elements left in the rnge4 F e now hve enough informtion to (nd the mximum numer of omprisonsF

n/2t = 1 n = 2t t = log2 n
his is typilly lled O(log n) s the di'erene etween logs of di'erent ses is simply onstnt multiplierF his is generlly onsidered to e quite fstF o get feel for whyD let9s look t few exmples of how log2 n sles with nF e list of pproximte vlues for this re given in tle IQFIF o relly put this in perspetiveD onsider the ft tht the (rst numer is the worst se for sequentil serh nd the seond numer is the worst se for inry serhF hen n is smllD the di'erene isn9t ll tht signi(ntF roweverD s n gets lrge the ost svings of doing inry serh eome quite pprentF he lst two vlues of n re lrge enough tht they pose prolem even for omputersD despite their speedF yf ourseD you n only use inry serh on sorted dt nd ttempting n O(n2 ) sort on even million items n e time onsumingF o the rel power of this O(log n) sling is purely demi until we disuss some etter wys to sortF

13.2.3 Linear Binary Search (Advanced)


he inry serh is idel for generl sorted dtF roweverD if you hppen to know tht your dt is firly evenly distriuted you n do even etterF 333 rite thisF
4 This
is only exact if n is a power of two. Otherwise some rounding will occur, but that is a detail we can ignore when talking about the order.

CHAPTER 13.

SORTING AND SEARCHING

QHS

13.2.4 Searching for Doubles (Advanced)


greful reders might hve notied tht etween the setion on sorts nd the setion on serhesD smll hnge ws mdeF he sorting setion used n erryhoule while the serhing setion used errysntF he hoie of the houle type for sorting ws motivted y the ft tht they re esy to generte nd visulizeF roweverD the re not idel for serhingF his is due to the nture of the houle typeF sn our disussions we hve only presented the houle type s the type we use for numers when frtionl prt is requiredF e hve glossed over the detils of wht is hppening with the houle typeF o understnd the reson tht houles re not good for serh lgorithms requires us to dig it deeper into wht they reF he term houle stnds for doule preision )oting point numerF he plot typeD whih we hve generlly ignoredD is single preision )oting point numerF he plot type n lso represent frtionl numersD ut it hs smller rnge nd lower preisionF es with ll numers on omputerD )oting point numersD e they single or doule preisionD re relly stored in inryF he est wy to think out )oting point numer is to think of numers in normlized sienti( nottionF sn deimlD you n think of numer in sienti( nottion s eing in the following formD

(1)s m 10e
D where s {0, 1}D 1 m < 10 or m = 0F e n s the signD m the mntissD nd e the exponentF xot muh hnges when the numer goes to inry exept tht sD mD nd e re stored in its insted of deiml digits nd we wnt powers of P insted of IHF o sienti( nottion in inry would e

(1)s m 2e
his still doesn9t explin why it is hrd to do serhing with )oting point numerF he key to tht omes from the ft tht we only hve (nite numer of its to use to store mF o understnd the implition of thisD onsider sitution where you only hve U deiml digits to write mF xow try to write the deiml form of the frtion IGQF ou would write (1)0 3.333333 101 F his isn9t extly the sme s IGQD ut it is lose s you n get with only U digitsF he relity is tht to write IGQ in deiml you need n in(nite numer of digitsF vots of frtions require n in(nite repeting representtion in deimlF his sme thing hppens in inry on the omputerF xot hving in(nite inry digits n led to some interesting results for ftionl numers tht n9t e perfetly representedF o understnd thisD onsider the following simple exmple from the l ivF F

scala> 0.1==1.0-0.9 res0: Boolean = false


wthemtilly you expet the expression HFIaaIFHEHFW to e trueD ut the deiml vlue HFI is n in(nite repeting sequene in inryF es suhD it is

CHAPTER 13.

SORTING AND SEARCHING

QHT

trunted t some point nd we get n pproximtionF imilrlyD HFW n e represented perfetly eitherF he result is tht sutrting HFW from I gives vlue tht isn9t extly the sme s the pproximtion to HFIF o see how di'erent the two re we n sutrt one from the otherF

scala> 0.1-(1.0-0.9) res1: Double = 2.7755575615628914E-17


his is n extremely smll numerD ut it isn9t zero nd euse it isn9t zeroD the two ren9t equlF his is well known hllenge with )oting point numers nd people who do numeri work hve lerned not to do heks for equlity on them s the results re generlly unpreditle euse of the rounding tht is prt of even the simplest rithmetiF por our disussionD wht we hve seen is evidene tht using aa in serh lgorithm on the houle type is likely to produe unexpeted resultsF o the next question isD how do we get round thtF he si ide ehind the solution is tht we generlly onsider )oting point numers to e equivlent s long s they re lose enough to one notherF o how lose is lose enoughc ht depends on whether you re working with single or doule preision numersF sn mth the qreek symol epsilon is typilly used to represent vnishingly smll vlueF sn omputer numeris the term epsilon is used to desrie the smllest vlue tht you n dd to one nd still get numer greter thn oneF sf you go smller thn epsilonD the vlue will e rounded o' in the sum nd ll you will get k is oneF rere is ode tht delres nd lultes this for oth the houle nd plot typesF

scala> val doubleEpsilon = { | var eps=1.0 | while(1.0+eps > 1.0) eps*=0.5 | eps*2.0 | } doubleEpsilon: Double = 2.220446049250313E-16 scala> val floatEpsilon = { | var eps=1.0f | while(1.0f+eps > 1.0f) eps*=0.5f | eps*2.0 | } floatEpsilon: Double = 1.1920928955078125E-7
eny single opertion n e expeted to hve errors on the order of epsilonF hen you string mny opertions together the error growsF es suhD it is stndrd prtie to onsider to vlues equl if the reltive error is less thn the squre root of epsilonF his mens you only trust hlf the its of preision in the numerF es suhD the following vlues re wht you relly (nd importntF

scala> val sqrtDoubleEpsilon=math.sqrt(doubleEpsilon) sqrtDoubleEpsilon: Double = 1.4901161193847656E-8

CHAPTER 13.

SORTING AND SEARCHING

QHU

scala> val sqrtFloatEpsilon=math.sqrt(floatEpsilon) sqrtFloatEpsilon: Double = 3.4526698300124393E-4


por simple order of mgnitude purposesD you might rememer tht for houle this is out 108 nd for plot it is 104 F e will use this pproximte vlue in the ode tht followsF o how ould we modify our serhes to work with the houle typec e simE ply need to reple the hek for equlity with hek of the reltive di'erene etween the twoF por the liner serh tht would look like the followingF

def linearSearch(a:Array[Double],value:Double):Int = { var i=0 while(i < a.length && (a(i)-value).abs > 1e-8*value.abs) { i+=1 } if(i > a.length) -1 else i }
he seond hlf of the ondition in the while loop is performing the ritil hekF st tkes the solute vlue of the di'erene etween the vlue in the rry nd the vlue we re looking forF st ompres to see if tht is igger thn our pproximte vlue for the squre root of epsilon times the vlue we re looking forF ou n9t simply ompre to IeEV euse if oth vlue nd @iA hve mgnitude muh smller thn unityD suh omprison ould e erroneousF por exmpleD imgine if the vlues were positions of toms in n ojet mesured in metersF e seprtion of 108 meters prt would likely e quite signi(ntF

13.3 Alternate Sorts (Advanced)


333 ve for lter

13.3.1 Bucket Sort 13.3.2 Radix Sort

13.4 Performance and Timing


his hpter hs introdued numer of di'erent sorting nd serhing lgoE rithmsF e hve disussed the performne of these lgorithms in terms of orderF his tells us how they sle s the numer of inputs is hnged nd quite often this is ll you relly re outF ou might not know or re out detils of the hrdwre or the dt sets you will e running onD or you know tht suh detils will hnge over timeF here re times though when you relly do re extly how fst n lgorithm is on prtiulr mhine nd you need

CHAPTER 13.

SORTING AND SEARCHING

QHV

to ompre it to other similr lgorithms on tht sme mhineF hen you do thisD you need to do timing tests on the lgorithmF here re numer of di'erent wys to get timing informtion on progrmF vinux hs ommnd lled time tht will let you know how muh time progrm onsumes when it is runningF por some pplitions this is idelF roweverD for our purposes we only wnt to mesure how long prtiulr prt of the progrm tkesF e don9t wnt to mesure the time tken to strt things up or to initilize the rryF e only wnt to mesure the time spent sorting the rryF ou n get very detiled informtion like this from pro(ler5 D ut tht is overkill for wht we wnt to doF por our purposes we just need the ility to determine the strt time nd stop time nd tke the di'erene etween the twoF e n do this y lling ystemFnnoime@AF his is ll to the tv lirries tht returns vong mesuring the urrent time in nnoseondsF enother thing tht we wnt to do to mke the tests even is sort the sme numers for eh sortF o mke this hppenD we relly need to sort opy of the rry nd keep the originl so tht we n mke other opies of itF e need to do this for eh of the sorts so it is nie to put the ode into funtion tht we n esily ll with di'erent sortsF o mke it work with di'erent sortsD we need to pss in the sort funtion s n rgumentF he following funtion does this for usF

def timeFunc(sortFunc:(Array[Double])=>Unit,a:Array[Double]) { val copy=Array.tabulate(a.length)(i => a(i)) val start=System.nanoTime() sortFunc(copy) val end=System.nanoTime() println("Time:"+(end-start)/1e9) assert(isSorted(copy)) }
he print sttement divides the time di'erene y IeWF his gives us k vlue in seonds insted of nnoseonds whih is muh esier for us to red nd del withF e n invoke this y putting the following ode t the end of our sriptF

args(1) match { case "bubble" => timeFunc(bubbleSort,nums) case "flagged" => timeFunc(flaggedBubbleSort,nums) case "min" => timeFunc(minSort,nums) case "insert" => timeFunc(insertionSort,nums) case "shell" => timeFunc(shellSort,nums) }
5 You
can invoke the Java proler with the Java -Xprof option. To get Scala to run this option you set the JAVA_OPTS environment variable to include -Xprof.

CHAPTER 13.

SORTING AND SEARCHING

QHW

fefore you use this you will need to mke sure you tke out the lls tht do the rendering s the renders intentionlly slow things down so you n see wht they re doingF sf you ply round with this some you will notie few thingsF pirstD you hve to get up to t lest IHHHH numers in the rry efore the timing mens muhF sf the rry is too smllD the sort will e so fst tht the resolution of the mhines lok will eome prolemF eondD the mount of time spent doing the sort n vry on di'erent invotionsF por this resonD ny true ttempt to mesure performne will run the ode multiple times nd tke n verge of the di'erent vluesF

13.5 Classifying Bugs


fy this point you hve ertinly lerned tht simply writing your ode does not men tht it is orret nd tht it will workF irrors in progrms re ommonly referred to s ugsF he term ug is historil in origin euse the (rst one ws mothF he erliest omputers were hugeF hey took up rooms the size of gymnsiumsF en erly mlfuntion in one turned out to e moth tht hd )own in nd ws using shortF hile the term ug hs stuk roundD the implitions of this term no longer (tF he term nd its history imply tht it is something eyond the ontrol of the progrmmer tht just put itself into the ode nd now the progrmmer hs to serh for itF sn relityD virtully ll modern ugs re relly mistkes on the prt of the progrmmerF hey re things tht the progrmmer put into the ode nd now the progrmmer needs to orretF xot ll ugs re the smeF here re three fundmentlly di'erent types of errorsF IF yntx error E irror in the struture of the ode tht is found y the ompilerF PF untime error E irror tht uses the progrm to rsh while runningF QF vogi error E irror tht doesn9t rsh the odeD ut uses it to produe the wrong nswerF ih of these deserves fir it of disussionF e will lso tlk out how they ompre to one nother nd the wy in whih they impt progrmmersF hen you re (rst lerning to progrmD the errors tht you likely run into the most re syntx errorsF hese n e s simple s typos or misspellingsF hey n lso e more omplex like type mismth errors or lling funtions or methods with the wrong numer of prmetersF he ommon element tht mkes something syntx error is tht it is disovered y the ompiler when it is trying to trnslte the humn written ode into formt tht is more omputer friendlyF hi'erent progrmming lnguges do di'erent mounts of heking for errors t ompile timeF his is often lled stti heking euse it n e done without tully running the progrmF

CHAPTER 13.

SORTING AND SEARCHING

QIH

l does signi(nt mount of stti heking for errorsF he wy we hve een running our progrms in the iv or with sripts the ompile stge isn9t lerly seprted from the running of the progrmF he l system is running ompiler in the kground nd then exeuting the results of the ompileF he syntx errors disply messge like the followingX

timing.scala:5: error: not found: value This This line will not compile ^ one error found
hey tell you the nme of the (le long with line numerF hen they desrie the error nd show the line nd where on the line the error ourredF he seond type of ug is runtime errorF his type of error ours when everything is synttilly orret nd the progrm ompiles nd runsF roweverD during the run this error uses the progrm to rshF sn l runtime error will produe messge tht looks similr to the followingX

java.lang.ArrayIndexOutOfBoundsException: -1 at Main$$anon$1.<init>(timing.scala:5) at Main$.main(timing.scala:1) at Main.main(timing.scala) ...


his messge tells you wht went wrong nd then prints stk tre tht inludes line numersF sn this simple exmpleD the ode filed on line SF here re mny di'erent resons why runtime errors hppen nd it might e dependent on user inputF o runtime error might not e found from running the progrm one or twieF o redue the numer of runtime errors in progrm you hve to run it with multiple di'erent input test inputs s ws disussed in setion VFSF sn generl senseD it is impossile to prove tht ode hs no runtime errorsF he lst type of error is logi errorF en error is logi error if the ode ompiles nd runs to norml termintionD ut provides n inorret output or ehves inorretly in some other mnnerF hese errors n ome in ll types of forms nd there is no messge tht tells you there is prolemF ou know know there is prolem y heking the output or ehvior of the progrm to see if it mthes expettionsF vike runtime errorsD logi errors might not our for ll inputsF here might e only spei( inputs tht trigger the errorF sf you hve hoieD you wnt errors of types higher on the listF es novie progrmmer you proly get tired of deling with syntx errors nd (nd them frustrtingF roweverD the relity is tht syntx errors re y fr the est type of errorF his is euse syntx errors give you the most informtion on how to (x them nd re deteted y the ompiler in wy tht doesn9t depend on inputsF our seond hoie would e runtime error for similr resonsD it provides you with some informtion relted to wht is wrong ndD s resultD helps you (x

CHAPTER 13.

SORTING AND SEARCHING

QII

the prolemF fy ontrstD logi errors provide no informtion on how to (x themF hi'erent lnguges do more or less to help you with error detetionF yne of the signi(nt dvntges of l is tht it is designed to mximize the numer of errors tht re syntx errors nd redue the numer of runtime nd logi errorsF rt of this is the type heking system of lF he lnguge does signi(nt stti type heking to mke sure tht ll the vlues you re using re of type tht is pproprite for the usgeF wny of the higher order funtions nd methods in l lso help to prevent ommon errors tht progrmmers fe in other lngugesF his is lso true of rules suh s the requirement to initilize vriles t delrtion nd the generl preferene of vl delrtions over vr delrtionsF o understnd thisD simply onsider the following line of odeF

val dbl=nums.filter(_>0.5).map(_*2)
his line of ode will give us new olletion of numers tht re twie the mgnitude of the elements ut only for the elements tht were originlly igger thn HFSF here ren9t too mny wys to mess up this line without hving it e syntx errorF st is possile to get logi error if you mistype the greter thn or the multiplitionD ut tht is something no progrmming lnguge n relly (xF he progrmmer hs to orretly ommunite the key logiD ut this line doesn9t hve ll tht muh other thn tht key logiF o understnd the rel vlue of this line of odeD you hve to onsider the lterntiveD whih is wht you would hve to write in most other progrmming lngugesF e9ll write equivlent ode tht is spei( for n rryF he l ode works eqully well for ny sequeneD ut we9ll ignore tht dvntge for nowF st will eome more signi(nt lter onF

var cnt=0 for(i <- 0 until nums.length) { if(nums(i)>0.5) cnt += 1 } val dbl=new Array[Double](cnt) cnt=0 for(i <- 0 until nums.length) { if(nums(i)>0.5) { dbl(cnt)=nums(i)*2 cnt += 1 } }
he (rst loop ounts how mny elements re greter thn HFSF his is required euse rrys hve to e given size when they re retedF yne we know how mny there will eD we n mke the rryF he seond loop (lls in the rry with doule the vlues in the originl oneF

CHAPTER 13.

SORTING AND SEARCHING

QIP

glerly this seond version is longerF wore importntlyD tht re lot more ples where typos eome runtime or logi errorsF he relity is tht the one line version is doing silly this sme thingF roweverD most of the ode is in the lirries nd isn9t rewritten y eh progrmmer every timeF his worksD in lrge prtD euse of the (rstElss funtions nd the ese with whih funtion literls n e written in lF

13.6 Memory Layout


he memory of the omputer is silly like huge rry of ytesF st is shred etween the operting system nd mny di'erent progrmsF hi'erent prts of memory n e lloted for di'erent things or ssoited with di'erent deviesF l hides most of the intriies of memory from youF st is not lnguge designed for doing lowElevel system progrmmingF et some point in your omputer siene trining you should lern out the detils of omputer memoryF por our purposes hereD we will only re out the orgniztion of memory inside of the llotion of single progrmF he memory for progrm is roken into two rod pieesD the stk nd the hepF hese terms were hosen intentionlly nd the imges they invoke in your mind re proly firly urteF e stk is orderly with one item pled on top of the previous oneF e hep is muh less orgnized with items pled lmost t rndomF vol vriles nd funtion rguments re lloted on the stkF es ws disussed in setion UFVD the memory model in l is suh tht the vriles re referenes nd they refer to ojetsF sn this memory modelD the ojets re lloted on the hepF ivery time new funtion is lledD the memory for the rguments nd the lol vrilesD long with some memory for ookkeepingD is lloted in lok tht is often referred to s the stk frmeF sf tht funtion lls notherD then nother frme is lloted on top of itF hen funtion returnsD the stk frme for tht funtion is freed upF ht sme memory will e used lter for nother funtionF his should help explin the output from runtime errorF he stk imE pliitly keeps trk of where you re in eh funtion when it lls the nextF ou n piture eh of those funtions stked on top of the one tht lled itF ht is wht gets printed in the stk treF ih line tells you wht funtion hs een lled followed y the (le nme nd line numerF he ojets on the hep re lloted in free spesF he memory for ojets is freed up utomtilly when the ojet is no longer in useF his proess of utomtilly freeing hep memory is omplished y proess lled grge olletionF en ojet n e olleted if it n no longer e rehed y following referenes tht strt on the stkF xot ll lnguges inlude grge olletorsF sn those tht don9tD the progrmmer is responsile for freeing memory tht ws lloted on the stkF

CHAPTER 13.

SORTING AND SEARCHING

QIQ

13.7 Sorting/Searching with Case Classes


sn the sorts nd serhes tht we hve looked tD we were working with numeri typesF wore generllyD the ode tht ws written will work with ny type tht works with the omprison opertorsF es suhD our ode would hve worked with erryghr or errytring if you simply ltered the type tht ws pssed into the sortF yur se lsses don9t meet this requirementF es suhD we need to mke other ltertions to the ode eyond the type if we wnt to sort se lssF portuntelyD these ltertions ren9t ll tht signi(ntF e will work with the following se lssF

case class Weather(id:String,year:Int,month:Int,precip:Double,tmax:Double, tmean:Double,tmin:Double)


his se lss ws reted to store historil wether dtF st ws used to represent reords for monthly dt on temperture nd preipittionF ou would lod n entire (le of these reords into n rryF sf you wnt to see the hottest ten months you ould sort the rry y the high temperturesF gode for suh sort is shown hereF

def bubbleSortWeatherHighTemps(a:Array[Weather]) { for(j <- 0 until a.length-1) { for(i <- 0 until a.length-1-j) { if(a(i).tmax > a(i+1).tmax) { val tmp=a(i) a(i)=a(i+1) a(i+1)=tmp } } } }
e ule sort ws piked euse of the simpliity of the sortF st is very esy to see wht ws hngedF he only hnges re the type in the prmeter for the rry tht is pssed in nd the ft tht the omprison is done etween (elds of the rry elementsF efter pplying this sort to the rry you n use tke or tkeight to pull o' the elements t one end or the otherF gse lsses lso present nother lterntive tht we didn9t relly get with single vluesD the ility to hve the omprison sed on more thn one (eldF por the wether dtD it is likely to e stored in the dt (le in hronologil orderF roper hronologil order is omintion of oth the yer nd month (eldsF sf you wnted to hve the ility to serh for entries y time you might wnt to hve inry serh tht n look for prtiulr yer nd monthF gode for doing tht is listed hereF

def binarySearchWeather(a:Array[Weather],year:Int,month:Int):Int = {

CHAPTER 13.

SORTING AND SEARCHING

QIR

var start=0 var end=a.length var mid=(end+start)/2 while(end>start && (a(mid).year!=year || a(mid).month!=month)) { if(year < a(mid).year || (year==a(mid).year && month < a(mid).month)) { end=mid } else { start=mid+1 } mid=(end+start)/2 } if(end <= start) -1 else mid

xote tht the omprison hs eome signi(ntly more omplexF st hs to ompre the yer (rst nd then if there is tieD rek tht tie with the monthF nfortuntelyD when written in this wyD we hve to write ompletely seprte sort or serh for eh ordering we might wnt on the se lssF por exmpleD if you wnted wettest months insted of hottest monthsD you would need seprte sortF ou might feel tht opying whole sort or serh funtion only to mke suh smll hnges isn9t very e0ient nd tht there should e wy to mke sort or serh tht works more generllyF e n help improve these funtions for se lsses hereF vterD in hpter PHD we will gin the ility to strt these ides so tht the funtion works with multiple typesD not just di'erent sort orders on single typeF fk in setion TFR we sw how we ould mke some reursive funtions more powerful y pssing funtions into themF his pproh is extly wht is tken y the higher order funtions in the l olletions lirriesF es suhD we hven9t hd to go to it ourselves muh sine thenF roweverD the desire to not write ompletely new sort or serh funtion for eh nd every possile ordering on se lss provides motivtion to pull out these ides ginF sf you were to write new version of ule sort tht sorts the ether ojets y preipittionD you would (nd tht the only thing you hnge is the ode relted to the omprison of the elementsF sn order to get sort tht n sort y high tempertureD preipittionD or nything else relted to the ether typeD ll we hve to do is mke it so tht we n vry the omprison from the outsideF his n e omplished y pssing in funtion tht does the omprisonF por our sortsD we hve een using less thn nd greter thn for omprison so we just need to pss in funtion tht represents one of theseF e pik less thn here though the ode ould esily e rewritten with greter thnF he ode for the sort fter this hnge looks like the followingF

def bubbleSortWeather(a:Array[Weather],lessThan:(Weather,Weather)=>Boolean) { for(j <- 0 until a.length-1) { for(i <- 0 until a.length-1-j) {

CHAPTER 13.

SORTING AND SEARCHING

QIS

if(lessThan(a(i+1),a(i))) { val tmp=a(i) a(i)=a(i+1) a(i+1)=tmp }

he omprison opertor is represented s funtion tht tkes two ether ojets nd returns foolenF e ll to this funtion is used in the if sttementF sing this modi(ed versionD we ould sort y the high tempertures with ll like thisF

bubbleSortWeather(weather,(w1,w2)=>{w1.tmax < w2.tmax})


elterntelyD the sme method ould e used to sort y preipittion with ll like thisF

bubbleSortWeather(weather,(w1,w2)=>{w1.precip < w2.precip})


ht is moreD using this version of the sortD it is esy to hnge it so tht it sorts from gretest to lest insted of the stndrd lest to gretestF sn the se of preipittion this is done y hnging the ll in the following wyF

bubbleSortWeather(weather,(w1,w2)=>{w1.precip > w2.precip})


ell tht is hnged in the diretion of the omprison opertorF es you n seeD this strted version tht uses funtion insted of hrd oded omprison opertor is fr more )exileF rving seen the ene(ts we n get from using this in our sortD it would e nie to enle serhing in the sme wyF sf you strt to write the serh ode with the sme omprison opertor you will (nd tht there is signi(nt prolemD the serh requires more thn just less thn or greter thnF he serh requires tht we e le to tell if two things re equlF he stndrd wy to del with this is to hve funtion tht returns n snt insted of foolenF he snt is negtiveD zeroD or positive to represent less thnD equl toD or greter thn respetivelyF he other hnge tht mkes serh it di'erent is tht the funtion only tkes one ether ojet euse we just wnt to know where the thing we re looking for is reltive to this vlueF rnslting ll of this into ode gives the followingF

def binarySearchWeather(a:Array[Weather],comp:(Weather)=>Int):Int = { var start=0

CHAPTER 13.

SORTING AND SEARCHING

QIT

var end=a.length var mid=(end+start)/2 var c=0 while(end>start && {c=comp(a(mid)); c!=0}) { if(c<0) { end=mid } else { start=mid+1 } mid=(end+start)/2 } if(end <= start) -1 else mid

he funtion is lled omp nd it tkes ether nd returns n sntF sn order to prevent hving the ode ll omp more times thn it needs toD we introdue vrile nmed tht stores the result of the most reent omprisonF e ssign this in ode lok in the onditionF he loop heks to mke sure it isn9t zeroF he if heks if it is negtiveF efter we lulte new mid we lso mke new omprisonF xow the question isD how ould we use this serh to (nd di'erent elements in the rryF he (rst exmple we9ll give is one tht duplites the serh we hd ove serhing for spei( yer nd monthF

binarySearchWeather(data,w => { if(w.year>1896) -1 else if(w.year<1896) 1 else if(w.month>2) -1 else if(w.month<2) 1 else 0 })
sn this seD we re serhing for perury of IVWTF his version uses sequene of if expressions to determine if the element w omes efore or fter tht timeF ith little mth we n mke shorter version tking dvntge of the ft tht there re IP months in eh yerF

binarySearchWeather(data,w => (1896*12+2)-(w.year*12+w.month))


erh for dt sed on dte is mde more omplex euse it depends on two vluesF sf we use our )exile sort to reorder the rry y preipittion we ould use the following to serh for month in whih there were IFRQ inhes of rinF

binarySearchWeather(data,w => { val diff = 1.43-w.precip if(diff > 1e-8) 1

CHAPTER 13.

SORTING AND SEARCHING

QIU

})

else if(diff < -1e-8) -1 else 0

he logi in this n e hllenging to writeF hnkfullyD the ehvior of reE turning negtiveD zeroD or positive is ommon stndrd nd the l lirry ontins ode tht does this with the uilt in numeri typesF es suhD the ode n e expressed more simply in this wyF

binarySearchWeather(data, 1.43 compare _.precip)


he ompre ll is tully method we n ll on houleF he ft tht period hs other mening for numers led to us using opertor nottion for the method insted of the more stndrd nottion with dot nd prenthesesF

13.8 Putting it Together


333 orted qroery vist with reipe seletion

Self-Directed Study
inter the following sttements into the iv nd see wht they doF ome will produe errorsF ou should try to (gure out whyF ry some vritions to mke sure you understnd wht is going onF

scala> def succ(n:Int):Int = n+1 scala> succ(1)


333

Exercises
IF ixerise PF minwxort QF iming using ystemFnnoime X vong RF estrt insertion sort nd min sortF

Projects
IF his projet is intended for people who hve een working on grphis nd ry tringD ut it doesn9t immeditely link so you n do it even if you hven9t een doing the previous onesF por this prolem you will drw polygons to qrphisPh using pinters lgorithmF ht is where you drw things from the k to the front so tht the things in front pper on top of the things ehind themF hoing this properly is hllenging

CHAPTER 13.

SORTING AND SEARCHING

QIV

prolemF ou should se your drwing on the point in the polygon tht is losest to the viewerF o keep things simpleD the viewer will e t the origin fing out the zExisF ht wy the x nd y oordintes re roughly wht you expetF o mke it so tht things tht re further wy re smller you divide the tul x nd y y the z vlue to get the lotion you would drw them tF qiven point @xDyDzA you would wnt it drwn on n imge or pnel t @@xGzCIABsizeFwidthGPD@IEyGzABsizeFwidthGPAF o represent polygon for drwing to the qrphisPh you should use jvFwtFgeomFthPhFhouleF ou n moveo the (rst pointD then use lineo to mke linesF hen you get to the lst point you ll loseth to lose it o'F tore your polygons in (leF you n deide the ext formtF sn dE dition to hving the points in eh polygonD eh one should hve olor tht it will e drwn inF ememer to sort them y z vlue so tht the one with the smllest z vlue is drwn lstF PF he fesg progrmming lnguge ws reted to e simple lnugge for novie progrmmersF he originl versions were orgnized y line numE erF ih sttement of the progrm ws single line tht hs numer ssoited with itF he lines were ordered ording to tht numer nd )ow ontrol ws implemented y llowing the progrm to jump to other line numersF por this projet you will rete simple qs tht lets you edit simpli(ed version of fesgF por this simpli(ed version you hve very limited set of possile omE mndsF he qs will lso use line editor styleF he llowed ommnds inluding the followingX qyyD spErixD sxD viD nd sxF ih of these must e preeded y line numer tht is n integerF por our purposesD vrile nmes re single hrters nd they will ll e numersF ou n use houleF he qyy ommnd should e followed y n integer numer tht is the line numer the progrm should exeute nextF @ixmpleX IHH qyy SHA he spErix ommnd hs the following syntxX sp comp rix #F he comp is omprison tht n hve vrile or numer on either side nd either a or ` etween themF he # is line numer tht the exeution will jump to if the omprison in the ondition is trueF sf the omprison is flseD the exeution ontinues on the next lineF @ixmpleX IIH sp `PI qyy SHA he sx ommnd should e followed y single vrile nme nd when it is exeuted the progrm puses nd wits for the user to input

CHAPTER 13.

SORTING AND SEARCHING

QIW

vlue tht is stored in tht vrileF @ixmpleX IPH sx A he vi ommnd hs the keyword vi followed y vrile nme with n equl sign nd then either single numerGvrile or two numE erGvrile opernds tht seprted y n opertorF he opertor n e CD ED BD or GF he result of the opertion should e stored in the vrile efore the equl signF @ixmpleX IQH vi aCQA he sx ommnd n e followed either y vrile nme or string in doule quotesF hen exeutedD this will print either the vlue of the vrile or the string to the outputF riles do not hve to e delredF hey ome into existene when (rst used nd they should hve vlue of H to strt with if no other vlues ws given to themF he qs for this progrm should hve three min elementsF he proE grm itself is displyed in vistiewF his mkes it simple for users the selet line to edit without letting them type rndom textF here should lso e extpield where the user n enterGedit linesF sf line is seleted in the vistiew the text from it should pper in the extpieldF he user n edit tht line or enter nything elseF he numer t the eginning of the line will e user to put it in pleF sf numer is used tht dupliE tes n existing lineD the new one reples the old oneF vstly there is extere tht shows the output when the progrm is runF hen the user hits enter on the text (eld your progrm should hek if wht ws entered is vlid ommndF sf it isD it should put it in the progrm nd lerF sf it isn9tD it should leve the text there nd not lter the existing progrmF here should e t lest four menu items for this progrmX veD ypenD emoveD nd unF he ve option sves the progrm to text (leF he ypen option llows the user to selet (le nd open it up s progrmF he emove option will remove the urrently seleted lines in the proE grmF xothing hppens if nothing is seletedF he un option runs the progrmF sf strts running t the (rst line nd ontinues until exeution goes eyond the lst lineF QF et the v httpXGGwwwFsFtrinityFeduG~mlewisGlfookGghpterIQGRIUWRSIUIHFsv you will (nd (le with historil wether dt for n entonioD F ou should red this dt into n rry of some se lss tht you reteF he dt is seprted y ommsF xote tht the seond line tells you wht eh olumns of dt representsF ou will skip the top two lines when reding the informtionF

CHAPTER 13.

SORTING AND SEARCHING

QPH

rite sript tht will report the months with the (ve wrmest verE ge tempertures nd those with the (ve lowest verge temperturesF sf you wnt to ply round with other lotionD full dt is ville t httpXGGdiFornlFgovGepusGndpGushnGessFhtmlF por it of n extr hllenge mke it so tht the user n tell the proE grm whether to report the top nd ottom (ve months for ny of the vlues in the (leF ou ould do this with lot of typingD ut y pssing in funtion pointer you n ut down on the length of the ode gretlyF RF sf you did gme for one of the projets in hpter IPD for this one you n enhne it y dding high sores listF ht mens hving some wy to sore gmesF st lso mens sving sores to (le in formt of your hoosingF vstlyD the high sores need to e sortedF ih sore reord needs to hve t lest sore nd n identifying nme or initilsF ell other detils re up to the studentF

Chapter 14

XML and Patterns


his hpter dels with two rther di'erent topis tht (t together is ertin wys nd whih will llow us to expnd wht we n do in our progrms in signi(nt wysF he (rst topi is wvD short for etensile wrkup vngugeF hile wv is tehnilly ompletely lnguge independent topiD l ws developed with wv in mind nd mkes it esy to work withF tternsD on the other hndD re very muh prt of spei( lngugesF hey re used extensively in the fmily of lnguges desended from wvF l inorported numer of di'erent fetures from this fmilyD inluding the use of ptternsF he wy they re implemented in l is very )exileF rt of tht )exiility llows you to user ptterns in deling with wvD whih is why these topis hve een grouped togetherF

14.1 XML
sn hpter WD we lerned how to red from nd write to text (lesF he (les tht we used in tht nd following hpters re wht re lled )t text (lesF hey hve the dt in them with nothing tht tells us out the nture of the dt other thn formttingF he dvntges of this re tht it is firly simple to red nd write nd it n e oth red nd write with stndrd tools like text editorF he disdvntges re tht it n e slow nd it lks ny inherent mening so it is hrd to move the informtion from one progrm to notherF wv ddresses the ltter disdvntgeD without losing the dvntgesF he etensile wrkup vnguge is stndrd for formtting text (les to enode ny type of informtionF st is mrkup lngugeD not progrmming lngugeF he stndrd simply de(nes formt for enoding informtion in strutured wyF st is likely tht you hve herd of di'erent mrkup lnguge lled rwvD the ryperext wrkup vngugeF rwv is used to enode we pges nd hs formt very similr to wvF sndeedD newer stndrd lled rwv is silly rwv tht onforms to the wv rulesF

QPI

CHAPTER 14.

XML AND PATTERNS

QPP

14.1.1 Description of XML


iverything in n wv (le n e lssi(ed s either mrkup or ontentF wrkup in wv is found etween 9`9 nd 9b9 or etween 989 nd 9Y9F he ontent is nything tht isn9t mrkupF o help you understnd wv we will look t n exmple wv (leF his exmple is uilt on the ide of lulting grdes for ourseF

<course name="CSCI 1320"> <student fname="Jason" lname="Hughes"> <quiz grade="98"/> <quiz grade="100"/> <quiz grade="90"/> <test grade="94"/> <assignment grade="100"> <!-- Feedback --> Code compiled and runs fine. </assignment> </student> <student fname="Kevin" lname="Peese"> <quiz grade="85"/> <quiz grade="78"/> <test grade="67"/> <assignment grade="20"> Code didn't compile. </assignment> </student> </course>
tust reding this should tell you wht informtion it ontinsF xow we wnt to go through the di'erent types piees of wv to see how this ws uiltF

14.1.1.1 Tags
ext etween 9`9 nd 9b9 hrters re lled tgsF xerly everything in our smple wv (le is inside of tgF he (rst word in the tg is the nme of the tg nd it is the only thing tht is required in the tgF here re three types of tgs tht n pper in n wv (leF

trt tg E fegins with 9`9 nd ends with 9b9D ind tg E fegins with 9`G9 nd ends with 9b9D imptyEelement tg E fegins with 9`9 nd ends with 9Gb9F
gs n lso inlude ttriutesD whih ome fter the nme nd efore the lose of the tgF

CHAPTER 14.

XML AND PATTERNS

QPQ

14.1.1.2 Elements
he tgs re used to de(ne elements whih give struture to the wv doumentF en element is either strt tg nd n end tg with everything in etween or it is n empty element tgF he empty element tg is simply shorter version of strt tg followed y n end tg with nothing in etweenF ilements n e nested inside of one notherF sn our smple (leD there is ourse element tht enloses everything elseF here re two student elements inside of thtF ih of those inludes elements for the di'erent grdesF wost of these re empty elementsD ut the ssignments re not empty nd hve ontents in themF eny time there is strt tgD there should e mthing end tgF hen elements re nestedD they hve to e nested properlyF ht is to sy tht if elementEP egins inside of elementEID then elementEP must lso end efore the end of elementEIF sn ddition to other elementsD you n ple generl text inside of elementsF

14.1.1.3 Attributes
edditionl informtion n e tthed to oth strt tgs nd empty element tgs in the form of ttriutesF en ttriute is nme vlue pir where the vlue is in quotes nd the two re seprted y n equl signF he exmple wv is loded with ttriutesF sn ftD every strt or empty element tg in the exmple hs n ttriuteF st isn9t required tht these tgs hve n ttriuteD ut it is good wy to ssoite simple dt with tgF hese tgs n lso hve multiple ttriutes ssoited with themF

14.1.1.4 Content
fetween strt tg nd n end tg you n not only put other tgsD you n put plin textF his text is the ontents of the elementF sn the exmple wvD the ssignment element hs text in it tht serves s omment on the grdeF he text tht you put inside of n element is unformtted nd n inlude nything you wntF nlike the mrkup prt of the wv doumentD there is no speil formtting on ontentF

14.1.1.5 Special Characters


hile the ontent doesn9t hve ny speil formttingD it is still emedded in n wv doumentF here re ertin hrters tht re speil in wv tht you n9t inlude diretly in the ontentF por exmpleD if you put 9`9 in the ontent it will e interpreted s the eginning of tgF por this resonD there is speil syntx tht you n use to inlude symols in the ontent of n wv (leF 333 8nspY 8quotY 8ltY 8gtY 8mpY

CHAPTER 14.

XML AND PATTERNS

QPR

14.1.1.6 Comments
tust like with odeD it is helpful to osionlly put omments in your wvF e omment egins with 9`3!9 nd ends with 9!b9F ou n put whtever text you wnt etween these s long s it doesn9t inlude the sequene to end the ommentF

14.1.1.7 Overall Format


333 wv spei(tion 333 outside element

14.1.2 Comparison to Flat File


o etter understnd the ene(t of wvD we will ompre our wv (le to )t (le tht might e used to store silly the sme informtionF

CSCI 1320 2 Jason Hughes 98 100 90 90 100 Kevin Peese 85 78 67 20


his is lot shorterD ut unless you hppen to know wht it is enodingD you won9t e le to (gure muh outF xmelyD the numers in the (le re hrd to distinguishF he P ner the top you might e le to (gure outD ut without dditionl informtionD it is impossile to determine whih lines of grdes re ssignmentsD quizzesD or testsF he )t (le lso lks some of the informtion tht ws in the wvF sn prtiulrD the omments on the ssignments in the wv formt re missing in this (leF st would e possile to mke the )t (le ontin suh informtionD ut doing so would use the ode required to prse the )t (le to e muh more omplexF

14.1.2.1 Flexibility in XML


e signi(nt gth PP of wv is tht there re lots of di'erent wys to express the sme informtionF por exmpleD the omment ould hve een given s n ttriute with the nme 9omment9 insted of s ontents of the elementF imilrlyD if you don9t wnt to llow ommentsD you ould shorten the wv to e more like the )t (le y hnging it to the following formtF

CHAPTER 14.

XML AND PATTERNS

QPS

<course name="CSCI 1320"> <student fname="Jason" lname="Hughes"> <quizzes>98 100 90</quizzes> <tests>94</tests> <assignments>100</assignments> </student> <student fname="Kevin" lname="Peese"> <quizzes>85 78</quizzes> <tests>67</tests> <assignments>20</assignments> </student> </course>
rere ll the grdes of the sme type hs een given s ontents of elements with the proper nmesF his mkes things muh shorter nd doesn9t signi(ntly inrese the di0ulty of prsing the grdesF st does remove the )exiility of tthing dditionl informtion with eh grde suh s the ommentsF here isn9t rule tht tells you if informtion should e stored in seprte tgsD s ttriutes in tgsD or s text inside of elementsF por spei( pplitions there will e ertin stndrdsF rwv is perfet exmple of thtF por your own dtD it will e up to you s developer or your tem to determine how you wnt to enode the informtionF htever is deidedD you need to hold to it onsistentlyF

14.1.3 XML in Scala


wv isn9t prt of the norml (rst semester topis in omputer sieneD ut l mkes it so esy tht there is no reson not tooF o see thisD simply go to the iv nd type in vlid wvF

scala> <tag>Some XML.</tag> res0: scala.xml.Elem = <tag>Some XML.</tag>


he l lnguge hs uilt in wv prser tht llows you to write wv diE retly into your odeF ou n see tht the type of this expression is slFxmlFilemF he slFxml pkge ontins the types relted wvF e will run through some of the more signi(nt hereF

ilem E epresents single elementF his is sutype of xodeF xode E epresents more generl node in the wv doumentF his is sutype of xodeeqF xodeeq E epresents sequene of nodesF wv E e helper type tht hs methods for reding nd writing wv (lesF
here re quite few other types tht you n see in the esD ut we will fous on these s they give us the funtionlity tht we need for our purposesF

CHAPTER 14.

XML AND PATTERNS

QPT

14.1.3.1 Loading XML


he wv type is n ojet tht hs methods we n use to either red from (les or write to (lesF he lodpile method n e used to red in (leF sf the (rst exmple wv tht ws shown is put in (le with the nme 9grdesFxml9D then the following ll would lod it inF

scala> xml.XML.loadFile("grades.xml") res4: scala.xml.Elem = <course name="CSCI 1320"> <student lname="Hughes" fname="Jason"> <quiz grade="98"></quiz> <quiz grade="100"></quiz> <quiz grade="90"></quiz> <test grade="94"></test> <assignment grade="100"> Code compiled and runs fine. </assignment> </student> <student lname="Peese" fname="Kevin"> <quiz grade="85"></quiz> <quiz grade="78"></quiz> <test grade="67"></test> <assignment grade="20"> Code didn't compile. </assignment> </student> </course>
glerly this is the ontents of the wv (le tht we hd retedF ell tht is missing is the ommentD whih ws there for humn purposesD not for other progrms to worry outF sn dditionD the empty tgs hve lso een onverted to strt nd end tgs with nothing in etweenF his illustrtes tht the empty tgs were lso just for humn onveniene nd their mening is the sme s n empty pir of strt nd end tgsF

14.1.3.2 Parsing XML


yne we hve this ilem ojet stored in resRD the question eomes how you get the informtion out of itF he xodeeq typeD nd hene the xode nd ilem type whih re sutypes of itD delre opertors lled nd F hese opertors re used to serh inside the ontents of n ojetF foth opertors tke seond rgument of string tht gives the nme of wht you wnt to look forF he di'erene is how fr they serhF he opertor looks only for things t the top levelD either xodes in the urrent sequene if we hve true xodeequeneD or hildren of this node if we hve xode or ilemF he D on the other hndD

CHAPTER 14.

XML AND PATTERNS

QPU

(nds nything tht mthes t ny depth elow the urrent levelF o illustrte thisD we will do three exmple serhesF

scala> res4 \ "student" res5: scala.xml.NodeSeq = NodeSeq(<student lname="Hughes" fname="Jason"> <quiz grade="98"></quiz> <quiz grade="100"></quiz> <quiz grade="90"></quiz> <test grade="94"></test> <assignment grade="100"> Code compiled and runs fine. </assignment> </student>, <student lname="Peese" fname="Kevin"> <quiz grade="85"></quiz> <quiz grade="78"></quiz> <test grade="67"></test> <assignment grade="20"> Code didn't compile. </assignment> </student>) scala> res4 \ "test" res6: scala.xml.NodeSeq = NodeSeq() scala> res4 \\ "test" res7: scala.xml.NodeSeq = NodeSeq(<test grade="94"></test>, <test grade="67"></test>)
he (rst two serhes use the opertorF he (rst one serhes for elements tht hve the tg nme studentF st (nds two of them euse they re t the top level nd gives us k xodeeq with them in itF he seond serh looks for tgs tht hve the nme testF his serh returns n empty xodeeqF his is euse while there re tgs with the nme test in resRD they re nested more deeply inside of the student elements s s suhD ren9t found y the opertorF he lst exmple serhes for the sme tg nmeD ut does so with D whih serhes more deeplyD nd hene gives k xodeeq with two xodes inside of itF he nd opertors n lso e used to get the ttriutes from elementsF o get n ttriute insted of tgD simply put 9d9 t the eginning of the string you re serhing forF rere re three serhes to illustrte thisF

scala> res4 \ "@name" res8: scala.xml.NodeSeq = CSCI 1320 scala> res4 \ "@grade" res9: scala.xml.NodeSeq = NodeSeq() scala> res4 \\ "@grade" res10: scala.xml.NodeSeq = NodeSeq(98, 100, 90, 94, 100, 85, 78, 67, 20)
he (rst serh uses to get the nme of the top level nodeF sing to look for grde t the top level node doesn9t give us nythingD ut using will return

CHAPTER 14.

XML AND PATTERNS

QPV

the vlues of ll the grdes in the doumentF yf ourseD wht you relly wnt to do is put the informtion from the wv (le into struture tht n e used in the progrmF qiven wht we hve lernedD this would men tht we wnt to put things into se lssesF he dt in this wv (le orresponds very losely to the student type tht ws reted in hpter IHF ht se lss looked like thisF

case class Student(name:String,assignments:List[Double],tests:List[Double], quizzes:List[Double])


sn tht hpter we prsed )t (le into n rry of tudentsF xow we will demonstrte how to do the sme thing using the wvF e will strt with funtion tht tkes xode tht should e student ilement nd returns tudent ojetF uh funtion might look like the followingF

def studentFromXML(elem:xml.Node):Student = Student((elem \ "@fname")+" "+(elem \ "@lname"), (elem \ "assignment").map(n => (n \ "@grade").toString.toDouble).toList, (elem \ "test").map(n => (n \ "@grade").text.toDouble).toList, (elem \ "quiz").map(n => (n \ "@grade").text.toDouble).toList)
his funtion uilds tudent ojet nd psses in the four required rgumentsF he (rst is the nmeD whih is mde from the fnme nd lnme ttriutes of the elementF efter tht re three lists of grdes for the ssignmentsD testsD nd quizzes respetivelyF hese ll hve similr formF hey strt y doing serh for to proper tg nme nd mpping the result to funtion tht onverts the vlue of the grde ttriute to houleF he ll to text is required euse the result of here is xodeD not tringD nd the xode type doesn9t hve tohoule methodF he lst prt of eh grde type is ll to tovistF his is required euse the mp is working on xodeeq nd will give k xodeeqD ut vist is required for the tudent typeF he use of mp proly doesn9t jump out to you t (rstF ropefully ut this point you hve euse quite omfortle with it nd other higher order methodsF roweverD if you think it you will relize tht is is it surprising here euse the thing it is eing lled on is not vist or n erryF snstedD it is xodeeqF his works euse the xodeeq is itself sutype of eqxodeD mening tht ll the methods we hve een using on other sequenes work just (ne on this s wellF his is useful for getting our rry of students s wellF he following line shows how we n use mp nd toerry to get the result tht we wnt with the studentpromwv funtionF

scala> (res4 \ "student").map(studentFromXML).toArray res15: Array[Student] = Array(Student(Jason Hughes,List(100.0),List(94.0),List(98.0, 10

CHAPTER 14.

XML AND PATTERNS

QPW

eginD the ll to toerry gives us k the desired errytudent insted of more generl eqtudentF he text method pplied to full ilem will give you ll of the text tht ppers inside of it nd ll suEelementsF o lling text on resR gives the two omments long with lot of whitespeF o get just the omment on ny prtiulr grdeD you would prse down to tht spei( element nd ll the text method on itF

14.1.3.3 Building XML


o now you know how to get the ontents of n wv (le into useful form in lF ht out going the other wyc essume tht the ode we just wrote were used in the menu sed pplition from hpter IH nd tht hnges were mde nd now we wnt to write the results k out to (leF he (rst step in this would e to uild the xode tht represents the dtF e sw ove tht we n put wv diretly into l progrm or the iv nd it will e prsed nd understoodF roweverD tht lone doesn9t give us the ility to put vlues from the progrm k into the wv (leF portuntelyD this isn9t hrd to do eitherF snside of wv tht is emedded in l progrm you n emed l expressions inside of urly resF e9ll strt with simple exmpleF

scala> <tag>4+5 is {4+5}</tag> res19: scala.xml.Elem = <tag>4+5 is 9</tag>


rere the expression RCS hs een put in urly res nd s you n see it evlutes to the vlue W s it shouldF he ode you put inside of the urly res n e fr more omplex nd uilt dditionl wv ontent or tgsF e will use this to write funtion tht pks tudent ojet into n wv nodeF his ode looks like the followingF

def studentToXML(stu:Student):xml.Node = { val nameParts=stu.name.split(" +") <student fname={nameParts(0)} lname={nameParts(1)}> {stu.quizzes.map(q => <quiz grade={q.toString}/>)} {stu.tests.map(t => <test grade={t.toString}/>)} {stu.assignments.map(a => <assignment grade={a.toString}/>)} </student> }
he (rst line splits the student nme into piees round spesF st is ssumed tht the (rst element is the (rst nme nd the seond element is the seond nmeF hese re used s ttriute vlues in the student tgF snside of tht element re three lines of odeD one eh for quizzesD testsD nd ssignmentsF ih of these mps orresponding list to set of elements with grde ttriutesF st is worth noting two things out using ode for the ttriute vluesF pirstD the quotes ren9t written nywhereF hey re utomtilly provided when the

CHAPTER 14.

XML AND PATTERNS

QQH

vlue is l odeF eondD the type of the l expression for the vlue hs to e tringF his is pprent with the grde vluesF hey re houles nd hve to e expliitly onverted to tringsF

14.1.3.4 Writing XML to File


yne you hve the xode you wnt to writeD the writing proess is s esy s ll to the sve method of the wv ojetF

xml.XML.save("grades.xml",node)
he (rst rgument is the nme of the (le you wnt to write toF he seond is the xode tht you wnt to writeF

14.1.4 DTDs (Advanced)


333

14.2 Patterns
he onept of pttern is something we hve enountered previouslyD ut hven9t relly explored until nowF st is something tht doesn9t ome up in most progrmming lngugesD only those tht pull elements from the wv lngugeF roweverD in those tht support ptternsD it n provide signi(nt mount of power nd llows the progrmmer to express ertin types of ides muh more esily thn they ould without ptternsF he ide of pttern is something tht is tught in elementry shoolF ou typilly strt with si repeting ptterns like efefefF tudents re sked to identify the pttern in sequenes or olors or shpes with the nture of the ptterns inresing in omplexity over timeF he ide of pttern in progrmming lnguge is extly the smeF he progrmmer spei(ed n expression nd then one or more ptterns tht the expression might mth withF he progrm is supposed to (gure out mth etween the vlue of the expression nd pttern nd perform to pproprite tionF he most ovious form of ptterns in l is in the mth expressionF

14.2.1 Variable Binding 14.2.2 Case Class Patterns


333 snlude event ptterns

14.2.3 XML Patterns 14.2.4 Patterns Everywhere


333 mth

CHAPTER 14.

XML AND PATTERNS

QQI

333 vrile delrtion 333 for loop

14.3 Primality Testing


Self-Directed Study
inter the following sttements into the iv nd see wht they doF ome will produe errorsF ou should try to (gure out whyF ry some vritions to mke sure you understnd wht is going onF

scala> def succ(n:Int):Int = n+1 scala> succ(1)


333

Exercises
IF ixerise

Projects
IF sf you hve een working on the di'erent grphis options for erlier projets the mteril in this hpter gives you ler extensionD store your geometry dt in n wv (le insted of )t text (leF ou n use tgs like sphere nd plne to give mening to the informtionF edd in light tg s well in ntiiption of dding lighting in future projetF efter you hve the wv formt set up nd some dt to ply withD lter the ode from projet IPFU to use this dt formtF PF rojet IHFQ is very niely extended with the use of wv dt (lesF sing wv lso mkes it esier to extend the (le to inlude dditionl inforE mtionF por this projet you should onvert your mp over to n wv formt nd hve the ode red in tht formtF sn dditionD you should dd itemsF his will involve dding nother se lss for n item nd putting some items into rooms in the wv dt (leF o mke the items signi(ntD you need to hve it so tht the se lss for your room inludes items in tht room nd the text desription of the room lists wht items re thereF ou should lso give you plyer n inE ventory nd implements ommnds for get nd dropF o if the plyer enters get followed y the nme of n item in the roomD tht item will e tken out of the room nd dded to the plyers inventoryF en inv ommnd would e nie to let the plyer see wht is in hisGher inventoryF sf the plyer uses the drop ommnd followed y n item in inventoryD

CHAPTER 14.

XML AND PATTERNS

QQP

tht item should e removed from inventory nd pled in the urrent roomF sf get or drop re provided with n invlid item nmeD print n pproprite messge for the userF QF sf you did projet IQFRD you hd text (le tht spei(ed the high sores for plyers of prtiulr gmeF por this projet you should modify you ode nd the text (le to use wv insted of )t (leF RF he wndelrot set is fmous frtl in the omplex plne disovered y fenoit wndelrotF e we serh will provide you with lots of informE tion on this eutiful strutureF rt of wht is so remrkly out the wndelrot set is tht it hs suh simple de(nitionD ut ontins in(nite omplexitiesF he set is de(ned s the pointsD cD in the omplex plne for 2 + cD where z0 = 0 gives ounded sequeneF whih the eqution zn+1 = zn sn prtieD if the vlue of |z | ever goes eyond PD the sequene will divergeF o progrms to explore the wndelrot set ount the numer of itertions to reh tht point nd ssign olor sed on how mny itertions it tkesF feuse the points in the set itself will never divergeD there hs to e some mximum numer of itertions t whih point you simply sy it is in the setF por this projet you will write qs progrm tht displys the wnE delrot setF ou hve view on the set with minimum nd mximum vlues in the rel nd omplex xesF ellow the user to zoom in y likE ingF he wv omes in euse you should hve menu option tht llows the user to keep list of fvorite viewsF ht list should e sved in wv nd eh view should hve nme the user ssignsD the view regionD nd vlue for the mximum itertionsF SF wusi wv refers to wusiEqs

Chapter 15

Sets, Maps, and Buers


fk in hpter U we tlked out the most si sequene olletions in lD the erry nd the vistF ine then we hve seen other similr typesF hese olletions shre lrge numer of di'erent methods tht we hve used to gret e'etF he sequenes ren9t the only type of olletion thoughF he l olletions lirry is fr more extensive thn wht we hve seen so frF sn this hpter we will look t numer of other olletionsF

15.1 Sets
he onept of set omes from mthF here re two min di'erenes etween the et type nd the eq typeF he most importnt one is tht et does not llow duplite vluesF sf you dd something to et nd there is lredy something there tht is equl to itD it doesn9t dd new vlue nd the size of the resulting set is the sme s wht you hd eforeF he other di'erene is tht the order of elements in et isn9t gurnteedF e n see oth of these e'ets in the following sequene of iv ommndsF

scala> Set(1,2,3) res0: scala.collection.immutable.Set[Int] scala> res0 + 4 res1: scala.collection.immutable.Set[Int] scala> res1 + 2 res2: scala.collection.immutable.Set[Int] scala> res1 + -10 res3: scala.collection.immutable.Set[Int]

= Set(1, 2, 3) = Set(1, 2, 3, 4) = Set(1, 2, 3, 4) = Set(-10, 4, 1, 2, 3)

his egins with set tht hs the vlues ID PD nd QF es with the vist nd erry typesD l (gures out tht this is etsntF ou n lso see from the inferred type tht y defult we get n immutle setF ou n dd to set with CD you get k new set tht hs the element fter the plus sign dded inF he seond sttement gives us k set tht QQQ

CHAPTER 15.

SETS, MAPS, AND BUFFERS

QQR

inludes R in ddition to the ID PD nd QF sn the third ommnd we dd P to this new setF he result looks the sme s the set efore the P ws ddedF his is euse the set n9t ontin duplite elementsF he lst sttement dds the vlue EIH into the set from resIF his vlue goes into the resulting set euse there hdn9t een EIH previouslyF roweverD the result shows tht order is not preserved in setsF edding the EIH into the set not only put it in n odd ple t the eginningD it lso ltered the lotion of the R in the setF prom this you n see tht you wnt to use sets when wht you re out is the uniqueness of elementsD not the order in whih you get themF he ft tht the order n hnge mens tht indexing into set in the mnner we hve done with n erry or vist don9t hve muh meningF ou n perform tht type of opertion on etD howeverD ut the mening is it di'erentF gonsider the following exmplesF

scala> res3(2) res4: Boolean = true scala> res3(5) res5: Boolean = false scala> res3(-10) res6: Boolean = true
his type of opertion on set doesn9t give you k vlue t prtiulr lotionF snstedD it returns foolen tht tells you whether ot not the spei(ed vlue is in the setF his works eqully well if the set ontins vlues other thn sntsF gonsider the followingF

scala> val strSet=Set("Mark","Jason","Kevin") strSet: scala.collection.immutable.Set[java.lang.String] = Set(Mark, Jason, Kevin) scala> strSet("Jason") res7: Boolean = true scala> strSet("Bill") res8: Boolean = false
sn this exmpleD the set ontins trings nd the indexing is done y pssing in tringsF he mening is the sme either wyF he return vlue is true if the rgument pssed in is in the set nd flse if it is notF

15.1.1 Running Through Sets


sn ddition to the stndrd higher order methods like mpD (lterD nd foreh tht re ville for oth the et nd the sequenes tht we hve worked with previouslyD the et type works perfetly well with for loops s wellF

scala> for(v <- res3) println(v) 1 2 -10

CHAPTER 15.

SETS, MAPS, AND BUFFERS

QQS

3 4
sn ftD you n9t relly use while loop to run through set euse you n9t index y positionF elsoD the order in whih the loop runs through the set vlues is not something you n preditF st doesn9t even hve to mth the order tht the vlues re displyed when the et is onverted to tring for printingF

15.1.2 Mutable vs. Immutable


he exmples ove showed the defult immutle setF vike the vist type tht we sw previouslyD the immutle set doesn9t hnge fter it is retedF hen we dd elements to the set with the C opertorD we get k new set nd the originl set is unlteredF e n demonstrte this y lling k up the originl setF

scala> res0 res9: scala.collection.immutable.Set[Int] = Set(1, 2, 3)


ell of the opertions tht were done hven9t ltered it in ny wyF here is nother type lled set on the pkge slFolletionFmutleF ou ould get to this type using the fully spei(ed nme of slFolletionFmutleFetF roweverD doing so not only requires lot of typingD it lso mkes ode di0ult to redF ou ould import slFolletionFmutleFet nd then refer to it s just etF he prolem with this pproh is tht you n no longer esily refer to the immutle et typeF e reommended style for deling with this is to import slFolletionFmutleF he pkges in l re truly nestedF es resultD this import will llow us to refer to mutle set y the nme mutleFet nd the immutle set s just etF ell the opertions tht you n do with n immutle set re ville on mutle set s wellF eove we used the C opertor on the immutle set nd it works eqully well on the mutle setF

scala> import scala.collection.mutable import scala.collection.mutable scala> val mset=mutable.Set(1,2,3) mset: scala.collection.mutable.Set[Int] = Set(1, 2, 3) scala> mset + 4 res10: scala.collection.mutable.Set[Int] = Set(1, 4, 2, 3) scala> mset res11: scala.collection.mutable.Set[Int] = Set(1, 2, 3)
his ode shows you the import sttementD the delrtion of mutle set fter the importD nd the retion of new set y dding n element to the old oneF tust using C does not hnge the mutle setF he wy in whih the mutle set di'ers from the immutle version is tht it inludes dditionl opertors nd methodsF

CHAPTER 15.

SETS, MAPS, AND BUFFERS

QQT

o see this we will ll one of those extr opertorsF yn mutle set we n use Ca the sme wy we might with n snt tht ws delred s vrF

scala> res12: scala> res13:

mset += 4 mset.type = Set(1, 4, 2, 3) mset scala.collection.mutable.Set[Int] = Set(1, 4, 2, 3)

ou n see from this tht the use of Ca tully hnges the originl setF he Ca does not exist on the immutle set typeF sf you try to ll itD you will get syntx errorF he list of methodsGopertors on the mutle set tht mutte them inludes the following for eteF

Ca@elem X eA E edds the spei(ed element to the setF Ea@elem X eA E emoves the spei(ed element from the setF hoes nothing if it wsn9t there initillyF CCa@xs X rversleyneeA E edds ll the elements from olletion into the setF he rversleyne type is the most si type for l olletions so this n e used with ny of the olletions in lF !a@xs X rversleyneeA E emoves ll the elements in xs from the setF dd@elem X eA X foolen E edds the spei(ed element to the setF eturns true if it wsn9t there efore the ll nd flse otherwiseF ler@AXnit E emoves ll elements from the setF remove@elem X eA X foolen E emoves the spei(ed element from the set nd returns true if it ws there to remove of flse otherwiseF retin@p X @eA ab foolenA X nit E emoves ll elements tht don9t stisfy the predite from the setF
wutle sets n lso e updted using ssignmentF his is silly the inverse opertion of indexing tht we sw eforeF he index is the vlue you re djusting in the set nd the ssignment is either to true or flseF o see how this worksD onsider the following exmplesF

scala> scala> scala> res14:

mset(7)=true mset(2)=false mset scala.collection.mutable.Set[Int] = Set(1, 4, 7, 3)

he (rst line dds U to the et while the seond removes PF irlier in this setion it ws mentioned tht the stndrd methodsD like mp nd (lterD will do the sme thing on mutle set s the do on n immutle setF his ws very intentionlF he sme opertions on losely relted types like this

CHAPTER 15.

SETS, MAPS, AND BUFFERS

QQU

should lwys hve the sme outwrd pperneF his redues the hnes of progrmmers mking silly mistkesF sf you wnt to mutte the set you hve to ll one of the spei( methods for doing soF por exmpleD you would ll retin insted of (lterF sf you identlly try to use one of these opertions on n immutle type the ode won9t ompileF sf the opertions with the sme nme hd di'erent ehviorsD it would e very esy for the progrmmer to introdue logi errors euse heGshe elieved n ojet ws one type when it ws tully notherF

15.1.3 Using a Set


o see how et n e useful we will write funtion tht tells us ll the unique words in text (leF he funtion will tke the nme of the (le s n rgument nd return ettring tht hs ll the words in lower seF es with ny funtion of ny signi(neD this n e done in mny wysF e re going to do it mking hevy use of the l olletion methodsF he ft tht we re using the olletion methods mkes it more sensile to use oure thn nnerF rere is ode tht will do thisF

def uniqueWords(fileName:String):Set[String] = { val source = io.Source.fromFile(fileName) val words = source.getLines.toSeq.flatMap(_.split(" +")). map(_.filter(_.isLetter).toLowerCase).toSet source.close() words }
e funtion is de(ned using the signture tht ws desriedF his funtion inludes only four sttementsF he (rst nd third sttements in the funtion open the (le nd lose itF he lst sttement is just n expression for the set tht ws reted from the soureF he seond sttement is where ll the work is done nd is worth looking t in detilF his line delres the vrile words nd mkes it equl to set of the wordsF o do tht it gets the lines from the soure nd turns them into sequenesF he toeq ll mkes types work out etter with the )twpF es you might rellD getvines returns n stertorF he stertor type is olletion tht you n only pss through oneF st is onsumed during tht pssF st is lower level tht errys nd vistsF fy umping it up to sequene we get something tht works etter with the errytring tht we get from the split methodF efter the lines re onverted to sequene there is ll to )twpF his is one of the stndrd higher order methods on olletionsF e hven9t used it muh so it is worth tking minute to disussF es you n tell from the nmeD )twp is losely relted to mpF he mp method tkes eh element of olletionD pplies some funtionD nd mkes new olletion tht hs the results of tht funtion pplitionF he )twp does silly the sme thing only it expets tht the funtion pssed in is going to return olletionsF snsted

CHAPTER 15.

SETS, MAPS, AND BUFFERS

QQV

of returning olletion of olletionsD )twp will )tten out ll of the inner olletions into one long olletionF sf you use mp on the sequene of lines nd use the sme mp funtionD you will get eqerrytringF ih element of the sequene will ontin n rry of the words from tht lineF roweverD tht isn9t quite wht we wntF e wnt simple sequene of wordsD not sequene of rrys of wordsF his is wht )twp does for usF st puts eh of the rrys end to end in the new sequene so tht we get eqtringF sf we knew tht the (le only inluded simple words in lower se we ould stop thereF roweverD most text (les will inludes pitliztion nd puntution s wellF his would mess up the set euse ri is not equl to hi nd you two would e seprte in the (leF imilrlyD the word dog would e di'erent thn dogF or dogD if the word hppened to pper diretly efore puntution mrkF he seond line of the seond sttement inludes logi to del with thisF ih of the words tht the (le ws roken into is pssed through mpF ht mp (lters out ny nonEletter hrters nd onverts the resulting strings to lower seF he (ltering of nonEletter hrters is perhps too ggressive euse it removes things like postophies in ontrtionsD ut the result it provides is su0iently orret for our purposesF he lst thing tht hppens in the seond sttement is tht the sequene is onverted to setF his gives us the type we desired nd removes ny nonE unique elements y virtue of eing setF

15.2 Maps
enother olletion type tht is extremely usefulD proly more so thn the et in most progrmsD is the wpF vike the etD the term wp hs origins in mthF e mpping in mthemtis is something tht tkes vlues from one set nd gives k vlues from nother setF e funtion is mth is tehnilly mppingF he wp olletion type isn9t so di'erent from thisF st mps from vlue of one typeD lled the key typeD to nother type lled the vlue typeF he key nd vlue types n e the smeD ut they re very often di'erentF o help you understnd mpsD let9s look t some exmplesF e9ll strt with sttement to rete new mpF

scala> val imap=Map("one" -> 1, "two" -> 2, "three" -> 3) imap: scala.collection.immutable.Map[java.lang.String,Int] = Map((one,1), (two,2), (thr
he wp type tkes two prmetersF sn this exmple they re tring nd sntF he vlues pssed in to uild the wp re tully tuples where the key is the (rst element nd the vlue is the seond elementF sn this exmple we used the Eb syntx tht ws disussed in hpter QF his syntx ws dded to the l lirries for this ext purposeF ou n red this s mking mp where the tring one mps to the snt I nd so onF hen you index into mp you do so with vlues of the key typeF ht you get in return is the orresponding vlue ojetF

CHAPTER 15.

SETS, MAPS, AND BUFFERS

QQW

scala> imap("two") res0: Int = 2


sf you likeD you n think of mp s olletion tht n e indexed y ny type tht you wnt insted of just the integer indexes tht were used for sequenesF sf you try to pull out key tht isn9t in the mpD you will get n exeptionF sn ddition to llowing ny type for the keyD the mp lso hs the ene(t tht it doesn9t require ny prtiulr strting vlue for the indexesF por this resonD you might sometimes wnt to uild mp tht uses n snt s the indexF gonsider this exmpleF

scala> val imap2=Map(10 -> "ten", 100 -> "hundred", 1000 -> "thousand") imap2: scala.collection.immutable.Map[Int,java.lang.String] = Map((10,ten), (100,hundre
ehnilly you ould uild sequene tht hs the vlues tenD hundredD nd thousnd t the proper indexesF roweverD this is very wsteful euse there re mny indexes etween H nd IHHH tht you won9t e using nd they would hve null referenes in themF es with the et typeD you n dd new keyD vlue pirs to the mp with the C opertorF

scala> imap + ("four" -> 4) res1: scala.collection.immutable.Map[java.lang.String,Int] = Map((one,1), (two,2), (thr


he key nd vlue need to e in tupleD just like when the originl mp ws uiltF he prenthese in this smple re required for proper order of opertionF ytherwise the C hppens efore the Eb nd the result is @tringDsntA tht will look rther unusulF ou n lso use the E opertor to get mp with fewer elementsF por this opertionD the seond rgument is just the key you wnt to removeF ou don9t hve to hve or even know the vlue ssoited with tht keyF

scala> imap - "two" res2: scala.collection.immutable.Map[java.lang.String,Int] = Map((one,1), (three,3))


rere we remove the vlue P from the mp y tking out the key twoF es with the et typeD there re mutle nd immutle )vorsF es you n see from the exmples oveD the defult for the mpD like for the setD is immutleF o use the mutle version you should follow the sme reommenE dtion s ws given for the set nd import slFolletionFmutle nd then refer to it s mutleFwpF

15.2.1 Looping Through a Map


ou n use the higher order methods or for loop to run through the ontents of wpD ut there is signi(nt di'erene etween this nd the other olletions

CHAPTER 15.

SETS, MAPS, AND BUFFERS

QRH

we hve looked tF his is euse the ontents of the mp re e'etively tuplesF o illustrte thisD we9ll look t simple for loopF

scala> for(tup <- imap) println(tup) (one,1) (two,2) (three,3)


ih element tht is pulled o' the mp is tupleF his hs signi(nt impliE tions when using higher order methods like mpF he rgument to mp is funtion tht tkes single rgumentD ut tht rgument is tuple with keyEvlue pir in itF gonsider the following odeF

scala> imap.map(tup => tup._2*2) res3: scala.collection.immutable.Iterable[Int] = List(2, 4, 6)


feuse the rgumentD tupD is tupleD we hve to use the P method to get vlue out of itF he I method would give us the keyF he lterntive is to mke the ody of the funtion longer nd use pttern in n ssignment to pull out the vluesF por mny situtions this isn9t signi(ntly etterF unning through mp works muh etter with for loop euse the for loop does pttern mthing utomtilly s ws disussed in IRFPFRF his syntx is shown hereF

scala> for((k,v) <- imap) yield v*2 res4: scala.collection.immutable.Iterable[Int] = List(2, 4, 6)


his syntx isn9t signi(ntly shorter for this exmple though it n e in others nd it is esier for most people to redF he rel dvntge is tht you n esily use meningful vrile nmesF his exmple used k nd v for key nd vlueD ut in full progrm you ould use nmes tht rry signi(ntly more meningF ou might hve notied tht oth the exmple with mp nd with the for loop gve k listsF his is lso it di'erent s we re used to seeing this type of opertion give us k the sme type tht ws pssed inF he prolem is tht to uild mp we would need keyD vlue pirsF he wy the lirries for l re writtenD you will utomtilly get k mp ny time tht you use funtion tht produes tupleF

scala> imap.map(tup => tup._1 -> tup._2*2) res5: scala.collection.immutable.Map[java.lang.String,Int] = Map((one,2), (two,4), (thr scala> for((k,v) <- imap) yield k -> v*2 res6: scala.collection.immutable.Map[java.lang.String,Int] = Map((one,2), (two,4), (thr
hese two exmples show how tht n work using either mp or the for loop with yieldF

CHAPTER 15.

SETS, MAPS, AND BUFFERS

QRI

15.2.2 Using Maps


he exmple we will use for illustrting use of wp is losely relted to the one we used for the etF snsted of simply identifying ll the wordsD we will ount how mny times eh one oursF his funtion will strt o' very similr to wht we did eforeF e9ll strt with this templteF

def wordCount(fileName:String):Map[String,Int] = { val source = io.Source.fromFile(fileName) val words = source.getLines.toSeq.flatMap(_.split(" +")). map(_.filter(_.isLetter).toLowerCase) val counts = // ??? source.close() counts }
rere words will just e sequene of the words nd we will use it to uild the ounts nd return wp with those ountsF e will do this lst prt in two di'erent wysF he (rst pproh will use mutle mpF he logi here is tht we wnt to run through the sequene of words nd if the word hsn9t een seen efore we dd ount of I to the mpF sf it hs een seen eforeD we dd the sme key k inD ut with vlue tht is one lrger thn wht we hd eforeF he ode for this looks like the followingF

def wordCount(fileName:String):mutable.Map[String,Int] = { val source = io.Source.fromFile(fileName) val words = source.getLines.toSeq.flatMap(_.split(" +")). map(_.filter(_.isLetter).toLowerCase) val counts = mutable.Map[String,Int]() for(w <- words) { if(counts.contains(w)) counts += w -> (counts(w)+1) else counts += w -> 1 } source.close() counts }
xote tht the for loop to run through the words here ours fter the delE rtion of ountsF feuse ounts is mutle this pproh worksF ou should lso note tht the return type for the funtion hs een ltered to e mutE leFwptringDsntF sf you leve this o'D you hve to dd ll to Ftowp t the end fter ounts so tht the ounts will e onverted to n immutle typeF his distintion etween mutle nd immutle types is very sign(int for sfety in progrmsF sn generl there ould e other referenes to the wp you re given tht re retined in other prts of the odeF sf it were possile for

CHAPTER 15.

SETS, MAPS, AND BUFFERS

QRP

you to get mutle mp when you were expeting n immutle oneD those other prts of the ode ould lter the mp when you weren9t expeting itF his would led to very hrd to trk down logi errorsF sing the mutle version is firly logil nd n hve some e0ieny dE vntgesD ut s ws just lluded toD mutle vlues ome with risksF por this resonD we will write seond version tht uses n immutle mp nd the foldveft methodF he foldveft method is more omplex method tht we hven9t relly delt with eforeF roweverD it is idel for wht we re doing here s it e'etively does wht we write previouslyD ut without the need for for loopF he foldveft method runs through the olletion from left to right nd pplies funtion to eh element in turn ompiling result s it goesF he funtion is urried nd the (rst rgument list is single vlue tht tells wht the ompiles vlue should strt o' sF sn this seD we re ompiling wp so we will strt o' with n empty oneF he ode we wnt to pply is very muh like wht ws in the for loop previouslyF his is wht it ll looks like when put togetherF

def wordCount2(fileName:String):Map[String,Int] = { val source = io.Source.fromFile(fileName) val words = source.getLines.toSeq.flatMap(_.split(" +")). map(_.filter(_.isLetter).toLowerCase) val counts = words.foldLeft(Map[String,Int]())((m,w) => { if(m.contains(w)) m + (w -> (m(w)+1)) else m + (w -> 1) }) source.close() counts }
he funtion tht is pssed into foldveft tkes two rgumentsF he (rst is the ompiled vlue so fr nd the seond is the vlue tht is eing operted onF sn this se the ompiled vlue is wp nd we use the vrile m to represent itF he vlue eing pssed in is the next word tht we wnt to ount nd is represented y the nme w s it ws in the for loop previouslyF he ody of the funtion pssed into foldveft s the seond rgument list di'ers from wht ws inside the for loop previously in two wysF pirstD insted of referring to the mutle wp ountsD we use the rgument nme mF eondD we don9t use CaF snsted we just use CF he Ca opertor isn9t de(ned for the immutle mp nd wht we re doing here is uilding new immutle mp tht is pssed forwrd to e used with the next wordF sf you relly wnt to push things little hrder you n get rid of the delrtion of words ll togetherF efter llD the only thing it is used for is s the rgument to foldveft to uild ountsF hoing this nd getting rid of some urly res tht ren9t tehnilly needed produes the following odeF

def wordCount3(fileName:String):Map[String,Int] = { val source = io.Source.fromFile(fileName)

CHAPTER 15.

SETS, MAPS, AND BUFFERS

QRQ

val counts = source.getLines.toSeq.flatMap(_.split(" +")). map(_.filter(_.isLetter).toLowerCase). foldLeft(Map[String,Int]())((m,w) => if(m.contains(w)) m + (w -> (m(w)+1)) else m + (w -> 1)) source.close() counts

his ode is rther omptD ut whether you relly wnt to do things this wy or not is detleF he introdution of the vrile words did dd extr length to the odeD ut for most reders it proly lso mde things more understndleF rving ny version of wordgount impliitly gives us set of the words s wellF his is euse the wp type hs method lled keyet tht resturns et of ll of the keys used in the wpF feuse eh key n only our oneD nothing is lost when you get the keys s setF por e0ieny resons you would proly wnt to keep the uniuqeords funtion round if you were going to e using it often insted of repling lls to it with wordgount@(leFtxtAFkeyet euse the ounting of the words does fir it of extr work tht isn9t tehnilly needed to produe the etF e more generly use se for mps is using them s fst wy to look up groups of dt like se lsses y prtiulr key vlueF en exmple of this would e looking up se lss tht represents student y the students sh or perhps their unique login numerF he rel power of the wp type omes from the ft tht the key nd vlue types n e nything tht you wntF

15.3 Buers
he lst of the new olletion types tht we wnt to introdue in this hpter is the fu'erF he fu'er type is like n erry tht n hnge sizeF es resultD the fu'er type is impliitly mutleF here is no immutle u'erF sf you re using other mutle typesD the rule of importing slFolletionFmutle nd referring to fu'er s mutleFfu'er will still work well nd it mkes it perfetly ler to nyone reding the ode tht you re using mutle typeF roweverD euse the fu'er type is only mutle you ould lso onsider doing n import of slFolletionFmutleFfu'er nd simply lling it fu'er in your odeF here re severl sutypes of fu'er in the l lirriesF he two most signi(nt ones re erryfu'er nd vistfu'erF yne uses n rry to store vluesF he other uses struture lled linked listF he vist type in l is lso linked listD though it is not diretly used y the vistfu'er s the vistfu'er needs to e mutleF e will use the erryfu'er in this hpterF he nture of the vistfu'er nd how it is di'erent will eome more pprent in hpter PSF ou n rete u'er in extly the wy tht you would expetF

CHAPTER 15.

SETS, MAPS, AND BUFFERS

QRR

scala> val buf = mutable.Buffer(1,2,3,4,5) buf: scala.collection.mutable.Buffer[Int] = ArrayBuffer(1, 2, 3, 4, 5)


ou n lso use some of the methods we lerned out for erry nd vist like (ll nd tulteF

scala> val rbuf=mutable.Buffer.fill(10)(math.random) rbuf: scala.collection.mutable.Buffer[Double] = ArrayBuffer(0.061947605764430924, 0.029


ou n index into u'er nd hnge vlues the sme wy you did for n rryF

scala> rbuf(3) res0: Double = 0.7098206843826819 scala> buf(3)=99 scala> buf res1: scala.collection.mutable.Buffer[Int] = ArrayBuffer(1, 2, 3, 99, 5)
he wy in whih the fu'er type di'ers from the erry type is tht it n esily grow nd shrinkF here re whole set of methods tht tke dvntge of thisF rere re some of themF

Ca@elemX eAX fu'ere E eppend the element to the u'er nd return the sme u'erF CaX@elemX eAX fu'ere E repend the element to the u'er nd return the sme u'erF CCa@xsX rversleyneeAX fu'ere E eppend the elements in xs to the u'er nd return the sme u'erF CCaX@xsX rversleyneeAX fu'ere E repend the elements in xs to the u'er nd return the sme u'erF Ea@elemX eAX fu'ere E emove the element from the u'er nd return the sme u'erF !a@xsX rversleyneeAX fu'ere E emove ll the elements in xs from the u'er nd return the u'erF ppend@elemX eAX nit E eppend the element to the u'erF ppendell@xsX rversleyneeAX nit E eppend the elements in xs to the u'erF ler@AX nit E emove ll the elements from the u'erF insert@nX sntD elemsX eBAX nit E snsert the spei(ed elements t the spei(ed indexF

CHAPTER 15.

SETS, MAPS, AND BUFFERS

QRS

insertell@nX sntD elemsX rversleeAX nit E snsert ll the elements in elems t index nF prepend@elemsX eBAX nit E repend the elements to this u'erF prependell@xsX rversleyneeAX nit E repend ll the elements in xs to this u'erF remove@nX sntD ountX sntAX nit E emove ount elements strting with the one t index nF remove@nX sntAX e E emove the one element t index n nd return itF trimind@nX sntAX nit E emove the lst n elements from this u'erF trimtrt@nX sntAX nit E emove the (rst n elements from this u'erF
wost of these should e firly selfEexplnitoryF he only methods tht you might question re the ones tht involve symolsF here re two things of interest hereF he (rst is tht they ll return the u'er tht they re lled onF he reson for this is tht it llows you to string them together to ppend or prepend multiple elements in rowF gonsider this exmple with ppendingF

scala> buf += 6 += 7 res2: buf.type = ArrayBuffer(1, 2, 3, 99, 5, 6, 7)


rere oth T nd U re ppended in single lineF he other opertions tht might seem odd re CaX nd CCaXF hese opertions sy tht they prependF ht is interesting out them is their usgeF rere is n exmpleF

scala> 0 +=: buf res3: buf.type = ArrayBuffer(0, 1, 2, 3, 99, 5, 6, 7)


he vlue to e prepended is to the left of the opertor nd the u'er is on the rightF sn some wys tht mkes sense given where it is in the u'er fter the prependingF e hve seen something like this efore s wellF he ons opertor on list is XX nd it prepends the element to the listF ht opertor lso ends with olonF his is one of the more essoteri rules of lF eny symoli opertor method tht ends in olon is right ssoitive insted of eing left ssoitive the wy most opertors reF his mens tht the ojet the opertor works on is to the right of the opertor nd the opertions re grouped going from the right to the leftF

Self-Directed Study
inter the following sttements into the iv nd see wht they doF ome will produe errorsF ou should try to (gure out whyF ry some vritions to mke sure you understnd wht is going onF

CHAPTER 15.

SETS, MAPS, AND BUFFERS

QRT

scala> def succ(n:Int):Int = n+1 scala> succ(1)


333

Exercises
IF ixerise

Projects
IF por this projet you will write little progrm to work s musi lirryF his projet pulls in elements from projet IRFS where you stored musi lirry in wv formtF he use of (lter to nrrow down the songs tht re displyed sed on rtistD etF works (ne for smll lirriesD ut it is ine0ient if there re lots of songsF sf you know tht there re going to e ertin vlues tht people serh for oftenD you ould use wp to mke those opertions fstF en exmple of this would e to keep trk of the songs y prtiulr rtistF ou ould store ll the songs in fu'erongF roweverD to mke it fst to (nd ny given rtistD you ould keep wptringDfu'erong tht uses the rtist nme s the key nd keeps fu'er of ll the songs tht rtist hs sung s the vlueF ou shouldn9t hve to hnge the funE tionlity of the si qs for thisF imply lter how it stores nd esses vluesF PF his is ontinution of projet IPFS on turtle grphis to drw frtl shpes generted with vEsystemsF ou n (nd full desription of vE systems in he elgorithmi feuty of lntsD whih n e found for online t httpXGGlgorithmiotnyForgGppersG5opF he (rst hpter hs ll the mteril tht will e used for this projet nd lter oneF sn the lst projet you mde it so tht you ould use turtle to drw (gures from strings using the hrters 9p9D 9f9D 9C9D nd 9E9F vEsystems re forml grmmrs tht we will use to generte strings tht hve interE esting turtle representtionsF en vEsystem is de(ned y n initil string nd set of produtionsF ih prodution mps hrter to stringF o the prodution p Eb pEpCCpEp will use ny p in string to e repled y pEpCCpEpF he wy vEsystems work is tht ll produtions re pplied t the sme time to ll hrtersF ghrters tht don9t hve produtions just sty themselvesF o with this exmple you might strt with pF efter one itertion you would hve pEpCCpEpF efter the seond itertion you would hve pEpCCpEpEpE pCCpEpCCpEpCCpEpEpEpCCpEpF he next itertion will e out (ve times longer thn thtF he string in n vEsystem grow exponentilly in

CHAPTER 15.

SETS, MAPS, AND BUFFERS

QRU

lengthF es resultD you proly wnt to hve the length of the move for n p or f get exponentilly shorterF trt with good vlue nd divide y n pproprite vlue for eh genertionF por this exmple dividing y ftor of Q is idelF his one lso works est with turn ngle of TH degreesF he produtions for n vEsystem re niely implemented s wpghrDtringF gomine tht with )twp to run through genertions of your stringF ou n deide how elorte you wnt your qs to e nd if users should e le to enter produtions or if they will e hrd odedF vook in he elgorithmi feuty of lntsD ghpter I for exmples of other interesting prodution rulesF QF his projet is ontinution of projet IQFP on the fesg progrmming lngugeF sn tht projet you will simply use wp to store vrile vluesF e wptringDhoule will work niely s n e0ient wy to store nd lookEup vrilesF he rest of the funtionlity for the projet n remin the smeF RF e stndrd exmple of wp is telephone ookF he key is the nmeF he vlue would e se lss with telephone numerD ddressD etF ou should mke qs to disply the telephone ook nd store the dt in n wv (leF por the (rst ut you n mke it so tht there n only e one person with given nme nd use wptringDersonF sf you wnt it of hllengeD mke it so tht there n e mutliple people with the sme nmeF por tht you ould use wptringDfu'erersonF SF sf you hve een working on the grphis nd ry tring projets preE viouslyD for this projet you n lter you progrm to use fu'er @or twoA to store geometryF ut this into the qs you wrote for projet IIFR nd keep whtever the most reent sving nd loding options reF elso hnge your rendering ode to work with fu'erF

Chapter 16

Recursion
fk in hpter T we got our (rst introdution to reursionF et tht point we used reursion to provide itertionF sn hpter V we lerned how to produe itertion using loops nd hve used tht more thn reursion sine tht pointF sf the only pility of reursion ws to produe itertion it wouldn9t e of muh interest in gomputer iene euse loops would e omplete sustitute tht would hve simpler syntx for most usesF roweverD tht isn9t the seF eursion llows us to express lot more thn just simple itertionD nd euse of thisD reursion is ritil tool in writing onise solutions to mny di'erent prolemsF

16.1 Power of Recursion


o understnd the rel power of reursion nd where it omes fromD it might help to revisit some ode from the end of hpter TF irly in tht hpter we used reursive funtion to ount down from spei(ed numer using single rgumentF he ode for doing tht looked liker thisF

def countDown(n:Int) { if(n>=0) { println(n) countDown(n-1) } }


es long s the rgument hsn9t gotten elow zeroD this funtion prints the numer nd ounts downF e lso wrote ode to ount up using two rguments where one rgument ws inremented for eh susequent llF et the end of the hpter you were presented with the following odeF

def count(n:Int) { if(n>=0) {


QRV

CHAPTER 16.

RECURSION

QRW

count(n-1) println(n)

ou were told to enter this ode nd run it to see wht it doesF sf you did soD you might hve een rther surprised to see tht this ode ounts upF ht seems surprising euse the rgument is lerly derementingF he reson this n ount up hs to do with the memory of the omputer nd in prtiulr the ll stk whih ws introdued in setion IQFTF o understnd how this worksD onsider (gure ITFIF his shows grphil representtion for di'erent frmes on the ll stk nd wht hppens when you ll ount@SAF his ll immeditely lls ount@RA efore doing nything elseF he ll to ount@RA gets new stk frme tht keeps trk of where it ws in the ll to ount@SA so tht when it returns it n go k to tht pointF he ll to ount@RA lso does nothing ut ll ount@QAD whih lso gets new stk frmeF his ontinues until we get down to ount@HA whih does nothing t llD ut returnF hen it returnsD ontrol returns to the ll to ount@IA nd resumes right fter the ll to ount@HAD whih is the line with the print sttementF o it prints IF efter the print ount@IA returns to ount@PA whih similrly does printF feuse the prints re hppening s it pops k up the stkD the numer get printed in sending order even though the funtion only inludes derementF he memory of the stkk is essentil for this to work euse eh stk frme rememers its own vlue of nF his is very signi(nt point to rememer out reursive llsF hile the vriles in the reursive lls ll hve the sme nmesD they ren9t the sme vrilesF st is like multiple people with the sme nmeF tust euse two or three people re nmed tD tht doesn9t men they re the sme personF sn this seD there were six di'erent versions of n tht were reted nd they took on the vlues from S down to HF ih ws distint from the others nd oupied di'erent prts of memoryF his exmple shows how the stk n ome into ply with reursionD ut it doesn9t relly show the power of reursionF o do thtD we need to hve reursive funtion tht n ll itself more thn oneF sn the following setions we will look t severl di'erent exmples of this nd see prolems tht relly require the stk nd re signi(ntly hrder to onvert over to using loopsF

16.2 Fibonacci Numbers


he lssi exmple of reursion is the pioni numersF his is sequene of numers where eh numer is de(ned s the sum of the previous twoF o in mthemtil nottion this is written s f (n) = f (n 1) + f (n 2)F his isn9t omplete de(nitionD howeverD euse we need to know how the sequene strtsF ht is to sy tht we need se se for the reursionF st is ustomry to hve the (rst two elements e IF o the sequene then is ID ID PD QD SD VD IQD PID FFF

CHAPTER 16.

RECURSION

QSH

Call Stack
count(5) count(4) count(3) count(2) count(1) count(0)
println(5)

println(4)

println(3) println(2)

println(1)

pigure ITFIX his shows the ll stk for the funtion ount whih prints the numers ounting upF hen you ll the funtion with SD it lls itself with R without doing nything elseF his lls itself with Q nd so on down to HF he ll with H does nothing ut returnF st returns k into the ll to ount@IA tht does the print nd ontinues on k up the stkF

CHAPTER 16.

RECURSION

QSI

e n write this funtion in l with one short funtion de(nitionF

def fib(n:Int):Int = if(n<3) 1 else fib(n-1)+fib(n-2)


o for naI nd naP we get k IF por naQ we get k ICIaPF por lrger numersD the proess is more omplex nd it is instrutive to try to visulize itF e do this y onsidering wht hppens on the ll stk in mnner similr to (gure ITFIF nlike the ode for (gure ITFID this funtion lls itself twie nd tht mkes things it more omplexF por exmpleD onsider ll to (@RAF his is equl to (@QAC(@PAF sn order to know wht tht isD reursive lls hve to e mde to eh of those funtionsF fy onventionD we will imgine tht the lls re proessed from left to rightF o it lls (@QA whih gets stk frmeF ht in turn lls (@PA whih gets stk frmeF nlike exmples we hve seen eforeD when (@PA returnsD there is nother ll to (@IA still witingF o immeditely new stk frme ppers where the one for (@PA hd just eenF his proess of stk frmes returning to e repled with new one hppens lot in this lultion of the pioni numers s well s other reursive funtions tht ll themselves more thn oneF snsted of drwing this s vertil stk s ws done in (gure ITFID it is ustomry to drw it in rnhing struture lled tree s is drwn in (gure ITFPF ih new stk frme is still elow the one tht lled itD ut di'erent stk frmes t the sme depth in the stk re drwn next to one nother horizontllyF errows re used to keep trk of thingsF sn this representtionD oxes represent the stk frmesF e hve dispensed with putting the funtion nmes nd left only the rgument vlueF he stright rrows show funtion llsF he urved rrows show returns nd re leled with return vluesF hese types of digrms n e very helpful to you when you re trying to (gure out wht hppens in omplex reursive funtionF hen you drw them yourself you n dispense with the oxes nd rrowsF lues with lines etween them will typilly su0eF he pioni numers re stndrd exmple of reursionD ut they ren9t gret one outside of instrutionl purposesF ou n firly esily write funtion tht lultes pioni numers tht uses loop insted of reursion nd it will e lot fsterF ht isn9t true of the exmples tht followF

16.3 Permutations
his next exmple is it more prtilF e re given list of vlues nd we wnt to perform some funtion on ll permuttions of this listF e permuttion of olletion ontins ll the sme elementsD ut in potentilly di'erent ordersF his type of ehvior might e in order if you hve di'erent tsks nd you need to (nd n optiml order in whih to perform the tsks sed on some ruleF o the next question isD how ould we do thisc o (gure this out we will employ ommon idiom when uilding reursive funtionsF st is one tht we tlked out in hpter T with our simpler reursive funtionsF he ide is to tke lrge prolem nd rek it down so tht we solve one step nd then pply

CHAPTER 16.

RECURSION

QSP

Call Source
3

4
1 2

3
1

pigure ITFPX his (gure shows ll tree for (@RAF foxes represent stk frmesF tright rrows point in the diretion of funtion llsF gurved rrows show returns nd re leled with return vluesF the sme funtion to solve wht is leftF sn this seD one step is piking (rst elementF nlike wht we did in hpter TD there will generlly e more thn one option hereF eny of the elements in the urrent list ould e the (rst element in the permuttionF ht follows tht is the permuttions of everything else in the listF ht gives us reursive de(nitionF e wnt to pik n element to go (rstD then mke reursive ll on the restF efter tht returnsD we pik di'erent element to go (rst nd reurse ginF his should e repeted for ll the elements in the listF o onvert this into funtion we need to (gure out wht informtion hs to e pssed inF he ovious prt is tht we hve to pss in the list of vlues we re permutingF e lso need to pss in the elements in the permuttion tht hs een uilt so frF his n e done s seond listF sf we mde the funtion suh tht it returns list of lists with ll the permuttionsD these would e the only rguments we would needF roweverD suh funtion isn9t useful for mny situtions euse the numer of permuttions grows very quikly with list length nd the ost in memory would eome prohiitiveF snstedD we will pss in funtion tht opertes on list tht we will ll eh time omplete permuttion is uiltF ht wy the ller n deide wht is done with the di'erent permuttionsF o we re writing funtion tht tkes three rgumentsD the list of numers we wnt to permuteD funtion to pply to ny (nished permuttionsD nd the urrent list for this permuttionF his is done in the following odeF

CHAPTER 16.

RECURSION

QSQ

def permute(nums:List[Int],f:(List[Int])=>Unit,p:List[Int]) { if(nums.isEmpty) { f(p) } else { var before=List[Int]() var after=nums while(!after.isEmpty) { val perm = after.head :: p permute(before ::: after.tail,f,perm) before ::= after.head after = after.tail } } }
hen the list is emptyD we hve gotten full permuttion nd we ll the funtion on itF ytherwise we hve loop tht runs through ll the elements we wnt to permute nd mkes reursive lls ssuming eh one hs een dded to the hed of the permuttionF his is done using two vrile lists nd while loopF o strt o' withD one list is empty nd the other is ll the elements in the listF sn the list we not only mke the reursive llD we lso move elements from one list to the otherF e n hek to see tht this funtion works y lling it like thisF

permute(List(1,2,3),println,Nil)
e re getting the six di'erent permuttions of list with three elements nd simply printing themF he (rst ll should lwys use xil for the lst rgumentF his funtion displys n interesting feture tht is generlly true of reursive funtionsF feuse it is de(ned in terms of itselfD we write it ssuming tht it worksF hen we re done writing itD it will workF his logi seems irulrD ut it is tully using method lled indutionF he mke the funtion work for the simple se seF ivery se ove tht is de(ned in terms of smller oneF iventully this gets down to the se se whih generlly works in trivil wyF sf the se se worksD the se right ove it should workF hen the one ove the se se worksD the one ove tht hsould workF his logi progresses upwrd to llow us to solve prolems of ritrry sizeF e mentioned erlier tht we don9t return list of the permuttions euse there n e lot of them nd tht would require lot of memoryF st is worth tking seond to get slightly etter understnding of wht  lot mens hereF pei(llyD we9d like to know the order of the numer of permuttionsF his will not only tell us how long list would e if we uilt oneD it will give us mesure of how long this funtion will tke to run for ny tsk tht we might give it s it will e the numer of times tht the funtion prmeterD fD gets lledF

CHAPTER 16.

RECURSION

QSR

es is normlly the se for order nlysisD we will think of things in terms of the size of our inputF sn this seD tht is the size of the input list whih we will ll nF he (rst ll to permute mkes n lls to itselfD eh of whih is pssed list with nEI elementsF hose them mke nEI lls with lists of size nEPF his proess ontinues until we get down to H elements in the listF sf you piture this s tree similr to tht in (gure ITFPD we hve top ox with n rnhes o' itF hose led to n oxes tht eh hve nEI rnhes o' of themF o t the third level we hve nB@nEIA oxesF et the next level we hve nB@nEIAB@nEPAF sn you ontinue this down to I we get the ftoril funtion tht we plyed with wy k in hpter TF sndeedD the order of the permuttion funtion is y@n3AF sf you rell from our erlier disussionD the ftoril funtion grows very quiklyF o quikly in ftD tht we hd to use the vong or figsnt types if we wnted to use even modestly lrge inputsF glerly you don9t wnt to try to get ll the permuttions of lists with muh more thn IH elements in themF hepending on wht you re doingD even lists of IH elements might tke whileF

16.4 Towers of Hanoi


yur next exmple of these more powerful reursive funtions is it more plyfulF 333

16.5 Mazes
enother lss of prolems tht lls for reursion is those involving mzesF his might lso seem to e more for reretionD ut mzes re simpli(ed se of something lled grphs whih re very importnt in omputer siene nd re used to represent ll types of di'erent prolemsF he sme pprohes tht we will use here for mzes pply to grphs s wellF here re lso numer of pplitions where doing things like (nding the optiml route through some type of restrited pth like mze is signi(ntF o keep things simpleD we re going to use rther si pproh to uilding our mzesF snsted of hving grid with wlls etween ellsD we will hve grid where omplete squres n either e open or e oupied y wllF his representtion mens tht we n use PEh rry of vlues tht tell us if there is wll or notF sn theory we ould use n erryerryfoolen for this purposeD ut in prtie we will hve use of eing le to put numeri vlues in the rooms so n erryerrysnt will e more prtilF e will de(ne the mze with ode like the followingF

val maze=Array(Array( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), Array(-1,-1,-1, 0,-1,-1,-1,-1,-1,-1), Array( 0, 0, 0, 0,-1, 0, 0, 0,-1, 0), Array( 0,-1, 0,-1,-1,-1,-1, 0, 0, 0), Array( 0,-1, 0,-1, 0, 0,-1,-1,-1, 0),

CHAPTER 16.

RECURSION

QSS

Array( Array( Array( Array( Array(

0,-1,-1,-1,-1, 0,-1, 0, 0,-1, 0, 0, 0,-1,-1, 0,-1, 0,-1,-1, 0,-1, 0, 0, 0,

0, 0, 0, 0, 0), 0,-1,-1,-1, 0), 0,-1, 0, 0, 0), 0,-1, 0,-1,-1), 0,-1, 0, 0, 0))

his uilds PEh rry of snts tht uses H to represent n open squre nd EI to represent wllF he use of EI for wll is intentionl so tht positive numers n e used to represent other things lterF his prtiulr mze is only IHxIH in sizeF his is good size to strt o' with for our purposes though it doesn9t llow for very omplex mzeF yur (rst tsk is the thing tht most people would proly wnt to do with mzeF e wnt to know how to get through it in the shortest numer of stepsF o strt withD we will sk the simple question of how mny steps long is the shortest pthF his hs signi(nt dvntge over trying to tully return pthF xot only is it simple numeri vlueD it is lso uniqueF here n e multiple pths ll with the sme length tht produe miquity if we sk for the optiml pthF st lso hppens tht hving funtion to (nd the length of the shortest pth is su0ient s multiple lls to this funtion n e used to onstrut the optiml pth even though suh onstrution is less thn optimlF ou n write funtion to (nd the length of the shortest pth using loopsD ut it is firly omplex odeF e n write simpler solution using reursionF es with ll reursive funtions we n rek the solution down into two rod prtsD se ses nd reursive sesF he se ses should e trivil to solveF here re two good se ses for the mze prolemF yne se se is when you reh the exitF sf you re t the exit it tkes zero steps to get outF enother se se is if you re heking lotion whih is out of the mze or in wllF por tht we wnt to return vlue tht ouldn9t possily e solutionF e9ll ome k to tht fter disussing the reursive sesF iture yourself stnding t lotion somewhere in the mze nd you wnt to know how mny steps it tkes to get from your urrent lotion to the exit on the shortest pthF he reursive wy to do this is to imgine tht you hd funtion tht ould tell you tht nswer from ny of the neighoring squres nd (gure out how you would omine those vlues to determine the distne from where you reF es we sid oveD we write reursive funtion y ssuming we hve one tht works nd writing sed on tht ssumptionF yne we re doneD ssuming we hve hndled the ses properlyD it will workF sf you re in the mze nd you hve n instrument tht n tell you how mny steps it tkes to get out from one step to the northD southD estD nd westD how would you use tht informtion to detemine the shortest distne from where you rec o mke this more onreteD piture yourself t four wy intersetionF ou im your instrument in eh diretion nd get vlues of UD IQD RD nd IWF o the shortest pth lies in the diretion tht gve you k RF roweverD tht ws the distne from one step in tht diretionF he minimum distne from where you re then is S stepsF st is the minimum of the four plus to one step to get to the

CHAPTER 16.

RECURSION

QST

proper other lotionF he solution of tking the minimum lso points us in the proper diretion for the se se of hitting wll or going out of oundsF sf the nest solution is the minimumD we should return numer tht n9t possily e the minimum for d pthF e lrge numer suh s one illion will su0e for virtully ny mzeF ou might e tempted to use sntFwxlueD ut rememer tht we re dding I to itF ry doing sntFwxlueCI nd you will see why tht isn9t n idel hoieF ht de(nes our reursive seF here is only one other ftor tht needs to e onsideredF sf you hve ever een in hedge mze or some other mze where you n9t see over the wllsD it n e quite di0ult to tell one lotion from nother nd unless you do something to mrk your previous lotions you n wind up running in irles nd never (nding your wy outF e rther fmous solution to this prolem ws desried y this prolem y the frothers qrimm in rnsel nd qretel who left redrums to mrk their pthF e will hoose the sme pprohF essuming you hve no irds in your omputer this should work etter for you thn it did for the hildrenF sf you do hve irds in your omputerD you should proly del with tht efore reding onF o the lst fet tht we need for our lgorithm is the ility to drop down redrums to mrk our pthF sf we ever ome k upon our redrums we will tret it just like eing in wll or out of oundsF e will lso sweep up our redrums efore we return from pthF his wsn9t required y rnsel nd qretel who simply wnted to e le to (nd their pthF eD howeverD wnt to (nd n optiml pth nd leving redrums ll over the ple would often use us to miss suh pthF gonverting this ll to ode produes the followingF

def shortestPath(maze:Array[Array[Int]],x:Int,y:Int,endX:Int,endY:Int):Int = { if(x<0 || y<0 || y>=maze.length || x>=maze(y).length || maze(y)(x)!=0) { 1000000000 } else if(x==endX && y==endY) { 0 } else { maze(y)(x)=1 val dist=(shortestPath(maze,x+1,y,endX,endY) min shortestPath(maze,x-1,y,endX,endY) min shortestPath(maze,x,y+1,endX,endY) min shortestPath(maze,x,y-1,endX,endY)) + 1 maze(y)(x)=0 dist } }
he whole funtion is uilt from if expressionsF he (rst option is for going out of oundsD hitting wllD or oming ross one of our redrums nd it returns one illionD numer so lrge it n9t possily e vlis pthD ut one smll enough tht we lso won9t over)ow it y dding I for other steps through

CHAPTER 16.

RECURSION

QSU

the mzeF he seond se is where we hve rehed the endF hese two n e reversed nd would need to e if the exit were outside of the ounds or mrked y speil vlue in the rryF he lst se it the reursive se whih drops redrumD mkes four reursive lls nd omines them with minD then piks up the redrum nd returnsF his ode ould e invoked with this llF

println(shortestPath(maze,0,0,9,9))
por the mze shown oveD the return vlue from this ll is QTF por this prtiulr mzeD tht is the length of the only pth from HDH to WDWF ou should ply with the mze some to mke sure tht the funtion (nds the shortest pth for other on(gurtionsF his funtion literlly tests every single pth through the mze nd gives us k the shortestF here re strengths nd weknesses to this pprohF he wekness is tht if there re lot of pths this ould tke whileF e9ll explore tht more in the next two susetionsF he strength is tht it tkes only very minor modi(tions of this ode to produe other similr funtions suh s one to (nd the longest pth or to ount up how mny pths there reF hese prtiulr prolems re left s exerises for the studentD ut we9ll tell you now tht the only rel hnges re to lter the return vlues of the se ses nd the wy in whih the reursive lls re ominedF

16.6 Sorts
sn hpter IQ we used loops to provide ll of our itertionF e ould hve used reursion instedF sn ftD some of the sorts re expressed very niely s reursive sortsF gonsider mxsortF he two loops would e written s two reursive funtions nd one n e nested inside of the otherF he inner one (nds the index of the mximum vlue efore some lotionF his is nested in funtion tht runs k through the rry (nding the mx nd swpping it into ple efore moving k one spotF he ode for doing this looks like the followingF

def maxIndex(a:Array[Double],end:Int):Int = if(end==0) 0 else { val m=maxIndex(a,end-1) if(a(m) > a(end)) m else end } def maxSort(a:Array[Double],end:Int=a.length-1) { if(end>0) { val index=maxIndex(a,end) if(index!=end) { val tmp=a(index) a(index)=a(end) a(end)=tmp }

CHAPTER 16.

RECURSION

QSV

maxSort(a,end-1)

his is it longer thn the version tht uses loopD ut not y ll tht muhF sing the defult vlue on the seond rgument to mxort llows us to ll it with only one rgument if we wnt to sort the entire rryF erhps n even etter exmple is the insertion sortF he inner loop of the insertion sort is doing n insert so we write reursive insert funtionF his gets lled y n outer funtion tht does the sort nd simply wlks down the rry putting eh element in pleF

def insert(a:Array[Double],v:Double,i:Int) { if(i<=0 || v>=a(i-1)) a(i)=v else { a(i)=a(i-1) insert(a,v,i-1) } } def insertionSort(a:Array[Double],i:Int=1) { if(i<a.length) { insert(a,a(i),i) insertionSort(a,i+1) } }
he insertion sort is quite nie nd net s reursive funtionF he ft tht it doesn9t hve full swp helps with thtF por the mx sort nd the insertion sortD the use of reursion is only hnge in presenttionF st doesn9t relly lter how they run or how e0ient they reF he reusrion in these funtions is only used for itertionD nothing moreF rowE everD reursion lso opens the door to some more e0ient sortsF he next two susetions desrie two of theseF

16.6.1 Quick Sort


333 hort versions not inEple 333 inEple version 333 hoes the work going down the ll stkD nothing done oming k upF

16.6.2 Merge Sort


333 gn9t e done in pleF 333 orks well with listsF 333 eursive merge n fil on long rrys so use while loopF 333 hoes most of the work oming k up the stkF

CHAPTER 16.

RECURSION

QSW

16.7 Scheme Interpreter


Self-Directed Study
inter the following sttements into the iv nd see wht they doF ome will produe errorsF ou should try to (gure out whyF ry some vritions to mke sure you understnd wht is going onF

scala> def succ(n:Int):Int = n+1 scala> succ(1)


333

Exercises
IF ixerise PF rite funtion tht lultes pioni numers using loopF QF vongest pth through mzeF RF gount pths through mzeF

Projects
IF sf you hve een doing the ryEtring nd grphis optionsD this projet ontinues with thtF y trers n implement oth re)etions nd trnsE preny using reursionF sf you hve funtion tht tells you wht olor to drw for prtiulr ryD you n do re)etion y reursively lling tht funtion with the re)eted ry nd omining tht olor with the olor of the surfe tht is re)etingF row muh of eh goes into the olor depends on the frtionl re)etivity of the ojetF por this projet you will give your ojets olorsD ut you still won9t worry out lightingF o when ry hit n ojetD it gets the full olor of tht ojet unless the ojet is re)etiveF sf it hs re)etivity then it gets @IEA of the olor of tht ojet nd of the olor from the re)eted ryF o dd olors you need to e le to uild your own olors nd get the omponents out of olorsF he jvFwtFgolor lss hs methods lled getedD getqreenD nd getflue tht return the mount of eh primry in olorF he vlues re snts in the rnge of HEPSS inlusiveF ou n lso mke new golor ojet e lling new golor@redXsntDgreenXsntDlueXsntAF he vlues pssed in must e in the sme rnge or you will get n errorF o lulte re)etionD you need the unitEnorml vetor for the surfe you re re)eting o' ofF por plne this is esy s the norml is the sme everywhereF por sphereD this is the vetor from the enter to the point

CHAPTER 16.

RECURSION

QTH

of intersetionF sn oth sesD you wnt it normlizedF sf you hve thtD the diretion of the re)eted ry is given y

r ref lected = r 2 ( r n) n D where r is the diretion of the inoming ry nd n is the unit normlF he unit norml will lso e signi(nt for lulting lighting in lter projetF
PF por this projet you will write progrm tht solves WxW udoku puzzlesF st will do this through reursive funtionF he input will e W lines of textD eh with W hrters on itF he hrE ters will either e spe or single digit numerF ou should output ord with ll the lnks (lled in nd put spes etween the numers to keep it redleF st turns out tht most puzzles hve more thn one solutionF ou only need to provide oneF por n extr hllengeD mke it so your progrm hs qsF st should lod puzzles from (le nd use le or qridnel to disply the puzE zleF sers should e le to selet solve option to hve other spes (lled inF QF por this projetD you will write progrm tht reursively prses string for n rithmeti expression nd returns the vlue of itF ixmples would e SCU or WB@SCUFSAGPF our prser should do proper order of opertions @things in prentheses ind highestD B nd G efore C nd ED nd go from left to right for the sme level of priorityAF he pproh s wnt you to tke for solving this prolem is with reursive lgorithm tht reks the prolem into piees strting with the lowest priE ority opertionF ou will write funtion prse@expXtringAXhouleF his funtion will return the vlue of the expression in the string expF pirst it should (nd the lowest priority opertor @it n9t e in prenthesesAF sf it (nds one it reurses twie with the sustrings on either side of tht opertor @use the sustring method of tring or tke nd dropAF sf there isn9t n opertor tht isn9t in pretheses you n hek if the string strts with 9@9 nd pull the ounding prentheses o' nd reurse on wht is leftF sf it doesn9t strt with 9@9 you know tht prt of the expression is just numer so use tohoule to get the vlueF he user will give you formulD tht doesn9t inlude ny spesD t the ommnd line nd you should simply print the vlue it evlutes toF o potentil invotion of your progrm might e s followsX 4sl prserFsl SCQB@UHGSA4F RF sf you did the vEsystem projet in hpter ISD you n extend it in this projetF sf you go further into hpter I from he elgorithmi feuty

CHAPTER 16.

RECURSION

QTI

of lntsD you will (nd tht you n use vEsystems to model grsses nd treesF e won9t do the QEh implementtionD ut you n dd hndling for 99 nd 99 to llow rnhing struturesF his is est done using reursive lls tht strt on 99 nd return on 99F snsted of pssing in tringD pss in the stertorghr tht you get y lling the itertor method on tringF he dvntge of the stertor is tht the elements re onsumed when you ll next so tht when you return from funtion llD the ode will utomtilly e working on wht remins fter the 99F

Part II

Object-Orientation, Abstraction, and Data Structures

QTP

Chapter 17

Object-Orientation
prom the eginning we hve sid tht l is ompletely ojetEoriented lngugeF ou hve een using ojets nd lling methods on them sine k in hpter Q when we were tking our (rst steps in the lngugeF hespite thisD we hve tully done very little with ojetEorienttionF his hs een intentionlF o fr we hve een uilding up your logi skills nd tehing you to rek prolems up into di'erent funtionl unitsF xow tht your prolem solving skills hve rehed su0ient level we will tke the next step to hve you doing full ojetEoriented deomposition of prolemsF feginning with this hpter we will lso strt relly reveling mny of the detils ehind things tht we hve een using ll longF

17.1 Basics of Object-Orientation


he si ide of n ojet is tht it is something tht ontins oth dt nd the funtionlity tht opertes on tht dtF e grouped dt originlly with tuples nd then in hpter IH we strted using se lsses to group dt together in more meningful wyF ht we didn9t do with either of these ws to ind ny funtionlity to them diretlyF e wrote funtions tht ould operte on themD ut it ws independent of the dt itselfF sn the se of tuplesD we n9t ind the funtionlity into ojetsF gse lsses do llow us to do thisD we simply didn9tF sn this hpter we will lern how to do proper ojetEoriented progrmming in lF his is the model tht we will use through the rest of the ook s wellF l is lss sed ojetEoriented progrmming lngugeF ht mens tht progrmmers rete lsses in their progrms nd those lsses de(ne types tht re used to mke ojetsF e lredy sw how the se lsses tht we mde de(ned new typesF e didn9t put nything in them though exept some dt elements tht we wnted ny funtion to e le to essF he se keyword in front of se lss worked well for our needs in hpter IHD ut it isn9t required to de(ne typeF e will e writing norml lsses now QTQ

CHAPTER 17.

OBJECT-ORIENTATION

QTR

nd only using se lsses when they re lled forF he wy tht you should think of lss is s lueprint for n ojetF he lss tells l wht goes into the ojets of tht type nd wht type of funtionlity those ojets should hveF he syntx for lss is s followsF

class TypeName(arg1:Type1, arg2:Type2, ...) { // Methods and Additional Members }


es you n seeD the only things tht re di'erent etween this nd the se lsses we hve lredy worked with is the lk of the keyword se nd the urly res with stu' in them fter the lssF hese urly resD like ll urly res in lD de(ne new sopeF his sope is ssoited with the lss nd nything you wnt to put in the lss goes inside of themF here should e nothing too surprising out thtF 333 enpsultion 333 seprtion of interfe nd implementtion

17.1.1 Methods and Members


snside of the lss you n write ode extly the wy you hve nyple elseF here re smll di'erenes tht will e disussed nd the mening nd termiE nology hnges itF hen you write vrile delrtion inside the ody of lssD tht is now memer delrtionF st is dt tht is stored in the ojets reted from tht lssF hen you use def to rete funtionD we ll it method euse of its sope in the lss nd the ft tht it is something tht you will e le to ll on ojets reted from this lssF eny sttements tht you write tht ren9t delrtions of memers @vl or vrA or methods @defA will simply e run when n ojet of this type is instntitedF o see how this worksD we9ll write little sript tht inludes lss delE rtionF por the lss we will go k to the onept of grdes in ourse nd write the lss to represent studentF rere is (rst drft of the lss with one import sttement nd some lines tht use the lssF

import scala.collection.mutable class Student(name:String,id:String) { val tests=mutable.Buffer[Double]() val quizzes=mutable.Buffer[Double]() val assignments=mutable.Buffer[Double]() def testAverage = tests.sum/tests.size def quizAverage = quizzes.sum/quizzes.size def assignmentAverage = assignments.sum/assignments.size } val john=new Student("John Doe","0123456") john.tests += 78 += 85 println(john.testAverage)

CHAPTER 17.

OBJECT-ORIENTATION

QTS

he lss egins with lss delrtion tht looks lot like se lss nd relly isn9t too di'erent from defF efter the keyword lss is the nme of the typeD in this se tudentF his is followed y list of prmeters to the lssF sn this se we hve two strings lled nme nd idF he ody of the lss is denoted with urly res nd inside of the urly res we hve three memer vrile delrtions for grdes nd three method delrtions for tking vergesF wore will need to e ddedD ut we need to explore wht this relly mens efore we n do thtF efter the lss delrtion re three lines of odeF he (rst delres vrile lled john tht is set to e new student with the nme tohn hoe nd student numer of HIPQRSTF he seond sttement dds two test grdes of UV nd VS to this studentF he grdes re eing kept in u'ers so tht they n esily hnge size s grdes re editedF hile this is simpleD it isn9t ler tht we relly wnt the grdes to e this essileF e9ll tlk more out tht lterF he lst sttement in the sript prints the verge for the tests y lling the testeverge methodF

17.1.1.1 Arguments as Members


iverything in this exmple should seem firly strightforwrdF st relly doesn9t look muh di'erent from things tht we hve done eforeF his would hnge though if we try to mke the print sttement it more informtiveF

println(john.name+" has a "+john.testAverage+" test average.")


sf you hnge the println to this nd run the sript you will get n error messge tht might not mke muh sense to youF

ScalaBook/ch17.scala:15: error: value name is not a member of this.Student println(john.name+" has a "+john.testAverage+" test average.") ^ one error found
ou should de(nitely (nd this surprisingF his would hve worked for se lssF sndeedD if you put the se keyword t the eginning of the lss delrE tion this works (neF st is worth exploring why it doesn9t work without the se keyword nd how we n (x itF he error messge tells us tht nme is not memer of tudentF his is euseD y defult the rguments pssed into lss re not turned into memersF his is euse memers hve to e stored y eh instne of the lss tht is reted so extr memers onsume memoryF iven if they do hve to e rememeredD they won9t e visile to ny ode outside of the lssF por exmpleD if you dd the following method into the lss you n ll it to get the lst nmeD ut you still n9t get the nme itselfF

def lastName = name.split(" +").last

CHAPTER 17.

OBJECT-ORIENTATION

QTT

sf you wnt n rgument to e memer simply put vl or vr efore the nmeF st will then eome memer with the proper ehvior for either vl or vrF por our tudent lss we likely wnt oth to e onstnt so we should hnge the lss delrtion to the followingF

class Student(val name:String,val id:String) {


sf you mke this hnge you n use the print sttement shown oveF

17.1.1.2 Visibility
he possiility of things eing visile or not is pretty muh new to usD ut it is very importnt spet of ojetEoriented progrmming euse it llows you to hide detils of the wy n ojet works wy from the ode tht uses the lssF he vlue of this is tht you n hnge those detils without using prolems for the ode tht depends on the lss to workF sn the se of memer dtD you n lso hide wy detils tht you don9t wnt other prts of ode to hve free ess toF e gret demonstrtion of this lst prt omes in the form of nk ountF vet9s onsider the simplest possile lss tht we might write to represent nk ountF

class Account { var balance=0 }


his lss doesn9t tke ny rguments when it is onstruted nd s resultD the prentheses hve een left o'F st hs one piee of memer dtD n snt for the lneF es you might rell from hpter QD money should e stored in snts euse the rithmeti of the houle type is inurte due to the limited preisionF his representtion is simpleD ut it hs signi(nt drwkF he memer lne is vr tht n e set y ny ode tht gets hold of n eount ojetF por rel nk progrm tht would not e eptleF he lne n9t just e ny vlueF por exmpleD negtive numers generlly ren9t llowedF sn dditionD hnges to the lne re typilly supposed to hppen in spei( opertionD deposits nd withdrwsF hose opertions n enfore ertin rules ndD for rel nkD would log ny hnges to the lne so tht it is possile to go k nd (gure out wht hppenedF hile we ould mke funtions for those opertionsD there would e nothing tht fores progrmmers to use themF st would e possile for progrmmer to get lzy t some point nd ess the lne diretlyF he results of this in nking softwre ould e quite extremeF he ility to fore ess to dt to our through ertin methods is one of the most signi(nt pilities of ojetEorienttion s wy of improving softwre onstrution nd ontrolling omplexityF he rel ene(t of this E pility is to tke responsiility for proper usge wy from the users of the ojetsF sf the only wys to use the ojet re through methods or dt tht is sfe for them to useD then they know they n9t mess it up nd don9t hve to

CHAPTER 17.

OBJECT-ORIENTATION

QTU

worry out thtF snstedD they n fous on the logi tht they re working onF o how do we omplish this in our lssesc e do it y setting the visiility of memersF here re three min levels of visiility in l nd they re very similr to wht you will (nd in other lss sed ojetEoriented lngugesF

uli E his mens tht something n e essed y ny ode inside of outside of the lssF sn l this is the defult visiility for elements so there is no keyword for itF rivte E his mens tht the memer n only e essed inside the lss1 F ettempts to get to the memer outside of the lss will result in syntx errorF sf you pre(x delrtion in lss with the privte keywordD tht memer will e privteF roteted E his is like privte exept tht proteted memers re lso visile in sutypesF his will e disussed in detil in setion PHFPFIF
sn our exmple eount we relly wnt the lne to e privteF e n do this y simply dding it efore the vrF

class Account { private var balance = 0 }


nfortuntelyD this leves us with lss tht is ompletely uselessF fefore mking this hnge we ould hve done something like the followingF

val myAccount=new Account println(myAccount.balance) myAccount.balance += 100 println(myAccount.balance)


sf we do this now though we get set of error messgesF

/ScalaBook/ch17.scala:24: error: variable balance cannot be accessed in this.Account myAccount.balance += 100 ^ /ScalaBook/ch17.scala:24: error: reassignment to val myAccount.balance += 100 ^ /ScalaBook/ch17.scala:25: error: variable balance cannot be accessed in this.Account println(myAccount.balance) ^ 5 errors found
1 We
will see in section 19.5 that you can expand the range of access to packages.

CHAPTER 17.

OBJECT-ORIENTATION

QTV

xote how the error messge is di'erent thn wht we sw previously for nme on our tudent lssF snsted of telling us tht lne isn9t memerD it tells us tht lne n9t e essedF his is preisely euse the lne is now privte nd the ode is outside of the lssF o mke this lss usefulD we would need to put some methods in it tht re puli tht mnipulte the lne in llowed wyF e9ll strt with methods for deposit nd withdrwF rer is wht the deposity method might look likeF xote tht this is indented euse it ppers inside of the eount lssF

def deposit(amount:Int):Boolean = { if(amount>0) { balance += amount true } else false }


he method tkes the mount to deposity s n sntF st returns foolen to tell us if the deposit went throughF his method doesn9t support logging euse dding tht funtionlity goes deeper thn we wnt to t this pointF st does hek to mke sure tht the mount of the deposit is positiveF sf it isD then tht mount is dded to the lne nd we give k trueD otherwise nothing is done nd we give k flseF e n dd very smilr looking withdrw methodF

def withdraw(amount:Int):Boolean = { if(amount>0 && amount<=balance) { balance -= amount true } else false }
he only di'erene etween deposit nd withdrw is tht you n9t withdrw more money thn nd the mount is sutrted from the lneF he lst thing we need to dd is method to get the lne so tht it n e hekedF his method might look like the followingF

def getBalance = balance


st simply gives k the lne in the ountF his style of lling method the retrieves memer using method tht egins with get is stndrd prtive in tvF por resons tht we will see lterD this is not the reommended style in lF snstedD in l we would use di'erent nme for the privte memer nd use method with the norml nme for getting the vlueF here re di'erent pprohes to how you nme the privte vrF sn this ook we will typilly use shortened version of the wordD in this se lF ou n pik whtever style you wntD ut e onsistent with itF rving mde this hngeD the lss s whole looks like thisF

CHAPTER 17.

OBJECT-ORIENTATION

QTW

class Account { private var bal = 0 def deposit(amount:Int):Boolean = { if(amount>0) { bal += amount true } else false } def withdraw(amount:Int):Boolean = { if(amount>0 && amount<=balance) { bal -= amount true } else false } def balance = bal }
e n utilize this ode y doing the followingF

val myAccount=new Account println(myAccount.balance) myAccount.deposit(100) println(myAccount.balance)


xote tht euse of the use of the nme lneD the println sttements pper the sme wy they did when lne ws puli vrF he di'erene is tht you n9t set lne now unless you go through either the deposit or the withdrw methodF

17.1.2 Special Methods


here re few method nmes tht re speil in lF sn wyD these speil methods re rules tht you hve to lern s speil sesF uh things often weigh upon lngugeF sn this se there ren9t mny of themD nd the power they provide is quite remrkleF

17.1.2.1 Operator Methods


he (rst set of things tht we might onsider speil re opertor methodsF st turns out tht these ren9t relly speil in lF sn relity they re just like ny other methods in lF ou n use ny method ll tht tkes single rgument using opertor syntx s ws disussed k in hpter QF ht mens you n leve out the dot nd the prentheses nd just put the opertor etween the two operndsF ht mkes this more interesting is tht l epts nmes tht hve symols in them nd most lnguges don9tF his inludes nmes for methodsF

CHAPTER 17.

OBJECT-ORIENTATION

QUH

reedene @highest t the topA other speil hrters BG7 CE X a3 `b 8 | ll letters ssignment opertors le IUFIX his tle shows the preedene rules for opertors in lF he preendene is sed on the (rst hrter in the opertorF e hve een using nmes tht ontin only letters nd numers nd egin with letterF ou n lso inlude symoli opertor hrters in ertin wysF ou n hve nmes tht inlude only opertor hrters or you n hve letters nd numersD eginning with letterD followed y n undersore nd opertor hrtersF xote tht one you get to opertor hrters in nmeD ll susequent hrters must e opertors hrtersF o while we hve een using nmes like timeswo or timesPD the nmes BD BBD BCCBD etF re lso ompletely vlidF es with so mny things in lifeD just euse you n use symoli opertor nmes for methods does not men tht you shouldF hey hve their pleD ut if you use them you n led to ode tht is very di0ult to redF es generl ruleD you should only use symoli nmes when they mke senseF ghnging from text nmes tht people n red to ritrry symol sequenes will mke it nerly impossile for you or others to understnd wht is going onF hen you ll method using the norml method nottionD the order in whih things hppen is oviousF his is euse the rgument to the method is found inside of prentheses nd the prentheses determine the orderF hen you use opertor nottionD there hve to e preedene rulesF ou lredy know tht PCQBR is IRD not PHF ht is euse multiplition hppens efore dditionF his is true in l s it is in mthF roweverD the C nd B re simply nmes for methods on snt in this expressionF o how does l deide tht the B should hppen eforeD or hve higher preedene thnD the Cc hen methods re used in opertor nottionD l uses the (rst hrter in the nme to determine preedeneF le IUFI lists the di'erent levels of preedene tht re usedF sn the se of C nd BD the (rst hrter hppens to e the only hrterF he tle tells us tht B hs higher preedene thn C so it is done (rstF sf you put methods lled BCB nd CBC in lssD the BCB would hve higher preedene y virtue of strting with BF sf you lso put method nmed B it would hve lower preedene thn either or the other two euse of the low

CHAPTER 17.

OBJECT-ORIENTATION

QUI

preedene of F hese types of preedene rules exist in most other progrmE ming lnguges s wellF he only di'erene with l is tht you hve the pility of de(ning our own methods tht n e used s opertors nd hve the pproprite preedeneF ht if two opertors re re the sme level of preedenec hih omes (rstc por exmpleD is SEQCP equl to R or Hc sf the E hppens (rst you get RF sf the C hppens (rst you get HF he order in whih opertors of the sme preedene our depends on ssoitivityF ou re used to opertors eing leftE ssoitiveF his mens tht the furthest left opertor of given preedene is done (rstF uh is the se of C nd E nd hene the expression SEQCP is RF roweverD there re some opertions tht should e rightEssoitiveF en 3 exmple of this from stndrd mth is exponentitionF por exmple 33 = 3 3(3 ) = (33 )3 F he numers re grouped from right to left hereD not the norml left to right of other opertionsF en opertor in l is rightEssoitive if it ends with XF sn ddition to eing rightEssoitiveD it is lled on the ojet to the right side of it nd the vlue on the left side is the rgument to the methodF e hve tully seen this ehvior efore with the XX opertorF

3 :: 4 :: lst
his expression only mkes sense if the XX opertor is rightEssoitiveF he XX opertor isn9t de(ned on sntD it is de(ned on vistF o l sees this s the followingF

3 :: (4 :: lst)
his hppens to e the sme s thisF

lst.::(4).::(3)
here re quite few other methods in the es tht work in this wyF e sw some of them in hpter ISF here is one other spet of opertor methods tht is worth disussing efore moving on nd tht is ssignment methodsF e hve seen sttements like nt Ca IF he opertor in this se is n ssignment opertorF st performs n opertion nd does n ssignment ll in one stepF ou re llowed to write methods with nmes like Ca or EaF sf you doD l will use those in expressions like nt Ca IF roweverD if l n9t (nd mth for n opertor tht ends in aD it will try to expnd it outF o if there is no Ca de(ned on the type of ntD then l will try trnslting the nt Ca I into nt a nt C IF sf tht still doesn9t workD you will get syntx errorF he signi(ne of this is tht unless you relly need spei( ehvior from prtiulr ssignment opertorD you don9t hve to write oneF snstedD you will get the ehvior you wnt utomtilly y inluding just the inry opertorF o if you de(ne CD you will normlly get Ca for freeF xote tht this only works for symoli opertorsF here is no ssignment form for norml methods even though you n use them with opertor syntxF

CHAPTER 17.

OBJECT-ORIENTATION

QUP

17.1.2.2 Unary Operators


xot ll opertors tke two rgumentsF ypertors tht tke only single rE gument re lled unry opertorsF ou n write these in l y writing methods tht don9t tke ny rgumentsF eny method you writeD whether it is mde of opertor hrters or norml letters nd numersD n e used s n opertor if pled fter the ojet it is operting onF o see thisD onsider the tosnt method of tringF

scala> "5".toInt res0: Int = 5 scala> "5" toInt res1: Int = 5


he (rst version here uses the norml dot syntxF he seond version leves o' the dot nd simply spei(es tosnt s postE(x opertorF ostE(x simply mens tht the opertor omes fter the rgumentF he inry opertors we onsidered in the lst setion were used inE(xF por some unry opertorsD it is stndrd to use preE(x nottion insted of postE(x nottionF gonsider the E to mke numer negtiveF ith vlue like ES you ould sy it is just prt of the numerF roweverD with E@CUA the role of the E is lerly tht of n opertion tht is performed on the result of CUF he 3 nd ~ methods re other exmples we hve seen for pre(x unry opertorsF yne of the mjor gols in llowing methods to e used in opertor syntx is tht you n rete your own types tht work in the sme wy you would expet lnguge fetures to tF sndeedD the preE(x unry opertions for CD ED 3D nd ~ re prt of the l lirriesF ou n write methods in lss tht re interpreted s preE(x unry opertorsF o do soD simply nme the method unryopD where op is repled y CD ED 3D or ~F o if you wnted your own negtion you ould rete method lled unryEF

17.1.2.3 Property Assignment Methods


fk in the nk ount exmple we sid tht hving method tht strts with the word get followed y the vlue you were getting ws the tv style of doing things nd tht in l you simply nme method with the nme you wnt people to see for the propertyF sn our exmple this ws lneF sn tv style the prtner to the get method is set methodF sn l tht ounterprt to set is n ssignment methodF he dvntge of the ssignment method is tht it llows you to set property using norml ssignment syntxF o rete n ssignment opertorD write method with the nme prop aD where prop is the nme of the propertyF o help you understnd thisD let9s ssume tht you did wnt to e le to enter something like myeountFlneaUHHF e hd this ility with the puli vrD ut we deided tht ws too little ontrolF e ould get tht k y dding the following methodF

def balance_=(b:Int) = bal=b

CHAPTER 17.

OBJECT-ORIENTATION

QUQ

hnks to the wy l hndles ssignment opertorsD this will let oth of the following lines workF

myAccount.balance = 700 myAccount.balance += 40


o doing Ca will work like deposit nd Ea will work like withdrwF he downside is tht neither returns foolen to let you know if it workedF his prtiulr method leves things too openF e might s well hve the vr euse we re doing extly wht the vr would doF roweverD the dvntge of n ssignment method is tht it n e more omplex nd hve more logi ehind itF por exmpleD the lnea method ould e ltered to the followingF

def balance_=(b:Int) = { if(b>=0) { if(b<bal) withdraw(bal-b) else deposit(b-bal) } else false }


his version will reuse the ode from withdrw or deposit inlude ny error hekingD loggingD etF st lso throws in heking so tht ssignments to invlid lnes won9t go throughF xote tht you only inlude set method for properties tht re mutle so there re mny situtions where they re left o'F sf you re progrmming in more funtionl styleD you won9t hve these ssignment methodsF st is only when ojets spei(lly need to e le to mutte tht these re helpfulF he rel dvntge in tht se is tht the ode n look like norml ssignmentD ut will ll the method tht n do vrious types of error hekingF

17.1.2.4 The apply Method


hings get it more interesting in muh more sutle wy with the pply methodF ou write pply just like ny other method tht you might put in lssF ou n ll it just like ny other method s wellF roweverD l will llow you to ll the pply method without using dot or the nme pplyF hen you remove thoseD it mkes it look like you re treting the ojet s funtionF sndeedD this is how ll funtions work in lF es ws sid very erly onD everything in l is n ojetF ht inludes funtionsF e funtion is just n ojet of type tht hs n pply method tht tkes the pproprite methodsF he intelligent use of pply is tully how you hve een indexing into ll of the olletion typesF gonsider the following ode tht you ould write in the ivF

scala> val arr=Array(5,7,4,6,3,2,8) arr: Array[Int] = Array(5, 7, 4, 6, 3, 2, 8) scala> arr(3)

CHAPTER 17.

OBJECT-ORIENTATION

QUR

res0: Int = 6 scala> arr.apply(3) res1: Int = 6


he ll to rr@QA is tully just shortut for rrFpply@QAF l is doing nothing more here thn ssuming the presene of the ll to pplyF row n we use this in our own odec gonsider tht we write lss lled gourseetion tht will keep trk of students in ourse for usF e ould mke it so tht we n ddress into the ourse setion using either student nme or student shF

class CourseSection(val subject:String,val number:Int, val title:String) { private val students=mutable.Buffer[Student]() def addStudent(stu:Student) { students += stu } def apply(key:String):Option[Student] = { students.find(s => s.id==key || s.name==key) } }
he pply method here returns n yptiontudent euse it is possile tht there is no student tht mthesF sn tht se this returns the vlue xoneF ytherwise it will return ometudent with the proper tudent dtF ith this in ple you ould write the following odeF

val course=new CourseSection("CSCI",1321, "Principles of Programming II") course.addStudent(john) course("0123456").get.quizzes += 88


his mkes new ourse then dds in the student we reted ove tht is in the vrile johnF he lst line looks up our student y his sh nd dds quiz grdeF he ll to get is required euse of the ft tht pply returns n yptionF xote tht if the ourse didn9t hve mthing studentD this ode would result in n errorF

17.1.2.5 The update Method


rving n pply method is su0ient for mny situtionsF por exmpleD it is ll tht is needed for immutle olletionsF st is lso ll we will wnt for our gourseetion lss given how we hve written itF roweverD it isn9t su0ient if you wnt to do something like n ssignment into n rryF fsillyD it looks things upD it doesn9t hnge thingsF o do thisD you use the updte methodF hen l sees n expression like this

obj(args ) = e

CHAPTER 17.

OBJECT-ORIENTATION

QUS

it onverts it to ll of the form

obj.update(args,e)
o you n get ssignments for indexing y simply implementing the proper updte methodsF

17.1.2.6 Vector Example


o help demonstrte how these di'erent fetures n work we9ll write lss tht represents QEh vetorF e9ll give it xD yD nd z omponents then de(ne the types of opertions tht we would wnt to e le to perform on itF yne of the (rst mjor design deisions we hve to mke for this is whether we wnt the vetor ojets to e mutle or immutleF por this exmple we will go with the immutle version s it does etter jo of demonstrting funtionl design nd works etter for this exmpleF his pproh is more memory intensive nd n e slower in some pplitions euse it doesn9t mutte the vetorsF roweverD it often produes etterD more relile ode tht in some pplitions will e fster euse it prevents defensive opyingF ht is where you mke opy of n ojet to pss into other ode when you don9t wnt your version of the ojet to get hngedF e9ll strt with the delrtion of the lss tht inludes opertors for CD ED BD nd GF st lso hs two versions of pplyF vstly there is method lled totring tht we will lern more out in hpter PHF his method determines wht we see when n ojet of the et type is printed outF st is very useful to hve form tht helps you see wht is going on to orret prolemsF

class Vect(val x:Double, val y:Double, val z:Double) { def +(v:Vect):Vect = new Vect(x+v.x,y+v.y,z+v.z) def -(v:Vect):Vect = new Vect(x-v.x,y-v.y,z-v.z) def *(c:Double):Vect = new Vect(c*x,c*y,c*z) def /(c:Double):Vect = new Vect(c/x,c/y,c/z) def apply(i:Int):Double = i match { case 0 => x case 1 => y case 2 => z } def apply(is:Seq[Int]):Seq[Double] = { is.map(Array(x,y,z)) } override def toString = "<"+x+", "+y+", "+z+">" }
he (rst version of pply lets you index into the di'erent oordintesF st is written using mth expression though there re ertinly other wys it ould e doneF he seond version of pply is more unusulF st llows you get the xD yD nd z vlues k s sequene y pssing in sequene of indexesF

CHAPTER 17.

OBJECT-ORIENTATION

QUT

ith this ode written we n instntite ojets of the et type nd perform the spei(ed opertions on themF

scala> val v1: Vect = scala> val v2: Vect = scala> val v3: Vect = scala> val v4: Vect =

v1=new Vect(1,2,3) <1.0, 2.0, 3.0> v2=new Vect(2,-4,7) <2.0, -4.0, 7.0> v3=v1+v2 <3.0, -2.0, 10.0> v4=v3*8 <24.0, -16.0, 80.0>

xote tht with the ode tht we hve hereD we hve to put the slr on the right of the multiplyF sf you tried to do VBvQ you would get n errorF his is euse l sees tht s @VAFB@vQAF he vlue V is n sntD it doesn9t hve version of B tht works on etF st is possile to get round thisD ut it requires nother more dvned onept lled n impliit onversion whih we don9t wnt to onsider t this timeF por now we9ll e hppy putting the slr on the rightF here re two other ommon opertions on QEvetorsX the dot produt nd the ross produtF he dot produt returns slr nd the ross produt returns vetorF hen writing theseD we hve to mke signi(nt deisionD do we wnt them to e symoli or wordsc e n9t use just B for oth euse l ouldn9t (gure out whih one we ment to use t ny given timeF por tht mtterD people reding the ode proly ouldn9t eitherF l does give us the ility to use longer symol nmes with multiple opertor symolsF o mye BCB for dot produt nd BEB for ross produtF ou n9t use BFB nd BxB euse F nd x re not opertor hrtersF he hoie of C nd E in these omes from knowledge of the formuls for dot nd ross produtsD ut neither relly (ts well or will red to most people s dot nd rossF por tht resonD we will stik with norml lpheti method nmesF

def dot(v:Vect):Double = x*v.x+y*v.y+z*v.z def cross(v:Vect):Vect = new Vect(y*v.z-z*v.y,z*v.x-x*v.z,x*v.y-y*v.x)


e n still use these in opertor nottionF he only prolem is tht hrters hve lower preedene thn multiplition would so prenthese will hve to e used to enfore order of opertionF here is no updte method provided euse these re immutleF ou ouldD in theoryD mke them mutle nd provide n updteF ou would proE ly lso wnt to provide CaD EaD BaD nd Ga opertors tht mutte insted of mking new opyF hoing so is left s n exerise for the rederF

17.1.3 Objects
l hs nother type delrtion tht is similr to lss in syntxD ut whih hs very signi(nt di'erene in meningF he ojet delrtion retes

CHAPTER 17.

OBJECT-ORIENTATION

QUU

single ojet in the urrent sope with the memers nd methods tht you put in itF nlike lssD you n9t pss n ojet ny rgumentsF his is euse you don9t mke the ojet with newF he delrtion of the ojet is wht mkes itF vike lssesD the ojet delrtion retes new type nd s suhD we use ptil letter s the (rst letter in the nmeF o use the memers or methods of n ojetD use the type nme s the ojet nme nd ll it just like you would for n instne of lssF yjet delrtions n e used in ny sope where you wnt n ojetD ut you only wnt one ojet of tht typeF et the top level they re typilly used s ple to orgnize funtions though they hve fr more verstility thn this overllF

17.1.3.1 Applications
he ft tht you n use n ojet without instntition is very signi(ntF he ojets e'etively exist s soon s the progrm strts runningF ou don9t hve to hve line tht mkes new oneF his is most signi(nt when we move eyond the iv nd sripts nd into full lown pplitionsF e top level ojet delrtion de(nes n entry point to n pplition if it ontins method lled min tht tkes n rgument of type errytring nd returns nitF rere is simple exmpleF

object FirstApp { def main(args:Array[String]) { println("My first application.") } }


he sripts tht we hve een using n e onverted to pplitions y doing nothing more thn putting the ode inside of min tht is in n ojetF sf you use the vrile nme rgs for the ommndEline rgumentsD then referenes to them in sript will even workF he min di'erene etween sript nd n pplition is how you orgnize the ode in (les nd how you run themF fy de(nitionD sript is supposed to e smll progrmF ell of the ode for sript goes into single (leF hen the mount of ode tht is required gets lrgerD it needs to e split prt nd orgnizedF he orgniztionl struture you should follow in l in nerly ll situtions is to put eh lss or ojet type in seprte (le tht is the nme of the type followed y FslF gonsider the exmple of grdeook pplitionF e might use the tudent lss from ove nd put it in (le lled tudentFslF he gourseetion lss from ove would go in gourseetionFslF pinllyD we would hve n ojet delrtion for grdeook tht would go in qrdeookFslF sn ddition to hving min methodD this would keep olletion of ourses nd provide whtever funtionlity we wnted for the grdeookD whether it ws text or qs interfeF

CHAPTER 17.

OBJECT-ORIENTATION

QUV

unning n pplition like this is two step proessF pirst you hve to ompile the odeF his is done with the sl ommndD whih stnds for l ompilerF ou hve to tell the l ompiler wht (les it is you wnt to ompileF sf you orgnize your ode so tht ll the ode for n pplition is under diretory you n exeute something like sl BFslF his will ompile ll of the (les ending in Fsl in the urrent diretoryF hen you do thisD if you hve ny syntx errors they will e found nd reported to you in muh the sme wy they were when you rn progrms s sriptsF yne you hve found nd (xed ll syntx errorsD the ompiler will produe set of (les in ompiled yteode tht you n runF hese (les will end with the Flss extensionF o run the pplition you go k to using the sl ommndF ynly now you follow it y the nme of the ojet you wnt to run the min fromF o in the se of our grdeook we ould run it y entering sl qrdeookF yther ommndEline rguments n e spei(ed fter the nme of the ojetF he pplition hs to e n ojet euse methods in lss n only e lled on instnes of tht lssD not the lss itselfF o in order to ll method you hve to hve exeuted new on tht typeF roweverD min hs to e lled right o' the tD efore ny other logi hs een exeutedF his isn9t prolem with n ojet s the single instne exists without ll to newF

17.1.3.2 Introduction to Companion Objects


he most ommon use of ojets is s ompnion ojetsF e ompnion ojet is n ojet tht hs the sme nme s lssF foth the lss nd its ompnion ojet should e pled in the sme (leF he ompnion ojet hs ess to privte memers of ojets of the lss it is ompnion withF imilrlyD the lss n see privte elements in the ojetF ou might hve wondered why it is tht when we re uilding ojets in lD sometimes we use new nd sometimes we don9tF he relity is tht mking new ojet lwys invokes newF hen you don9t type itD it mens tht you re lling other ode tht doesF hen you use the nme of the type without new to uild n ojetD you re lling the pply method on the ompnion ojet nd tht pply method is lling newF nfortuntelyD you n9t simply write lsses with ompnion ojets in the iv or in sriptsF por us to rete our own ompnion ojetsD we hve to e working in the mode of writing pplitionsD ompiling with slD nd running the ompiled (les with slF e will ome k to this next hpterF

17.1.4 Object Decomposition


et (rstD the use of ojetEorienttion might not seem ll tht signi(ntF enyE thing tht is method ould e written s funtion tht tkes the ojet s (rst rgumentF roweverD over time you will ome to see tht undling dt nd funtionlity tully hs the ility to hnge lot of how we pproh solving prolemsF snsted of simply thinking of wht funtions you should rek your

CHAPTER 17.

OBJECT-ORIENTATION

QUW

prolem down into nd how to group the dt s seprte onsidertionsD you tke them togetherF ou think of wht dt memers nd wht funtionlity elong together in ojetsF st is ommon to use the nlogy when tehing ojetEorienttion tht oE jets re nouns nd the methods re the vers tht t on those nounsF his nlogy oversimpli(ed the sitution thoughF yjets in progrmming don9t lE wys hve to re)et things tht we onsider to e ojets in the rel worldF hey n represent muh more strt oneptsF sndeedD funtions in l re ojetsF e lrge portion of the seond hlf of this ook will e devoted to helping you see how we n use ojets to express vrious ides nd to mke our lives esier s we develop softwreF

17.2 Revisiting the API


enother signi(nt hnge in the seond hlf of the semester will e our reline on the esF sn the next few hpters we will e unovering mny elements of l tht will help you to understnd di'erent prts of the es nd you will e expeted to go into the es to get informtion on wht you n do with the lirriesF e hve lredy lerned enough to help it with understnding wht some things men in the esF hen you open up the es the left side hs frme tht looks like (gure IUFIF e hve used the generi word type to desrie the things tht re listed in this frmeF xow we n e more spei(F here re relly three di'erent wy of mking types in l nd the es indites whih one you re deling withF he irles next to the nmes ontin one of three letters in themF he mening of these letters is s followsF

E por lssF o E por n ojetF t E por tritD whih we will lern out in hpter PHF por now you n think of trit s eing like lssF
hen you lik on one of theseD you re shown the methods nd memers tht re de(ned in themD whether it e lssD n ojetD or tritF he es itself is uilt y running progrm lled sldo on sl ode to generte rwv desriptions of wht is in the odeF 333 gonsider more hereD like wht is on the pges of the esF pinding pply in ompnion ojetsF

17.3 Meaning of Case Classes


he (rst usge of the term lss tht we enountered ws k in hpter IH when we looked t se lssesF xow tht you know it out regulr

CHAPTER 17.

OBJECT-ORIENTATION

QVH

pigure IUFIX his is prt of the right pnel tht you see when you (rst enter the esF he little irles with the letters D oD nd t indite whether it is lssD ojetD or tritF

CHAPTER 17.

OBJECT-ORIENTATION

QVI

lssesD you might wonder wht se keyword does for se lssF st doesn9t do nything tht you ouldn9t do without the use of seD it simply dds lot of ode for youF pirstD ll the dt in the se lss is puli vls insted of just eing rguE mentsF eondD it utomtilly retes ompnion ojet tht hs n pply method tht you n use to mke instnes of the se lss without using newF st lso dds opy method to the lss tht hs defult rguments for ll the vluesF here re few other things dded in tht llow the pttern mthing tht we hven9t tlked out yetF

17.4 Import Options


333 like stu' from lsses or hiding things or renming things kges re nested nd you n import speifying only the lol nmesF import pkge E rings in the pkge nme import pkgeF{lsses} E rings in those lsses from the pkge por the lsses list you n lso renme or hide lssesF sf you put ab fter lss nme you n follow it with di'erent nme or use to hide the lssF

Self-Directed Study
inter the following sttements into the iv nd see wht they doF ome will produe errorsF ou should try to (gure out whyF ry some vritions to mke sure you understnd wht is going onF

scala> def succ(n:Int):Int = n+1 scala> succ(1)


333

Exercises
IF ixerise PF wutle etF trive to keep existing opertions unhngedF he(ne CaD EaD BaD Ga

Projects
IF sf you did projet ITFQ nd you did grvity integrtions efore thtD then you n onsider doing this optionF he si ide is tht you re going to mke it so your formul prser n use vriles nd then hve the user type in fore formul tht is used insted of grvityF sn the formul prserD there were two possile ses where you didn9t (nd n opertorX numer nd prenthesesF he vrile eomes third

CHAPTER 17.

OBJECT-ORIENTATION

QVP

possiilityF e will sy tht string is vrile if it is ll lettersF ou n sy tht in l with strFforll@FisvetterAF o use vriles you need n extr rgument to the evlutionD wptringDhouleF he tring is the vrile nme nd the houle is the vlue to use for tht vrileF sn the qs for your integrtor you should hve text (eld tht lets users input formulsF ou n de(ne stndrd vriles tht re usedD like d for distne or m nd m for the msses of the (rst nd seond prtiles in n intertionF sing thisD grvity would e input s EmBmG@dBdAF e spring onnetion would e EdF ou n ply with other options s well nd see how they hnge the wy prtiles moveF PF sf you did projet ITFQ nd you did funtion plotting erlierD then you n onsider this optionF he gol is to hve you lend the two together so tht users n input funtions nd rnge in x nd your ode will plot the funtionsF ou should hve three text (elds tht de(ne the funtions f@xAD g@xAD nd h@xAF por little it of n extr hllengeD mke it so tht funtions n refer to one notherF o the funtion for g@xA ould e f@xEIACS or something similrF ou ould lso dd things like trignometri funtion support so tht you n plot more interesting funtionsF QF sf you did the ron in n erlier projetD you ould updte it to e ojet orientedF por ron you n mke lss the represents light yle with the positionD diretionD nd olorF st ould hve method lled move tht lters the position ppropritly for the diretionF yther methods ould inlude turning left of right tht re lled y retions to key pressesF ith this hnge it is now fesle to dd in more plyers nd hve wlls from one plyer dispper when tht plyer diesF ixtend the gme to hve three humn plyers @or dd omputer plyerA nd mke it so tht when plyer diesD the line for tht plyer goes wyF RF sf you implemented the wndelrot set lultion nd disply previouslyD this is the projet for youF pirstD use wht you hve lerned in this hpter to mke lss lled gomplex tht represents omplex numers nd lE ter your originl wndelrot lultions to use thtF yne you hve done thtD you will tke further dvntge of it y dding the ility to disply tuli sets of qudrti polynomilsF ivery point in the wndelrot orresponds to one of these tuli setsF he eqution for qudrti polynomil looks muh like tht for the 2 wndelrot setD zn+1 = zn + c with c eing (xed vlue nd z0 eing the point in the plne you re lulting forF fy ontrstD the wnderot set used di'erent c vlue for eh point nd z0 = 0 so z1 = cF egin you iterte until either the vlue leves the re round the origin or until

CHAPTER 17.

OBJECT-ORIENTATION

QVQ

some prespei(ed numer of itertionsF sf the user liks on lotion @use the wousegliked eventA then you should pop up nother window @use prmeD not winprmeA with di'erE ent pnel tht will drw the tuli set ssoited with the point the user liked onF ou n deide wht funtionlity you wnt to put into winE dowF st should strt with ounds of r [2, 2] nd i [2, 2] for the rel nd imginry xes respetivelyF st shouldn9t e hrd to dd zoomingD ut tht isn9t requiredF SF his projet ontinues one of the options from n erlier ssignment where you hd to (gure out how mny elements of eh type were on the difE ferent sides of hemil equtionF ou should rell tht the output of tht progrm ws something like the followingF gX BIadBI rX BRaBP yX BPaBICdBP e wnt to tret this s system of liner equtions nd solve it to (nd the proper vlues of D D D nd dF hese prtiulr formuls give you three equtions for four unknownsF sf you rememer systems of equE tionsD tht9s typilly not good thing s the system is underdetermined so there re n in(nite numer of solutionsF he esy wy to (x tht is to ssume tht ertin numer of the oe0ients re I so tht you re left with equl numers of equtions nd unknownsF he form given ove would e (ne for solving this eqution y hndD ut for solving it on omputer we will wnt to move things round itF he ide is tht we wnt to get it into the form exayD where e is mtrix giving the expliit numers in the equtionsD x is vetor with the vriles we re solving forD nd y is vetor with whtever onstnts wind up eing on the right side of the equl signF vet9s mke this more expliit y rerrnging the equtions ove into something more like the form we wntF IBEIBdaH RBEPBaH PBEIBEPBdaH xow we hve to pik oe0ient to set to I so we get down to equl numers of equtions nd oe0ientsF eny will do eqully (neD ut proE grmmtilly you will proly (nd it is esiest to set the lst oe0ient to onstnt vlue @so everything is still zero indexed in your odeAF sn this se tht is dF sf we do tht nd move onstnts to the right side we get the following equtionsF

CHAPTER 17.

OBJECT-ORIENTATION

QVR

IBaI RBEPBaH PBEIBaP his n e trnsformed into exay 1 A= 4 0 nd if

0 0 2

0 1 1

1 y= 0 2

F foth x nd y re olumn vetors here so they hve single olumn nd multiple rowsF ememer tht a x= b c nd tht is wht we wnt to solve forF he wy you will do this is through proess lled qussin elimintionF st turns out tht there re mny methods of doing this tht hve di'erent numeril propertiesF qussin elimintion isn9t the estD ut it is the simplest to desrie nd su0ient for our purposesF qussin elimintion is lso extly wht you would do if you were solving this prolem on pper so hopefully it will mke senseF ht we do in qussin elimintion is multiply nd dd together rows in e nd y to remove oe0ients nd turn e into tringulr mtrixF e might lso hve to swp rows t ertin timesF sn ftD we will do tht generlly to improve numeril stilityF o egin withD we wnt to remove the term from everything ut the (rst rowF e ould do this with e s it isD ut for numeril resons it is est if we keep the lrgest oe0ientF ou9ll see other resons for this when we remove F o the (rst thing we do is we note tht the lrgest oe0ient of is R nd it is in the seond row so we swp the (rst nd seond rowsF xote tht we swp them in oth e nd yF his gives the following vluesF 4 0 1 0 A = 1 0 0 nd y = 1 0 2 1 2 xow we eliminte the terms in the seond nd third rows y multiE plying their vlues ppropritely so tht when we sutrt them from the top olumn we don9t hve nything leftF sf the term is lredy zero in row we n leve it loneF sn this se we will remove the term from

CHAPTER 17.

OBJECT-ORIENTATION

QVS

the middle row y multiplying it y R nd sutrting the top row from itF e9ll do nothing with the ottom rowF his gives the following vluesF 4 0 1 0 A = 0 0 1 nd y = 4 0 2 1 2 xow the top row is set so we look t the smller nested mtrix ignorE ing the (rst row nd olumnF e wnt to eliminte the oe0ients from thtF rere it relly mtters tht s swp up the row with the lrgest oe0ient euse wht is there right now hs zero oe0ient nd tht will do d thingsF e do the swp nd sine the lst row lredy hs zero in the oe0ient we won9t do nythign elseF ht leves us with the following vluesF 4 0 1 0 A = 0 2 1 nd y = 2 0 0 1 4 his we n solve y working out wy up the mtrixF he ottom row tells us tht aRF e plug tht into the next row nd get PBERaP nd (nd aQF st9s esy for us to sy thtD ut we should proly exmine how the omputer will (nd these vluesF por the (rst one the omputer simply does ay@PAGe@PA@PAF hen s we move up we hve to do some loops to sutrt things o' efore we do the divisionF sn this se a@y@IAE Be@IA@PAAGe@IA@IAF xote tht we re lwys dividing y the omponent on the digonl nd we sutrt o' ll the terms to the right of the diE gonlF xow we re down to our top eqution whih is aGR so aIF sn the progrm tht will e a@y@HAEBe@HA@PAEBe@HA@IAAGe@HA@HAF he y@HA nd e@HA@IA re oth zero ut the mth in the progrm will inlude them nd it won9t mtterF our progrm should tke n input just like the erlier ssignment where you type in hemil equtionF st should then print out the sme output s in tht ssignment nd follow tht with solutionF sn this se it would print out 4aI aQ aR daI4 s the lst line of outputF here might e some deiml points in there s wellF his exmple ws well ehved nd gve us integer resultsF roweverD our proedure doesn9t gurentee thtF sf you wnt n extr hllenge you n sle things up so they re ll integersF TF st9s time to mke your mp progrm into true text dventure gmeF st doesn9t mtter how you do thisD ut you need to dd in gol to the gme nd hve it inform the plyer if heGshe wins or losesF wost of the originl text dventure gmes hd some type of puzzle solving where the items ould intert with one nother or with rooms in ertin wys to mke things hppenF ou proly don9t wnt to go the wh route nd hve equipmentD omtD nd the like though simple omt might e fesileF

CHAPTER 17.

OBJECT-ORIENTATION

QVT

ou must dd help ommnd whih prints out the ojetive of the gme nd how to plyF his should red nd print the ontent of (le so you don9t hve to type in the full help in print sttementsF UF sf you hve een doing the ry tring nd grphis projetsD now it is time to dd olors nd mke it so tht you hve rel imgeF ou will lso enle re)etions s tht is simple ddition tht uses reursionF ou lredy hve sene tht inludes spheresD plnesD nd lightsF o fr you hven9t mde use of the lightsF ih of the geometry ojets nd lights should hve olor tthed to itF ou need to write funtion tht tkes ry nd the sene nd tells you wht olor to useF sf it never hits nything the olor should e lkF eftor the ry trer so tht it uses lsses for the vrious omponents inluding pointsGvetorsD spheresD plnesD lightsD etF o olor point you need the olor of the ojet tht ws hitD nd the lighting on tht pointF o get the lightingD send ry from the point of ontt to the light soureF sf there is ny geometry in the wyD then tht point is shdowed nd the light doesn9t get to itF sf there isn9t nything in the wyD tht light onE triuted to the pointF he olor should e the omponent wise produt of the olors of the light nd the ojet hit sled y the osine of the ngle etween the norml nd the diretion to the lightF o (nd the osineD keep in mind tht a b = |a| |b| cos F

Chapter 18

Bigger Programs/New Tools


e hve een working in the ommndEline environment this fr euse it is good thing to know nd it works very well for oth the iv nd sriptsF st supported the little steps tht we needed to tke erly onF roweverD it is now time to move eyond sripts nd write lrger progrms s pplitionsF his n e done using the ommndElineD s ws desried in the lst hpterD ut there re esier wysF

18.1 Eclipse IDE


vrge sle softwre is generlly developed with the ssistne of mny toolsD inluding n sntegrted hevelopment invironment @shiAF et this point we wnt to move our own e'orts from the ommndEline to n shiF por this ook we hve hosen to work with the ilipse shiF here re others tht you n ertinly tryD ut ilipse supports mny lnguges nd is one of the (rst pltforms for whih l plugEin ws retedF he shi mkes it lot esier to mnge the multiple (les tht re typiE lly reted when writing lrger pplitionsF st lso utomtes the proess of ompiling the ode nd n show you syntx errors s you re writing the odeF ou n downlod ilipse for free from httpXGGwwwFelipseForgF here re multiple di'erent version of ilipse tht hve een ustomized for di'erent types of usgeF ou should downlod the glssi versionF pollow their instrutions for instlltionF hen you run ilipse it will sk you for workspe diretoryF he defult should e perfetly (ne to strt withF he (rst time you run ilipse you will get welome sreen tht looks something like (gure IVFIF ou n spend s muh time s you like running through the tutorils nd other informtion they hveF hen you re redy to strt progrmmingD lik the ule tht tkes you to the workspeF pigure IVFP shows wht the ilipse workspe will look like when you (rst run itF he window is devided into numer of di'erent regions nd hs the norml set of menus you expet from grphil pplitionF sf you look through QVU

CHAPTER 18.

BIGGER PROGRAMS/NEW TOOLS

QVV

pigure IVFIX he welome sreen for ilipse tht you will see when you run it for the (rst timeF

CHAPTER 18.

BIGGER PROGRAMS/NEW TOOLS

QVW

pigure IVFPX e lnk ilipse workspeF his is wht you will strt with when you re redy to egin progrmming in ilipseF the menus you will see tht there re lots of di'erent optionsF hon9t let this sre youF e will only e using smll numer of them in this ook nd you don9t hve to know wht ll the others do to mke use of ilipseF fy defultD ilipse glssi is set up to progrm in tvF ou n tell this from the top right orner where there is little utton tht is seleted with n ion nd the word tvF sn order to progrm in l we will hve to dd something to ilipseF sf you go to httpXGGwwwFslEideForg they hve instrutions for dding the l plugEin to ilipseF sf you follow these orretly you will e sked to restrt ilipseF efter the restrt things will look the smeD ut you will hve the ility to write in lF o do this you will need to swith to the l perspetiveF ou n do this y liking the ion in the top right orner of the workspe nd seleting l s shonw in (gure IVFQF sf l isn9t listed on the initil menuD pik yther nd selet l from the window tht rings upF sn the ommndEline you ould just strt editing (le tht ended in Fsl nd you hd progrmF ilipse mkes you go through some other steps to keep ode orgnizedF ell ode in ilipse is pled in projetsF hi'erent projets n use di'erent lnguges for developmentF e wnt to mke projet tht is ssoited with lF ou n do this from the pile menu or y doing right lik on the kge region on the left side of the workspeF sf you re in

CHAPTER 18.

BIGGER PROGRAMS/NEW TOOLS

QWH

pigure IVFQX his (gure shows the workspe with the perspetive swithing menuF

CHAPTER 18.

BIGGER PROGRAMS/NEW TOOLS

QWI

pigure IVFRX hilog for mking new l projetF the l perspetive the option to mke l projet should e right up t the top of the xew sumenuF sf it isn9tD pik other nd (nd the l rojet optionF hoing this will ring up dilog ox tht looks like (gure IVFRF ou n enter nme nd lik pinishF he defult options should work well enough for our purposes t this pointF por this exmple we will mke projet lled lfook tht will e used for ll the ode written in the reminder of the ookF ou n pik di'erent nme if you likeF tust keep in mind tht projets re intended to e groupings of firly lrge groups of odeF hon9t mke new projet for every little ten line progrm you writeF ou mke new projet when you truly hve projet to e working onF snside of projet you need to orgnize your ode into pkgesF e (rst rn into pkges k in hpter W when we hd to strt importing ode from the stndrd lirry pkgesF xow we re going to strt mking our own pkgesF hen writing pplitionsD it is onsidered poor style to not use pkgesF sf you don9t speify pkgeD your ode is put into wht is lled the defult pkgeF o mke your ode prt of pkge ll you tehnilly hve to do is put in pkge sttementF his n e done in two wysF sf you put pkge sttement t the top of the (leD ll the ode tht ppers in the (le will e prt of tht pkgeF his style is dopted from tvF l pkges hve true nesting though nd you n follow pkge delrtion with ode lok nd ll the ode inside the urly res of tht lok will e in the pkgeF sn

CHAPTER 18.

BIGGER PROGRAMS/NEW TOOLS

QWP

this ook we will typilly use the former pprohD primrily for purposes of orgnizing odeF sn tv pkges re lso diretories nd when ode goes in pkge you hve to hve it in diretory with the sme nme s the pkgeF hile this isn9t required in lD it is reommended euse it mkes it esier to (nd the ode you wntF his is prt of the reson tht in this ook we will dhere to the tv styleF hen you mke pkges in ilipse the orresponding diretories re utomtilly reted for youF e will go hed nd mke our (rst pkge for putting our (rst its of ode intoF o mke pkge you n right lik on the projet nd selet kge from the xew menuF his will ring up dilog ox where you n enter the pkge nmeF por now we will rete pkge lled simpleF xote tht the nme is in ll lowerseF his is the epted style for pkgesF ell letters should e lowerse with no spes or speil hrtersF e lled this pkge simple euse it is where we re going to put little ode snippets tht we will need to write osionllyF e9ll e reting other pkges s well to orgnize other prts of the ode tht we writeF xow tht we hve pkge we need to put something in itF sf you expnd the projet nd the sr diretory you n right lik on the pkgeF he xew menu will hve numer of di'erent l relted optionsF ou will see tht you n mke lssD tritD n ojetD or n pplitionF e wnt to mke n pplitionF ou n give it the nme pirstepp nd go with ll the defult settingsF efter you hve done this (le will e reted nd will e opened in the min editor re giving you sreen tht looks like (gure IVFSF he pplition is just ojet with the proper min method de(nedF snE sted of using the option to mke n pplition you n lwys mke n ojet nd give it the proper min methodF o mke your (rst little progrm in ilipse do somethingD simply (ll in the ody of the min methodF e simple println will su0e to prove tht it worksF here re mny wys to tell ilipse to run progrmF erhps the most diret is to right lik on the editor window with the pplition nd go down to the un es sumenuF elet to run it s l pplitionF he result you might see from doing this is shown in (gure cccF xote tht the output ppers in the gonsole t t the ottomF hen writing ode in ilipse you will write it in the ojetEoriented style putting ll of your ode in lssesD tritsD or ojetsF ou won9t e writing sriptsF sdelly eh lssD tritD or ojet tht you delre t the top level will e in its own (le tht hs the sme nme s the lssD tritD or ojetF his isn9t required y lD ut helps to orgnize the ode nd mkes it esier to (nd thingsF hen writing smll progrms lone it doesn9t mtter so muhF roweverD s progrms get lrger or if you strt writing ode with other peopleD the ility to esily (nd things tht you wrote long go or tht others wrote grows more importntF his doesn9t men tht every (ve line lss you ever write needs its own (leF roper l style tends to led to mny smller lssesF ype delrtions n e nested just like everything else in lF sf you (nd need for quik little lss in one prt of your odeD just write it where you need itD even if tht is

CHAPTER 18.

BIGGER PROGRAMS/NEW TOOLS

QWQ

pigure IVFSX his (gure shows wht the workspe will look like fter you hve seleted to rete your (rst pplitionF

CHAPTER 18.

BIGGER PROGRAMS/NEW TOOLS

QWR

pigure IVFTX his shows the pplition with single println nd the result of running it with output in the gonsoleF

CHAPTER 18.

BIGGER PROGRAMS/NEW TOOLS

QWS

inside of some other lss or ojetF ou n even mke new types inside of funtionsGmethodsF o get yourself fmilir with ilipse you should onsider resolving some erlier prolems writing them s pplitions insted of sriptsF o keep things orgnizedD put eh prolem is seprte pkge inside of the simple pkgeF o you might hve simpleFrtionl or simpleFguiF ou n lso ring up n iv in ilipse if you right lik on projet nd selet l b grete l snterpreterF

18.2 Concurrent Versions System (CVS)


e signi(nt tool of softwre development is the versioning systemF hese help developers keep trk of ode nd del with the di0ulties of hving multiple people working on softwre t one timeF hey n lso e useful for individul developers who re working on piee of ode from multiple di'erent omputers s it n help in keeping the ode on the di'erent omputers in synhF here re numer of di'erent versioning systems tht developers hoose to use for di'erent resonsF por this ook we will e using the gonurrent ersions ystem @gAF g is one of the older versioning systemsD ut it is very villeF st is lso the versioning system tht omes y defult with ilipseF ou ould hoose to use n lternte systemD suh s suversionD ut you will hve to instll di'erent plugEin for ilipse to get tht funtionlityF

18.2.1 Making the Repository


o use g you need to mke g repository on some omputer tht you n ess from ny of the lotions where you will e working on the projetF sf you re on vinux system you n do this from the ommnd lineF pirst you need to mke diretory for the repositoryF e diretory lled g in your home diretory will work (neF sf you re in your home diretory you n do this with mkdirF

mkdir CVS
yne you hve the diretoryD you hve to set it up s g repositoryF he vs ommnd under vinux will do this nd ny other funtions you need to do with gF o see ll the di'erent options you hve use mnF sf you just wnt to initilize the diretory tht you mde you n use the following ommndF

cvs -d$HOME/CVS init


he 6rywi n e repled with the fully spei(ed pth of your home diretory if it isn9t de(ned on your systemF ou n use the vs ommnd to ommit ode to the reposity or to updte it from the repositoryF e will e doing these funtions from inside of ilipse insted of from the ommnd lineF

CHAPTER 18.

BIGGER PROGRAMS/NEW TOOLS

QWT

pigure IVFUX his (gure shows the ilipse g epository ixploring perspeE tiveF

18.2.2 Set-up in Eclipse


o get strted with g in ilipse you should open the g epository ixE ploring perspetive in ilipseF ht will hnge the workspe to look like (gure IVFUF sf you right lik on the g epositories view in the top left you n hoose to set up new repositoryF ht will ring up window into whih you need to enter the informtion for your system nd repositoryF ou might need to sk system dministrtor for onnetion informtion if there re seurity restritionsF yne you hve repository set up you n go k to the l perspetive nd right lik on the projet you wnt to use with the reposityF prom tht menu you will selet em b hre rojetF his will let you selet the repository you wnt to ple the ode inF por shring repositoryD you n skip the previous step of setting up repository n set one up when you hoose to shreF qoing the other wy requires tht you set up the repository (rst thoughF et this point you will e sked to ommit your ode to the respositoryF e dilog ox will ome up llowing you to selet whih (les you wnt to ommit nd sk you for omment ssoited with this ommitF hen you lik tht you re doneD the urrent version of your ode will e opied into the repositoryF

CHAPTER 18.

BIGGER PROGRAMS/NEW TOOLS

QWU

18.2.3 Getting Access on Other Systems


hen you wnt to gin ess to your projet on nother system you will ring up the g epository ixploring perspetive gin nd open the proper repositryF nder the repository will e seletion lled riehF sf you expnd tht it will tell you ll the projets urrently in tht repositoryF ight lik on the one you wnt nd hek it outF ht will pull down the version of tht ode urrently in the repository to your lol mhine nd put it in projetF ou n then swith k to the l perspetive to edit tht projetF

18.2.4 Repository Usage and Rules


iditing the ode on ny mhine doesn9t utomtilly hnge wht is in the repositoryF o do this you hve to ommit your hngesF ou lso don9t uE tomtilly get hnges from the repositoryF sn order to do tht you hve to updteF yne projet is onneted to repositoryD the em menu will hve options for oth ommit nd updteF yften it is good to see wht you re ommitting to or updting from the repositoryF ou n do this y seleting the ynhronize with epository option from the em menuF his option will sk you to swith to di'erent perspetive nd you should let itF prom there you n see wht (les you need to ommitD wht (les you ould updteD nd if ny (le needs othD it will show it s on)it tht you n look through nd resolveF hen you re working y yourself nd just using the repository to enle single ode se ross multiple omputersD you just hve to rememer to updte the ode nytime you strt working on omputer nd ommit it when you re doneF sf you forget to do this you won9t hve the ltest version when you go to work on di'erent mhineF orking lone you might (nd you need to ommit ode tht isn9t working euse you need to go somewhere elseD perhps even to see someone who will e helping you to (x the prolemsF roweverD when you re working on ode se s groupD the primry rule of g or ny other ode repository system is tht you never ommit roken odeF he reson for this is quite simpleF sf you ommit ode tht doesn9t work nd someone else updtes efore you (x itD now they hve the roken ode nd it might prevent them from ompiling or running the full projetF tust (xing your prolems efore you ommit isn9t quite enough thoughF efter you hve mde your hnges nd mde sure everything ompiles nd runs properlyD you need to updte from the repository gin nd hek your ode one more time efore you ommitF o understnd why you need to do thisD imgine you re in work environment nd you lst updted your ode n hour goF here re multiple developers on your tem though nd some might hve ommitted their own hnges sine you did n updteF tust euse your ode works (ne with wht ws in there n hour go does not men it will work (ne with wht is there nowF sf you ommit without updting nd your ode doesn9t work with other more reent ommitsD you will put the repository into stte where the ode will e roken for nyone else who updtesF o efore you ommitD you updte

CHAPTER 18.

BIGGER PROGRAMS/NEW TOOLS

QWV

nd hek for errorsF sf there ren9t nyD you n ommitF sf there re errorsD you hve to (x themD updte gin nd repet the proessF fsillyD you n9t ommit until your ode heks out with n updte you hve just doneF

Exercises
IF ixerise

Projects
IF rojet

Chapter 19

A Project (Drawing Program)


xow tht we re fousing on ojetEorienttion nd the development of lrger progrmsD it will e helpful to hve lrger progrm tht we work on in this ookF his hpter will introdue projet tht we will develop inrementlly in mny of the following hptersF ou will e uilding other lrge progrms s prt of the projets in the rest of this ook s wellD ut it is helpful for you to see something esides the ode tht you re reting to give you fuller view of how things workF he progrm tht we re going to develop is drwing progrmF st isn9t going to e like int or quite like ny other norml drwing progrmF e will do few things di'erently to mke it so tht this progrm n etter illustrte key oneptsF e few things will e thrown in just for edutionl purposesD ut in generl fetures will e inluded to produe (nl pplition tht is ple of things tht you don9t normlly see in drwing progrms inluding nimtionF

19.1 Software Development Stages


es ws originlly disussed in setion UFUFIIF here re (ve stges involved in the prodution of ny lrge softwre systemF here re mny di'erent pprohes to orgnizing these (ve stgesD ut the generl nture of them is lwys the smeD nd they ll hve to e involvedF the (ve stges re s followsF

Analysis his is where things eginF huring nlysis the developers (gure out

wht it is tht the progrm is supposed to doF his is prolem de(nition phseF he more detiled the nlysisD the esier the other stges will eF sn prtieD it isn9t possile to get n initil nlysis tht overs everythingD nd inevitlyD things hnge over time on rel produtsF por this resonD while ll softwre must strt with nlysisD it isn9t something you (nish nd leveD you generlly hve to ome k to itF xote tht nlysis is very independent of progrmming nd only looks t wht you wnt to doD not how to do itF QWW

CHAPTER 19.

A PROJECT (DRAWING PROGRAM)

RHH

Design efter you hve su0ient nlysis tht you know wht you re trying

to doD the development turns to (guring how how to produe the desired result in odeF his is the design phse where you mp out wht will e hppening in the odeF yne ginD more omplete design will mke life esier lter onD ut relize tht it is silly impossile to mke perfet nd omplete design initilly so this is something tht will lso e revisitedF he design phse disusses odeD ut doesn9t tully involve odeF the odeF his ookD nd muh of your introdution to omputer sieneD fouses on developing your ility to write odeF roweverD this is only one phse in the lifeyle of softwre development nd when things re done well it n tully e smll phse reltive to othersF his is wht is foused on though euse you n9t relly do ny of the other phsesD with the possile exeption of nlysisD unless you hve strong grsp of how the implementtion will workF

Implementation he middle of the (ve stges is where you tully write

Debugging et this point you should hve lredy lerned tht just writing
progrm is not the iggest hurdle you hve to lerF pinding the errors in the progrm n tke fr longerF he proess of (nding nd (xing errors is lled deuggingF st is n ongoing proess in softwre development nd it often tkes signi(ntly longer thn the implementtionF

Maintenance efter the softwre is deemed omplete nd su0iently free of

errorsGugsD it is relesedF his ushers in the mintenne phseF winE tenne is something tht is hrd to simulte in lssroom environmentD ut it ritil for most professionl softwreF eople who py money for piee of softwre often wnt to know tht if they (nd something wrongD someone will e there to orret itF yften ustomers will think of ddiE tionl fetures they would like to see s wellF wintenne is the generl proess of deling with issues in the softwre fter it hs een relesedF

ou will ome k to these di'erent steps in mny lter g oursesF he (eld of softwre engineering is ll out how to do these things in wy tht produes the est results with the miniml mount of e'ortF

19.2 Analysis
333 wvccc

19.3 Design
333 wvccc

CHAPTER 19.

A PROJECT (DRAWING PROGRAM)

RHI

19.4 Making Packages


vrge softwre projets tht hve lot of ode in them need to e orgnizedF his is done y dding pkgesF e sw in the lst hpter how we n rete new pkges in lF

19.5 Visibility Options 19.6 Implementing the GUI


Exercises
IF ixerise

Projects
IF rojet

Chapter 20

Abstraction and Polymorphism


20.1 Polymorphism 20.2 Inclusion Polymorphism (Inheritance and Subtyping)
totring method

RHP

CHAPTER 20.

ABSTRACTION AND POLYMORPHISM

RHQ

20.2.1 20.2.2 20.2.3 20.2.4

Protected Visibility Anonymous Classes Traits Inheriting from Function Types

20.3 Inheritance in the Project 20.4 Parametric Polymorphism


20.4.1 20.4.2 20.4.3 20.4.4 Parametric Types Parametric Functions Type Bounds Parametric Higher-Order Functions

20.5 Structured Types


Exercises
IF ixerise

Projects
IF rojet

RHR

CHAPTER 21.

MULTITHREADING AND CONCURRENCY

RHS

Chapter 21

Multithreading and Concurrency


21.1 The Multicore Future 21.2 Basic Threads
21.2.1 Problems with Threads
21.2.1.1 Race Conditions 21.2.1.2 Deadlock

21.2.2 Synchronization 21.2.3 Wait/Notify 21.2.4 Other Thread Methods

21.3 Concurrency Library


21.3.1 21.3.2 21.3.3 21.3.4 21.3.5 Executors and Executor Services Callable and Futures Parallel Data Structures Atomic Locks

21.4 Multithreading in GUIs 21.5 Multithreaded Mandelbrot 21.6 Animated Bouncing Balls
Exercises
IF ixerise

CHAPTER 21.

MULTITHREADING AND CONCURRENCY

RHT

Projects
IF rojet

Chapter 22

Stream I/O
22.1 Streams for Files 22.2 Exceptions 22.3 Decorating Streams
22.3.1 Buering 22.3.2 Binary Data 22.3.3 Serialization

22.4 Saving Drawings


Exercises
IF ixerise

Projects
IF rojet

RHU

Chapter 23

Networking
23.1 TCP and UDP 23.2 Sockets
23.2.1 Streams from Sockets

23.3 Chatting 23.4 Collaborative Drawing


Exercises
IF ixerise

Projects
IF rojet

RHV

Chapter 24

Stacks and Queues


24.1 Abstract Data Types (ADTs) 24.2 Operations on Stacks and Queues 24.3 Real Meaning of O 24.4 O(n) Requirement 24.5 Array Based Stack 24.6 Array Based Queue 24.7 RPC Calculator
Exercises
IF ixerise

Projects
IF rojet

RHW

Chapter 25

Linked Lists
25.1 Nature of Linked Lists 25.2 Singly Linked List 25.3 Doubly Linked List 25.4 Iterators 25.5 Linked List Based Stack 25.6 Linked List Based Queue 25.7 Scrabble
Exercises
IF ixerise

Projects
IF rojet

RIH

Chapter 26

Priority Queues
26.1 Two Approaches
26.1.1 Sorted Linked List 26.1.2 Searching by Priority
333 s feel like more is neededF en pplition would e idelF

26.2 Gravity Integration 26.3 Variable Timestep Gravity


Exercises
IF ixerise

Projects
IF rojet

RII

Chapter 27

Refactoring
27.1 Smells 27.2 Refactorings
Exercises
IF ixerise

Projects
IF rojet

RIP

Chapter 28

Recursion
28.1 Refresher 28.2 A Maze in the Drawer
28.2.1 Revisiting the Basic Approach 28.2.2 Animating the Solution 28.2.3 Optimizing the Maze
sf you did wht ws suggested nd plyed round with the mze someD you might hve notied somethingF sf you keep tking out wll fter wll nd run the funtionD s you remove wllsD they funtion will strt to run more nd more slowlyF et ertin pointD you will mke the mze empty enough tht the funtion will tke longer thn you hve the ptiene to let it runF 333

28.2.4 Formula Parser Exercises


IF ixerise

Projects
IF rojet

RIQ

Chapter 29

Trees
29.1 General Trees
29.1.1 Implementations 29.1.2 Traversals

29.2 Binary Trees as Maps


29.2.1 Order Analysis
333 omething to implement in the hrwerc

Exercises
IF ixerise

Projects
IF rojet

RIR

Chapter 30

Regular Expressions and Context-Free Parsers


30.1 Chomsky Grammars
30.1.1 30.1.2 30.1.3 30.1.4 30.2.1 30.2.2 30.2.3 30.2.4 30.2.5 Regular Grammars Context-Free Grammars Context-Sensitive Grammars Recursively Enumerable Grammars Characters and Character Classes Logical Operators Boundary Requirements Greedy Quantiers Groups

30.2 Regular Expressions

30.3 Context-Free Parsers


Exercises
IF ixerise

RIS

CHAPTER 30. REGULAR EXPRESSIONS AND CONTEXT-FREE PARSERSRIT

Projects
IF rojet

Chapter 31

Spatial Trees
31.1 Quadtrees and Octrees 31.2 kD-Trees 31.3 Ecient Bouncing Balls
31.3.1 Using a Grid 31.3.2 Using a Tree

31.4 Ecient Gravity


Exercises
IF ixerise

Projects
IF rojet

RIU

Chapter 32

Binary Heaps
32.1 Nature of Heaps 32.2 Heaps as Priority Queues 32.3 Heapsort 32.4 Ecient Variable Timestep Gravity
Exercises
IF ixerise

Projects
IF rojet

RIV

Chapter 33

Binary Files
33.1 Random Access Files
33.1.1 Fixed Record Length 33.1.2 Indexed

33.2 Pickling
Exercises
IF ixerise

Projects
IF rojet

RIW

Chapter 34

Actors
333 s9ll hve to red the tors ook to get good grsp of this oneF

Exercises
IF ixerise

Projects
IF rojet

RPH

Chapter 35

Balanced Binary Trees


35.1 Weakness of Binary Trees 35.2 AVL-Trees
Exercises
IF ixerise

Projects
IF rojet

RPI

Chapter 36

Wrapping Up
36.1 What You Have Learned 36.2 The Possibilities 36.3 A Pet Project
Exercises
IF ixerise

Projects
IF rojet

RPP

Part III

Appendix Material

RPQ

Chapter 37

Quick Preview of Java


l hs mny of its roots in the tv progrmming lnguge eyond ompiling to the tv irtul whine @twA nd hving tht ility to ll on tv lirry funtionsF por this resonD it shouldn9t e too hrd to pik up tv fter you hve lerned lF his hpter is designed to help you in doing extly thtF

RPR

Chapter 38

Advanced Scala Concepts


l is n interesting lnguge in tht it hs firly simple spei(tion nd

38.1 Implicits 38.2 Covariant, Contravariant, and Invariant

RPS

Chapter 39

Scala Syntax
he syntx for l is rther simple ompred to mny other lngugesF yne of the ig hllenges students n fe is tht it is )exile to mke progrmmer9s lives esierF his ppendix is silly short ourse in the l syntxF ih mjor omponent is in old nd they refer to one notherF

Statement: es is the se with most progrmming lngugesD l progrm


is omposed sttementsF l inludes just few types of sttementsF

expression sttements E hue to the funtionl nture of lD ny vlid expression is llowed to stnd lone s vlid sttementF delrtion

 vrileGvlue delrtion  user delred type


lss trit ojet import sttements if sttement for sttement while sttement doEwhile sttement

Expression: en expression is nything you n put in the lnguge tht will

evlute to vlueF fy virtue of hving vlueD every expression lso hs typeF he simplest expressions re literls RPT

Chapter 40

Appendix B - Glossary

RPU

Index
8D IHP 88D WT `#`D IHQ aaD WQ b#bD IHQ b#b#bD IHQ ~D IHP IsEomplimentD TI PsEomplimentD TID IHQ ddressD PH eln uringD IW elisingD ISH elonzo ghurhD IW enlysisD QWW nlysisD ITID ITP esD QUW pplyD QUQ eqfD IHR rgumentsD SQ rryD IPT ssertD PWS inryD SU itEwise ndD IHP fitEwise erithmetiD IHP itEwise negtionD IHP itEwise orD IHP foolen vogiD WS foolen opertorsD WS fordernelD PPW foxnelD PPW fu'erD QRQ fu'eringD RHU futtonD PPU tD QP dD QP ghekfoxD PPU ghekwenustemD PQS hmodD QW hownD QW ghurhEuring thesisD PH lerD RP collectionD IPT gomofoxD PPU gomprisonsD WQ gontextEpree rsersD RIS pD QP gD QWS heuggingD RHH deuggingD ITI defD UT hefult ergumentsD VT defensive opyD IST hesignD RHH designD ITID ITP dfD RP doEwhile loopD IUQ doule preision )oting point numerD QHS downshiftD IHQ duD RP ehoD RQ ilipse shiD QVU iditorneD PPU espe hrtersD TT exeptionD PRQ ixeptionsD RHU exponentD TR expressionD SH pilesD IWP RPV

INDEX

RPW lol sopeD ITS lol vrileD UV vogi rogrmmingD PW logil ndD WT logil notD WT logil orD WS lsD QP wintenneD RHH mintenneD ITI mntissD TR wpD QQV mthD IHH mthD TS wenuD PQR wenufrD PQR wenustemD PQR methodsD SQ mkdirD QP moreD QP multidimensionl rrysD IVI mutableD IPW mvD QP xmed ergumentsD VT ojetD SQ yjetEyriented rogrmmingD PV yjetsD QUT otlD TP yption ypeD IRR kgesD IWQD RHI prmeterized typeD IPU rmetri puntionsD IRR ssEfyExmeD IST pssEyErefereneD IST pssEyEvlueD IST sswordpieldD PPV pttern mthingD IHH permissionsD QU olymorphismD RHP preedeneD QUH rivteD QTU prolem deompositionD VI rogrmming rdigmsD PT

(ndD RQ )oting point typesD TR plownelD PQH for loopD IUR pormttedextpieldD PPU funtionD US puntion viterlsD VQ puntionl rogrmmingD PU glol sopeD ITS qrphil ser snterfeD QH grepD RQ qridfgnelD PQH qridnelD PQH groupsD QV qsD QH gunzipD RH gzipD RH hedD RQ hexdeimlD TP righer yrder puntionsD VS identityD WS if expressionD WP immutableD IPW smpertive rogrmmingD PU smplementtionD RHH implementtionD ITI smportD IWQ snlusion olymorphismD RHP snheritneD RHP integer typesD TP stertorsD IWS tv irtul whineD RPR twD RPR velD PPU vmd glulusD IW left shiftD IHQ leftEssoitiveD QUI lessD QP vistD IQP listD IPT vistiewD PPU literlD SH

INDEX

RQH telnetD RI testingD ITID IVR ext pilesD IWP extereD PPV extpieldD PPV thunkD ISU tokenD RW topD RQ touhD RQ tryEthD PRQ tupleD ST uring mhineD IW typeD SH unzipD RH up shiftD IHQ updteD QUR vlD TU vrD TU rile vength ergument vistsD IRV rilesD TU viD RS iewsD IVT isiilityD QTT wD RQ wgetD RQ while loopD IUI whomiD QV wv wv wv wv ttriuteD QPQ ommentsD QPR elementD QPQ tgD QPP

rogressfrD PPV rotetedD QTUD RHQ psD RQ uliD QTU puttyD RP pwdD QP diofuttonD PPV diowenustemD PQS ewD PI ndom eess wemoryD PI rnge typeD IUU reursionD IHV egulr ixpressionsD RIS ivD RV requireD PWS qfD IHR right shiftD IHQ rightEssoitiveD QUI rmD QP rmdirD QP rshD RI sopeD UWD ITS spD RP sriptD UI rollfrD PPV rollneD PQH eprtorD PQS sequeneD IPT etD QQQ sftpD RP single preision )oting point numerD QHS liderD PPV splitD IWT plitneD PQH sshD RI sttementD SH utypingD RHP t ompletionD QT edneD PQH leD PPV tilD RQ trD RH

yieldD IUV zipD RH

S-ar putea să vă placă și