Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
17 views
Lecture 16 Web Han
Object oriented systems
Uploaded by
Sekhamuri Ap
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download now
Download
Save Lecture 16 Web Han For Later
Download
Save
Save Lecture 16 Web Han For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
0 ratings
0% found this document useful (0 votes)
17 views
Lecture 16 Web Han
Object oriented systems
Uploaded by
Sekhamuri Ap
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download now
Download
Save Lecture 16 Web Han For Later
Carousel Previous
Carousel Next
Save
Save Lecture 16 Web Han For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 24
Search
Fullscreen
6.001StructureandInterpretationofComputerPrograms.Copyright2004byMassachusettsInstituteofTechnology.
6.001 Notes: Section 13.1
Slide 13.1.1
Inthislecture,wearegoingtolookatavery differentstyleof
creatinglargesystems,astylecalledobject oriented
programming.Thisstylefocusesonbreakingsystemsupina
differentmannerthanthosewehaveseenbefore.Tosetthe
stageforthis,wearefirstgoingtoreturntothenotionof
abstractions,andusethatideatoseehowwecancapture
objectswithsomeinternalstatethatreflectsthestatusofthose
objects.Wearegoingtobeledfromtheretoastyleof
programmingcalledmessage-passinginwhichwetreat
systemsasiftheyconsistoflargecollectionsofobjectsthat
communicatewithoneanothertocausecomputationtotake
place.
Slide 13.1.2
Let'sstartbygoingbackandthinkingaboutthetoolswehave
developedforthinkingaboutcomputation.Twoofthekeytools
wehavedevelopeddealtwithabstractions.
Wehaveseenprocedural abstractions.Heretheideaisto
captureacommonpatternofprocessingintoaprocedure,then
isolatethedetailsofthecomputationfromtheuseofthe
computation,bysimplynamingtheprocedureandusingthat
namewithappropriateconditionsontheprocedure'sinput.We
sawthatthisstyleofapproachisparticularlyusefulwhen
dealingwithproblemsthatareeasilyaddressedinafunctional
programmingapproach,thatis,wherewecantreatthe
proceduresasgeneralizedmathematicalfunctions,meaningthat
theiroutputforagiveninputwillbethesamewheneverweevaluateit.
Wehavealsoseendata abstractions.Heretheideaistomodularizeoursystembycreatingdatastructuresthat
capturekeypartsoftheinformationweneedtohandle.Thegoalistohidethedetailsoftherepresentationand
storageofthedatabehindstandardinterfaces,primarilyourconstructorsandselectors.Thismeanstheusercan
thenmanipulatedataobjectswithouthavingtoworryaboutdetailsofhowtheyaremaintained.
Asyoumightexpect,oftenthedataabstractionsandtheproceduralabstractionsworkhand-in-hand,withthe
proceduresusedtomanipulatethedatausingthedataabstractioninterfaces,andwiththestructureofthe
procedurestendingtomirrortheactualstructureofthedata.
6.001StructureandInterpretationofComputerPrograms.Copyright2004byMassachusettsInstituteofTechnology.
Slide 13.1.3
Thegoalineachcaseisactuallythesame:wewanttohide
detailsoftheabstractionsothatwecantreatcomplexthingsas
iftheyareprimitiveunits.Inthecaseofprocedural
abstractions,wewanttohidethedetailsofthecomputation,
andtreattheprocedureasaprimitivecomputationalunit.Inthe
caseofdataabstractions,wewanttohidethedetailsofhow
componentsaregluedtogether,andtreateachunitasan
abstractcollectionofparts.
Slide 13.1.4
Giventhatwewanttouseabstractionsasatoolincontrolling
complexityinlargesystems,thereareseveralquestionsthat
comeupwhenthinkingabouthowtouseabstractions.Thefirst
is:whatisthebestwaytobreakanewproblemareaupintoa
setofmodules?Bothdatamodulesandproceduremodules?As
wehavealreadyseeninearlierlectures,someproblemsbreak
upinmultipleways,andbreakingthemupindifferentways
makessomeprocesseseasierandothersharder.Soakey
questionis:HowdoIusetheideaofabstractiontobreak
systemsintomodulesandwhatsthebestwaytodothis?
Thesecondquestiondealswithhoweasyitistoextendthe
system.IfIwanttoaddnewdatatypestomysystem,isthat
easy?IfIwanttoaddnewmethodstomysystem,newwaysofmanipulatingdatatypes,isthateasy?Wehave
seenseveralexamplesofthisalready,wearenowgoingtoreturntothesequestionsinordertoleadtoavery
differentwayofbreakingsystemsupintoconvenientsizedchunks.
Slide 13.1.5
Let'sstartbygoingbacktodataobjectsanddataabstractions.
Hereisthetraditionalwayoflookingatdata,atleastaswe
havedonethingssofar.
First,webuildsomecomplexdatastructureoutofprimitives,
forexample,conscellsorpairs.Second,weusetagsto
identifythetypeofstructurebeingrepresented.Thistellsus
howtointerpretthedifferentslotsintheliststructure.For
example,isthecaroftheliststructurethenameofaperson
orhisbattingaverageorhisGPA?
Then,thedataabstractionisactuallybuiltbycreatingasetof
proceduresthatoperateonthedata.Theseareproceduresthat
takeininstancesofthedata,useselectorstogetoutthepieces,dosomemanipulationtocreatenewpieces,and
thenusetheconstructortore-gluetheabstractionbacktogether.Thisledtotheconceptofdata-directed
programming,whichwesawearlier.Weusethetagtodeterminetherightsetofprocedurestoapply.Andthis
allowstheusertoprograminagenericfashion.Theycanfocusonwhat theywanttodo,buthavethecodedirect
thedatatotherightplacefortheactualwork.
6.001StructureandInterpretationofComputerPrograms.Copyright2004byMassachusettsInstituteofTechnology.
Slide 13.1.6
Hereisasimpleexampletoillustratethispoint.SupposeIhave
asetofdifferentgeometricobjects,thingslikenumbers,lines,
shapes,andIwanttowriteaprocedure,oranoperation,that
willscaleeachofthoseobjectsbysomeamount.Thena
genericoperation,underthedata-directedapproachwouldlook
likethisprocedureshownhere.Givenanobjectandmydesired
scalefactor,Iusethetypeoftheobjecttodispatch:ifitisa
number,Ijustmultiply;ifitisaline,Ishipittotheprocedure
thatwillscalealine,andsoon.
ThepointofthisexampleisthatIthinkaboutthingsintermsof
thekindsofobjectsIhaveandproceduresformanipulating
eachdistinctobjecttype.Iusethetagorthetypeoftheobject
totellmewhichproceduretosendtheobjectto.
Slide 13.1.7
Sonowlet'sgobacktoourquestions.Howeasyisittoextend
suchasystem,asystemwherewearebreakingthingsupinto
taggeddata,andusingdatadirectedprogramming?First,ifwe
addanewdatatypetooursystem,whatdowehavetodo?
Wellwecanseefromourexamplethatwewillhavetoallthe
procedureslikescale,toaddanewclausetoeachcond,
dispatchingonthatnewtypeofobject.Asaconsequence,if
therearemanysuchprocedures,wehavealotofchangesto
make,bothagreatdealofcodetowrite,andmoreimportantly
makingsurethatwechangealltherelevantprocedures.
Ifweaddanewoperationormethod,whatdoweneedtodo?
Thisiseasier,aswejustneedtodevelopasubprocedureforeachtypeofobjecttowhichthemethodwillapply.
Thusinthisstyleofprogramming,addinganewdatatypeispainful,whileaddinganewmethodisreasonable.As
aconsequence,thisapproachtomodularizingsystemsworksbestwhenthereareonlyafewdataabstractionsor
whenthechangesaremostlynewmethodsoroperations,orwhenthedifferentkindsofdatastructuresinthe
systemaremostlyindependentofoneanother.Inthosecases,thisstyleofapproachworkswell.Butnoteverything
fitsthesecases.Whatshouldwedointhosecases?
Slide 13.1.8
Solet'sstepbackfromthisorganizationforasecond.Oneway
tothinkaboutstructuringalargesystemistorealizethatweare
likelytohavealargenumberofdifferentdataobjects(or
instancesofdataabstractions),andalargenumberof
operationswewanttoperformonthoseobjects.Conceptually,
thismeanswehaveabigtable,wherewecanuseadifferent
rowforeachoperationwewanttoperform,andadifferent
columnforeachkindofdataabstractionwehave.Thenateach
elementinthistable,wecanconceptualizehavingaspecific
procedure,intendedtoperformtheparticularoperation(e.g.
scaling)ontheparticularkindofdataobject(e.g.anumber).
6.001StructureandInterpretationofComputerPrograms.Copyright2004byMassachusettsInstituteofTechnology.
Slide 13.1.9
Onewayofactuallybuildingsuchasystemistofocusonthe
rowsofthetable,thatistheoperations.Indeed,ouruseof
taggeddatawasbasedaroundthisviewpoint,inwhichwe
createdgeneric operationsthathandlethesameoperationfor
differentdataobjects,andusedthetagonthedataobjectto
dispatchtotheappropriateversionoftheproceduretohandle
thatkindofdata.
Slide 13.1.10
Butgiventhistable,thereisanalternativepossible
organization,whichisaroundthecolumnsofthetable.This
wouldfocusoncreatingageneric data objectthatwouldknow
howtohandledifferentoperationsonthatkindofdata
structure.
Slide 13.1.11
Let'sstepbackandrethinkdata.Thissoundslikeanoddthing
todobutlet'sthinkaboutdatainaverydifferentway.Rather
thanthinkingofdataabstractionsassomeslotsintowhichwe
canputthings,let'sinsteadconsiderdatatobeaprocedurewith
someinternalstate.
Thissoundsstrange!But,whatisaprocedure?Itreallyhastwo
parts:ithasasetofparametersandabodywhichdefinethe
patternofcomputationtoperformasafunctionoftheobjects
passedin;andaswesawintheenvironmentmodel,ithasan
associatedenvironmentwhichcanholdname-valuebindings,
thatis,pairingsofnamesandvalues.
6.001StructureandInterpretationofComputerPrograms.Copyright2004byMassachusettsInstituteofTechnology.
Slide 13.1.12
Sowhat,yousay!Well,wecanusethisideatocapture
informationaboutadatastructure.Inparticular,wecanusea
proceduretorepresentdataobjectswithstate.Whatwouldthat
mean?Itwouldsaythatwecouldusethelocalenvironmentof
theprocedureplusitsparameterstoholdthevaluesofthe
datum,andwecouldcreatelocalprocedureswithinthedata
proceduretomanipulatethesevalues,tochangethestateofthe
object.
Thismeansthattheonlyaccesstothevaluesofthedataobject
willbethroughtheprocedurerepresentingthedata.Thiswould
nicelyencapsulatethedatastructureinsidethisprocedure.
Thisprobablystillsoundsoddsolet'slookataspecific
example.
6.001 Notes: Section 13.2
Slide 13.2.1
Toillustratethisideaofusingaproceduretorepresentadata
structure,anobjectwithstate,let'slookatthefollowing,rather
odd,example.Hereisaverydifferentwayofimplementinga
conscellorapair.Letmestressthatthisisnotthewaythat
Schemenormallyrepresentspairs.Ofcourse,theideaofdata
abstractionisthattheactualimplementationofadatastructure
shouldbeirrelevanttotheuser.Thisexampleisusedtodrive
homeaconceptualpoint.
Here,wehaveimplementedapairasaprocedure!Thusour
fundamentaldatastructureisnowaprocedureratherthansome
storageinmemoryslots.
Slide 13.2.2
Lookatthiscarefully.First,notethatcons,asdefinedhere,
involvestwolambdas.Rememberthatthereisahidden
lambdainsidethesyntacticsugarofthisdefinition.This
meansthatthereisasecondlambda asthebodyofthe
cons andthuswhenweevaluate(cons x y)using
thisparticularimplementation,wegetbackasavalue,a
procedureofoneparameter,msg.
Sowhatdoesthissay?Itsaysthatwhenweuseconswith
thisimplementationourrepresentationforourfundamentalway
ofgluingthingstogetherisnowaprocedureofoneargument.
Sowhatwouldthatcons thingdo?Sinceitisaprocedure,ifwesenditavalue,orifweapplytheprocedureto
asingleargument,notewhatitdoes.Itusesthevalueoftheargument,inthiscaseaparticularsymbol,todecide
6.001StructureandInterpretationofComputerPrograms.Copyright2004byMassachusettsInstituteofTechnology.
whatvaluetoreturn.
Wecallthisstyleofprogramming,message passing,becausetheprocedureacceptsamessageasinput,andthen
doessomethingbasedonthevalueofthatmessage.
Slide 13.2.3
Thislooksabitweird!Ourconstructorforgluingthings
togethergivesusaprocedureastheactualobject.Shouldwe
care?
Ofcourseweknowthatweshouldn'tcare.Tocompletethe
abstractionforapair,wesimplyneedtocreatecarandcdr
tofulfillthecontractoftheabstractionofapair.
Eachofthoseisitselfaprocedurethattakesasinputapair,
whichweknowisaprocedure,andthenappliesthatprocedure
toasingleargument,whichinthiscaseisjustasymbolic
message.Ideally,thatmessageshouldgetbackforusthevalue
weneedtosatisfythecontract.Ifwelookatthisdefinitionfor
car,weseeittakesasinputoneofthesenewpairs,andthenappliesthatpair(aprocedure)tothesymbolcar,
which inprincipleshouldreturnforusthevalueweusedwhenwecreatedthepair.
Notetheotherprocedurewebuilthere.Ourpredicatefortestingwhethersomethingisapairnowreliesonthepair
identifyingitself.Thisistheversionofourtag.Beforeweattachedatagasasymbolonadatastructure.Here,our
tagsarepartoftheprocedure.
Slide 13.2.4
Tocheckitout,let'stakethisstrangeimplementationofpairs
andverifythatthisimplementationsatisfiesthecontractfora
pair.
Slide 13.2.5
Totestthis,letsconstogetherthenumbers1and2,andgivethe
resultingpairthenamefoo.
6.001StructureandInterpretationofComputerPrograms.Copyright2004byMassachusettsInstituteofTechnology.
Slide 13.2.6
Sohereisanenvironmentdiagramthatwouldrepresentthe
stateoftheworld,beforewedothisdefinition.Intheglobal
environment,wewouldhaveabindingforconsasa
procedure,basedonthepreviousslide.
Slide 13.2.7
Whathappenswhenweevaluatethisexpression?Sincecons
isjustaprocedure,evaluating(cons 1 2)saystoapply
theprocedureassociatedwithconstothearguments1and2.
Thus,wedropaframe,scopeitbytheenvironmentpointerof
theprocedure,bindtheformalparameters(xandy)ofthe
proceduretothevaluesofthearguments,andrelativetothat
newframe,andevaluatethebodyoftheprocedure.Thatbody
isitselfalambda!Soitmakesanewprocedureobject,
whoseenvironmentpointerpointstotheframeE1becausethat
iswherethelambdawasevaluated.Then,theprocedure
objectisreturnedasthevalueofthecons.Finally,thedefine bindsfoo intheglobalenvironmenttothis
returnedvalue,thisprocedureobject.
Slide 13.2.8
Noticewhatthisdoes.Itgivesusanobjectinthisenvironment,
wherebyobjectImeanthethingenclosedinred,whichisa
procedurethathasalocalframewithsomebindingsorvalues
withinit.Thus,xbeingboundto1,andy beingboundto2
constituteslocalstateinformation.Thatframeisscopedbythe
globalenvironment,andtheprocedurethatpointstoallofthis
isreferredtobyanameintheglobalenvironment.Thus,from
theperspectiveofauserinteractingattheglobalenvironment,
foo referstoastructurethathaswithinitinformationabout
whatisthefirstpartoftheobject(1)andwhatisthesecond
partoftheobject(2).Itshouldalsohaveinformationabouthow
toextractthosevaluesfromthestructure.
Sothispattern:ofaprocedurethatacceptsmessages,hasaccesstoalocalframewithstateandmethodstoextract
thatlocalstate;isaverycommonpatternthatwearegoingtousealot.
6.001StructureandInterpretationofComputerPrograms.Copyright2004byMassachusettsInstituteofTechnology.
Slide 13.2.9
Nowallwehavetodoischeckthatthecontractholdsforthis
dataabstraction.Indoingso,wewillseehowthisstructureofa
procedurewithaccesstolocalstatecapturesexactlythe
behaviorwewant.
Tocheckthis,letsevaluate(car foo).Weknowthatthis
shouldgetconvertedinto(foo 'car),sohowdoesthis
happen?
Slide 13.2.10
Evaluating(car foo)intheglobalenvironmentsimply
appliestheprocedurethatisthevalueassociatedwithcar to
thevalueoffoowhichistheprocedureobjectshown.Now
thedefinitionofcar showsthatthisreducestoevaluatingthe
bodyofcarnamely(foo 'car)withrespecttosome
newenvironment.
Slide 13.2.11
...andwhatdoesthatdo?Itsaystoapplythevalueassociated
withfoo,whichisaprocedure,sothestandardenvironment
modelsaystodropaframe,andscopeitbytheenvironment
pointeroffoo.ThisisimportantasE3nowpointstoE1.
InsideE3webindtheparametermsg totheargumentcar.
Relativetothisframeweevaluatethebodyoftheprocedure
representedbyfoo.Butthatisjustacond clausethatlooks
atthevalueofmsgandcomparesittoasetofsymbols.Inthis
case,thecond saystoreturnthevalueofxwithrespectto
thisframe,whichisjust1.ThisisexactlywhatIwanted,asit
showsthatmycontractissatisfied.
6.001StructureandInterpretationofComputerPrograms.Copyright2004byMassachusettsInstituteofTechnology.
Slide 13.2.12
Sowhatdoesallthissay?Asidefromshowingthatourcontract
isfulfilled,thatwhatwegluetogetherusingthisversionof
cons wecangetbackapartusingcarorcdr,wehave
alsoseenthiscommonpatternthatwecancreateadataobject
representedasaprocedure.Theprocedurehassomelocalstate
capturedinaframethatisaccessibleonlybythatprocedureand
ithastheabilitytoacceptmessagesandbasedonthose
messagesreturninformationfromthelocalstate.Solet'ssee
howtobuildonthatidea.
Slide 13.2.13
Inthecasewejustconsidered,ourproceduresfordata
structurescouldreturnvaluesasafunctionofinputmessages.
Ifwearegoingtousethisideaofmessage-passingprocedures
torepresentinformation,wealsoneedtohavewaysof
changingthevalueofthestatecapturedbythoseprocedures.In
ourpairexample,hereishowwewoulddothis.
Slide 13.2.14
Let'saddtwomoremessages,ortwomorewaysofdealingwith
messages,toourconstructor,cons:onefordealingwith
mutatingthecarandonefordealingwithmutatingthecdr.
Noticethatinthiscaseweneedsomethingdifferent.Ifthe
cons pair(i.e.oneoftheseprocedures)getsthemessage
set-car!wearegoingtoreturnaprocedurethatwill
takeanewvalueforthecar andchangetheoldvaluetothis
newvalue.
Thisisadifferentbehaviorfrombefore.Nowamessagegetsus
backaprocedureratherthananumber.
6.001StructureandInterpretationofComputerPrograms.Copyright2004byMassachusettsInstituteofTechnology.
Slide 13.2.15
Asaconsequence,theprocedureset-car!musthavea
newform.Asbefore,itwilltakeapairandanewvalueas
arguments,butnowitsendsthepair(thatprocedure)the
messageset-car!,whichgivesustheprocedureneeded
tochangevalues,andwethenapplythatproceduretothenew
value.Youcanseethatthedefinitionaccomplishesexactlythis.
Slide 13.2.16
Solet'stracethisthrough.Hereisadefinitionforbartobe
thecons of3and4,andhereistheglobalenvironmentin
whichwearegoingtodothis.
Slide 13.2.17
Whenweevaluatethisexpressionwesimplygetastructure
similartowhatwesawbefore,abindingofbar toa
procedurewithsomelocalstate.Thus,wehavebarasa
message-passingobject.
Slide 13.2.18
Sonowlet'smutatethisobject.Let'schangethecarpartof
thisobjecttobe0.Thenevaluating(set-car! bar
0)reducestoevaluating((bar 'set-car!) 0)
insomeotherframe.Nowhowdoesevaluatingthisexpression
effecttherightmutation?
6.001StructureandInterpretationofComputerPrograms.Copyright2004byMassachusettsInstituteofTechnology.
Slide 13.2.19
First,weneedtogetthevaluesofthesubexpressionswith
respecttothisframe.Wellbarisboundtoaprocedure,sowe
canapplyittothesymbolset-car!.Thisdropsaframe,
scopedbyE4becausebar'sprocedureisalsoscopedthere.
Withinthatframewebindmsg tothesymbolset-car!
andrelativetothatframeweevaluatethebodyoftheprocedure
bar.Thiswillreturnanexpression(lambda (new-
car) (set! x new-car))tobeevaluatedwith
respecttothisframeE6.
Slide 13.2.20
Nowherecomesthecriticalpoint.Rememberthatweare
evaluatingthebodyofbar withrespecttoE6,whichreduced
toevaluating(lambda (new-car) (set! x
new-car)) withrespecttothisframeE6.
This,ofcourse,createsaprocedureobject,whoseenvironment
pointerisscopedbyE6(andthisisthecrucialpoint!).Notethat
thisnewlycreatedprocedureobjectwillhaveaccesstoE6and
bychainingtoE4.Thisprocedureobjectisthevaluereturned
byevaluating(bar 'set-car!).
Slide 13.2.21
...andthisisexactlywhatIwant.Inowapplythisprocedureto
thevalue0,whichisthelastpartoftheoriginalevaluation.By
environmentmodel,Ijustdropaframe,scopedbyE6,binding
new-cartothevalue0.ThusE7isscopedbyE6,whichinturn
isscopedbyE4.RelativetoE7,Inowevaluatethebodyofthis
procedurethatIjustcreated,andthatsays(set! x new-
car)withrespecttoE7.
Slide 13.2.22
Sonowweevaluatethatset! expressionwithrespecttoE7.
Firstwefindthebindingforx,whichwegetbytracingfrom
E7throughE6toE4.Thenwefindthebindingfornew-
car whichwefindinE7,andthenchangethebindingforx
inE4tothisnewvalue.
Noticehowwehavenowmutatedavalueinthelocalstate
associatedwithbar.Thusourprocedurescannotonly
capturelocalstateinformation,theycanalsosupplyprocedures
forchanginglocalstate.
6.001StructureandInterpretationofComputerPrograms.Copyright2004byMassachusettsInstituteofTechnology.
Slide 13.2.23
Thisiscertainlydifferentfromourearlierdataabstractions.
Nowwehavedataobjectsthatareactuallyprocedures.Acons
pairisnowaprocedure,andcarorcdrissomethingthat
operatesonaprocedure.Butaswehaveseen,thecons,
car, cdrwejustbuiltsatisfythedataabstraction
contract,andthereforebehaveasexpected.Thekeynewthing
wehaveisaprocedurethatrepresentsdata,andtakesmessages
asinputandreturnseitherdatavaluesorproceduresfor
changingdatavalues.Thisisaveryhandyidea,solet's
generalizeit.
Let'screateprivatestatevariables(aswedidearlier)butalso
privateproceduresthatwillbelongtoeachinstanceofthedataabstraction.
Slide 13.2.24
Noticethedifferenceinthisversion.NowIcreateinternal
procedures(change-car, change-cdr)but
insideofmyactualobject,Inotonlycreatethoseprocedures,I
usetheminsidetheobject.ThishasaniceeffectinthatwhenI
executesomeoperationonanobject,Idon'thavetoremember
whattypeofvalueisreturnedbytheobject(e.g.numberversus
procedure).Inallcases,theuseofthedataobjectisidentical.
Thusnowourselectorsandmutatorsperforminauniform
manner.
Before,wehadtorememberwhethertheobjectreturneda
valueoraprocedure,inordertocompleteourmanipulation.
Here,theselectorsandmutatorsjustsendamessagetotheobjectandwithintheimplementationoftheobject,we
takecareofthenecessaryworktoeitherapplyaninternalprocedureortosimplyreturnavalue.
Noticethatbydefiningtheinternalprocedureswithinthecontextoftheconswewillcreateproceduresthatare
scopedwithinthecreatedbycallingthecons.Thus,theseprocedureswillbelongonlytothisinstanceofthe
dataobject.
Bymakingauniforminterfaceformutatorsandselectorswehaveintroducedoneotherthingintooursystem.In
particularwenowneedourselectorsandmutatorstodealwithdifferentnumbersofarguments,andyetwewould
likeourdataabstractiontobeasingleprocedure.Soweneedawayoflettingalambdaspecifythatitwantsto
takeanarbitrarynumberofarguments.Thatisthe"funny"notationyouseeof(lambda (msg .
args) body),whichwedealwithonthenextslide.
6.001StructureandInterpretationofComputerPrograms.Copyright2004byMassachusettsInstituteofTechnology.
Slide 13.2.25
Upuntilnow,everyprocedureyouhavewrittenhasrequired
thatyouspecifynamesofalltheinputparameters,andasyou
haveseen,ifyoucalltheprocedurewiththewrongnumberof
argumentsitcausesanerror.Wewouldlikeamechanismthat
letsaproceduretakeanarbitrarynumberofarguments,suchas
youhavealreadyseenwithbuilt-inprocedureslike+.
Slide 13.2.26
SoSchemeprovidesawayofdoingthis.Toseethis,let's
define(add x y . rest)tobeaprocedurethatis
goingtoaddabunchofthings.Here,thesyntaxisanargument
xanargumenty andthenadot(.)andthentheargument
rest.Andthebehaviorisasfollows:Ifweapplyadd toa
setofarguments,thevalueofthefirstargumentwillbebound
tothevariablex,thevalueofthesecondargumentwillbe
boundtothevariabley andthevaluesoftheanyother
argumentswillbebound,asalisttothevariablerest.
Thusifweevaluate(add 1 2)thenx isboundto1,yis
boundto2,andrestisboundtoanemptylist.Ifwetrytoevaluate(add 1)wewillgetanerror,because
inthisformat,thefirsttwoargumentsarerequired,i.e.wemusthavesomethingforbothxandy.Butifwe
evaluate(add 1 2 3),thenx willbeboundto1,ywillbeboundto2,andrestwillbeboundtothelist
(3).Andifweevaluate(add 1 2 3 4 5)inthiscaserestwillbeboundtothelist(3 4 5).
Thusinthisnotation,alloftheparameterspriortothedotmusthaveavaluepassedin,theparameterafterthedot
willbeboundtothelistofthevaluesofalltheremainingarguments.
Slide 13.2.27
Ifwecomebacktoourexample,weseethatifwejusttakethe
carofapair,msg willbeboundtothesymbolcar,and
restwillbeboundtotheemptylist.Ontheotherhand,ifwe
wanttomutatethecarofapair,thenmsgwillbeboundtothe
symbolset-car!,andargswillbeboundtothelistof
onevalue,thenewvaluetobeused.Withintheprocedurethat
definesthecons,noticewhathappens.Ifwearegoingto
executeaset-car!,weapplytheinternalprocedure
change-cartothefirstvalueinthelistargs.Inother
words,itwillextracttherightvaluetouse,andcausethe
appropriatechange,itwillmutatethebindingofxtobethatnewvalue.Andthuswecanapplytheseinternal
procedurestotheappropriatevalues,whilepreservingauniformexternalinterface.
6.001StructureandInterpretationofComputerPrograms.Copyright2004byMassachusettsInstituteofTechnology.
Slide 13.2.28
Sincewehavebeenthrowingalotofdetailsatyou,let'sstep
backforamoment.Whatwehavenowseenisamethod,using
aparticularexampletoillustrate,forcreatingaprocedurethat
captureslocalstate.Thisproceduretakesinamessage,and
basedonthatmessageandpossiblysomeotherarguments,
eitherreturnsvaluesbasedonthelocalstateoritcauses
changesinthatlocalstate.
Thisnewmethod,thisideaofamessagepassingprocedure,
let'suscaptureinformationaboutadatastructureinsidea
procedureitself.
Slide 13.2.29
Sowhatdoesthissay?Wehaveintroducedthebasicideaofa
newstyleforapproachingcomputationalsystems.Our
traditionalstyleisproceduralprogramming:weorganizethe
systemaroundtheproceduresthatoperateonthedata.Thekey
isthatweisolatethedatainstandardlist-likestructures,with
tags,thenfocusonthinkingaboutwhatmethodsorprocedures
wewanttousetomanipulatethevalueswithinthosestructures.
Slide 13.2.30
Herewehaveshownthebasisforanewapproach,whichis
orientedaroundthedataobjectsthemselves.Notewhatwedid
withourexampleofapair.Wefocusedoncapturingthe
informationwithinastructure,wheretheoperationsto
manipulatethedatawereassociateddirectlywiththatstructure.
Moreimportantly,thebasicconceptualunitwasthedataobject
itself.Whatmessagesshouldanobjecthandle?Whatoperations
shouldanobjectsupport?Howshouldwecapturethose
methodsinternallywithintheobject?
Slide 13.2.31
Sowhichapproachisbetter?Itdependsontheproblem
domain!Proceduralmethodsareverygoodwhenweare
dealingwiththingslikenumericaloperationsorwhenweare
dealingwithsystemswithverysmallnumbersofdata
structures.
Ontheotherhand,objectorientedsystemsareverygoodfor
thingslikesimulationsorforsystemswithlargenumbersof
objects,wheretheobjectsarecharacterizedbyasmallamount
ofstateinformationandthecomputationbasicallyinvolves
interactionbetweentheobjects,causingthatstatetochange.
6.001StructureandInterpretationofComputerPrograms.Copyright2004byMassachusettsInstituteofTechnology.
6.001 Notes: Section 13.3
Slide 13.3.1
Wehaveseenlotsofexamplesofthefirststyleofprogramming
inthefirstpartofthecourse.Nowwearegoingtospendsome
timeexploringthesecondstyle.Whatdoesitmeantocreatean
object-orientedsystem?
Todiscussthis,weneedsometerminology:Inanobject-
orientedsystem,wewilltalkaboutaclassandaninstance.A
classcapturesasetofobjects,withcommonbehavior.For
instance,cons inourpreviousexamplewasaclass.By
convention,touseaclasswewillhaveamakerprocedurethat
createsinstancesofthisclass.
Aninstancewillbeaparticularandspecificversionofaclass.
Forexample,fooorbarinourearlierexampleswereinstancesofthecons class.Aninstancetakes
messagesinthemannerdefinedbythemakerprocedureandusesthemtomanipulatetheparticularvaluesofthe
instance.Soweexpectasaconsequencetohavelotsofinstancesofaparticularclassinoursystem.
Slide 13.3.2
Sohereisagoodwaytoconceptualizetheseideas,andin
particularthedifferencesbetweenthem.Associatedwithaclass
willbeaclass diagram.Thiscontainsinformationsuchasthe
nameoftheclass(pair),theprivatestatethatbelongstothe
class(xandy),aswellaswhatpublicmessagesare
recognizedbythisclass(car, cdr, pair?, set-
car! andset-cdr!).Notethatthesepublicmessages
definetheinterfacetotheclassofobjects.Thisclassdiagram
thuscapturestherelevantinformationaboutaclass.
Slide 13.3.3
Thusinourearlierexample,consdefinesaclass.Our
previousdefinitionforcons isourparticularwayof
implementingthisclass,orconstructingelementsofthisclass.
6.001StructureandInterpretationofComputerPrograms.Copyright2004byMassachusettsInstituteofTechnology.
Slide 13.3.4
Andthatleadsnaturallytotheideaofaninstance.Whenwe
usethemakerassociatedwiththisclass,wecreateparticular
instancesoftheclass,orexamplesfromthisclass.Wecan
representdiagrammaticallyinaninstance diagram.Within
thatdiagram,wewillhaveinformationaboutthetypeofeach
instanceaswellasspecificvaluesfortheinternalstateofeach
instance.Notethatthesevaluescouldthemselvesbeother
instancesofclasses.
Slide 13.3.5
SoifIdefinetheexampleexpressionshown,inmyinstance
diagramIcreatetwoinstancesoftheclasspair,bothcreated
bythemakerprocedurecons.Withineach,Ihavebindings
for,orspecificvaluesfor,theinternalstateassociatedwitheach
instance.Noticehowthesebindingscanbesimplevalueslike
numbersorpointerstootherinstancesofclasses.
Soweseethataclassdefinesasetofobjectsandaninstanceis
aparticularversionofanobjectfromsomeclass.
Slide 13.3.6
SohowdoIusetheideasofclassesandinstancestostart
designingasystem?Let'ssuppose,asanexample,thatIwantto
buildasimulatorforastarwarsgame:itwouldhaveshipsthat
couldflythroughspace,landonplanets,shoototherships.
IcanstartbythinkingaboutwhatkindsofobjectsdoIneed?
ThatwilltellmewhatkindsofclassIneedandwhatstate
informationisneededforaclassandwhatinterfacesbetween
classesareneeded.Itmightsay,forexample,thatIwantsome
ships.Sinceshipswillneedtomove,thishelpsmedecidewhat
kindofstateashipwillneed.
ThusIbeginthinkingaboutthesystemintermsofwhatkinds
ofobjectsandwhatinformationassociatedwiththoseobjects
doIwant.Icanthenextendthistostartthinkingaboutparticularinstancesofobjects.Howmany,whatstatefor
each,andsoon.
Solet'sseehowtheideaofaclass,andinstancesofaclass,canbeusedtodesignanobject-orientedsystem.
6.001StructureandInterpretationofComputerPrograms.Copyright2004byMassachusettsInstituteofTechnology.
Slide 13.3.7
Wewilluseourstarwarssimulatortoexploretheuseofclasses
andinstancesofclassestobuildobject-orientedsystems.The
firstclassofobjectsinmysystemwillbeships.Sohereisa
procedureformakinginstancesoftheclassofships.This
makerproceduredefinestheactualclass.
Slide 13.3.8
Giventheideaofaship,Icanturntothequestionofwhat
behaviorIwantforinstancesofthatclass.Clearlyashipneeds
tobeabletomove.NotethatthisthentellsmethatIwillneed
someinformationaboutwheretheshipcurrentlyliesandhowit
ismoving,aspartoftheclassdefinition.Inthiscase,Ichoose
topassthatinformationin,whenIactuallyconstructthe
instance.SothistellsmeIwillneedposition,
velocity andmaybesomeotherthingsasinputstothe
classconstructor.
Actually,Iamcheatinghere.Iknowthatinordertomove,I
needtohavethatkindofinformationaspartoftheclass,butin
factIcouldhavecreatedaconstructorwithnoparameters,andsimplyhavewithinitaletclausethatcontained
initialdefaultvaluesforthepositionandvelocity.
NoticehowthinkingaboutwhatIwantmyobjectstodohelpsmetodecidewhatinformationshouldbecaptured
aslocalstate,andwhatinformationshouldbepassedinwhenIcreateinstancesofthisclass.
Slide 13.3.9
Andwhatabouttheclassitself?WhenIusethismaker
procedure,itwillreturnaninstanceofaship,whichwillbe
representedbyoneofthesemessage-passinglambdas.
Notetheform.Ittakesasinputamessage,andeitherreturns
informationaboutthestateoftheship,orcausesoneofthe
internalprocedurestobeexecuted.Thislooksalotlikethe
generalizedformweusedforourconspairearlier.
Similarly,wewillhaveinternalproceduresformanipulatingthe
datavalues,verymuchlikeourconsexample.Theonly
otherthingtonoteishowthelastclauseofourmessagepassing
procedureisabailoutclause.Itsays:ifyougivemeamessage
thatIdon'trecognize,I'llletyouknowsothatyoudon'ttrytodosomethingyoucan't.
Thushereisadefinitionofaclass:amakerprocedurethatcreatesships.
6.001StructureandInterpretationofComputerPrograms.Copyright2004byMassachusettsInstituteofTechnology.
Slide 13.3.10
Solet'sgatherthattogetherinourclassdiagram.Hereisthe
classdiagramofaship,basedonthatdefinition,includingstate
variables,andmessagesformanipulatingthosestatevariables.
Thosemessagesnowdefinetheinterfacetoinstancesofthis
class.
Slide 13.3.11
Nowwecanmakesomeinstances,asshown.Ofcourse,weare
assumingsomeabstractionforvectors,whichwecouldeasily
define.Notethatbyusingtheclass'smakerprocedure,Ihave
createddifferentinstances,eachwithitsownstatevariablesand
itsownproceduresformanipulatingthatstateinformation.The
interfacestotheseinstancesaredefinedasthesetofinterfaces
fromtheclassdefinition.Eachoftheseobjectswillacceptthe
samesetofmessages,butcasetheirown internalstateto
change.
Slide 13.3.12
Toseethis,let'suseourenvironmentdiagramtoseehowour
simulationevolves.Wewanttoseebothhowinstancesare
genericallymaintainedinthesystem,aswellasexaminingthe
detailsofourparticularimplementation.Let'sevaluatethese
threeexpressionsinorder,toseehowourclassescreate
instances,andhowthoseinstanceskeeptrackofstate
information,asoursimulationmovesforward.
Slide 13.3.13
First,wewilluseourmake-ship proceduretocreatean
instanceoftheclass.Evaluatingthatfirstexpressioncreatesa
frame,throughtheapplicationoftheprocedure,inwhichthe
formalparametersareboundtothevaluesofthearguments
passedin.
6.001StructureandInterpretationofComputerPrograms.Copyright2004byMassachusettsInstituteofTechnology.
Slide 13.3.14
Havingcreatedthatframe,wethenevaluatethebodyofthe
procedurewithrespecttoit.Notewhatthatdoes.Theinternal
definitionscauseabindingofavariableinthisframetothe
valueshown,inparticular,move getsboundtoaprocedure
whoseenvironmentpointerpointstothisframe.Thus,wehave
aninternalprocedure,whichwillhaveaccesstothelocalstate
variablescapturedinthisframe.
Slide 13.3.15
Thus,thosetwointernaldefines createbindingsfor
namesinthatframethatpointtolocalprocedureswithaccessto
thebindingsofthisframe.Thusthisframecontainsinformation
aboutthisinstanceoftheclass,thestatevariablesandthelocal
methodsthatwillbeusedtochangethosevariables.
Slide 13.3.16
Havingevaluatedthelocaldefines,wethenevaluatethe
restofthebodyofthisconstructor,make-ship.That
evaluatesthatlastlambda,creatingaprocedureobject
whoseenvironmentpointeralsopointstothisframe,anda
bindingforthenameintheglobalenvironmentthatpointsto
thisprocedureobject.Again,wegetamessage-passingobject
withlocalstateandmethodsforchangingthelocalstate.
Slide 13.3.17
Supposeweaskthisparticularinstanceofashiptomove.This
saystosendtheprocedurerepresentingthisshipthemessage
move,andweknowthatthisreducestoevaluatingtheactual
proceduremovewithrespecttothisframe.Applyingthat
procedurecreatesaframe,eventhoughtherearenoarguments
tobind,andrelativetothisframeweevaluatethebodyof
move.Thisthensaystochangetheposition.
6.001StructureandInterpretationofComputerPrograms.Copyright2004byMassachusettsInstituteofTechnology.
Slide 13.3.18
Andofcourseevaluatingthebodyofthisprocedurecausesus
tomutatethecurrentvalueforposition.Justaswesaw
withourconsexample,wehavechangedthestateofour
instance.Thus,ifweaskforthepositionofourobjectnow,we
willgetthisnewvalueastheanswer.
Thus,ourlocalinstanceofashipcaptureswithinitstate
informationandprocedurestochangethatstateinformation.
Theactualinstanceobjectisaprocedurethatusesmessagesto
determinewhattodo.
6.001 Notes: Section 13.4
Slide 13.4.1
Thekeythingtonoteishowwecanuseobjectstomodularize
ourdesign.Noticeinthepreviouscasethatwecanleavesome
methodsblankandstilltestoursystem,aswecanjustfillthese
methodsinwhenweneedthem.Alsonoticehowweusethe
ideaofwhatthingswewantedtheobjecttobeabletodoto
definewhatstateinformationweneeded,andwhatmethodswe
neededtodealwiththatinformation.Solet'sbuildonthisidea
toseewhatothercapabilitieswecanadd,andhowthinking
aboutthingsintermsofclassesofobjectsandinstancesof
thoseclassesallowsustoeasilydesigninteractivesystems.
Slide 13.4.2
Sowhatkindsofthingscouldweaddtooursystem?
First,wecouldaddnewclasses,forexampleaplanetclass,
whichshouldhaveadifferentbehaviorfromships.
Second,weforgottoallowfortypesandtagsinoursystem.
Thismeansweneedtoaddpredicatemessagesandmethodsso
thatobjectscanidentifytheirtype.NotethatthisarisesonceI
addmorethanonekindofobjecttomysystem(e.g.withjust
shipsImightnotneedit,butonceIaddplanetsIhaveto
distinguishbetweentypesofobjects).
Andwemightwantadisplayhandler,somethingthatdrawsthe
positionofmyobjectsonascreen.Thiswewillseecanbe
implementedasaprocedure,sothatnoteverythingneedstobe
anobjectinoursystem.Todothis,wewillneedtomodifyourclassessothateveryobjectcandisplayitselfon
demand.
Withthisframeworkformodifyingoursystem,let'sseehowonegoesaboutextendingobject-orientedsystems.
6.001StructureandInterpretationofComputerPrograms.Copyright2004byMassachusettsInstituteofTechnology.
Slide 13.4.3
Ifweaddplanetstooursystem,wewillhaveanewclass
diagram.Inadditiontoourearlierclass,wenowhaveaclass
forplanets,withsomestateinformationandsomemethodsfor
manipulatingthatinformation.Noticethataspartofourdesign
weaddtwonewthingstoboththisclassandouroriginalship
class:apredicatefortestingtypes,andamethodforhandling
display.
Nowwatchhowwecanaddnewinstancestooursystemand
howwecaneasilyreturntoouroriginaldesignandmodifyitto
addnewcomponentsandmethods.
Slide 13.4.4
Tostart,hereisourmakerprocedurefortheplanetclass.Note
thattheonlylocalinformationisposition andthe
instanceswillrecognizethreemethods.Hereisourfirstversion
ofapredicate:themessageplanet?willreturnthetrue
value,toindicatethatthisobjectisofthattype,hencewehave
anewwayoftaggingobjects.Andnoticehowwecanadd
methodsthatsimplyexecuteaprocedurewithoutreturninga
value.Heredrawisusedforthesideeffectofgraphically
displayingtheplanet.
Noteinparticularhowplanet?isdefiningtheequivalent
ofatypetag.
Slide 13.4.5
Nowthatwehaveseensomesimpleextensionstoourworld,
whatelsecanweadd?Well,theoriginalmotivationfor
buildingthissystemistoenablelargesystemsofdifferent
kindsofobjectstointeract.Wewouldliketosetupoursystem
sothatwecancreateabunchofobjects,initializetheirstate,
andthenlettheobjectsinteractinasimulationofsome
dynamicevolution.
Todothis,wejustaddonenewobject:aclock.Ifwethenkeep
trackofeverythinginouruniverseofinstances,wecanhave
theclocksynchronizetheevolutionofeachobjectbysendingit
amessagetoupdateitsstate,whichitwilldothroughitsown
localprocedure.
Andtoaddsomespicetooursystem,wewillletshipsshootateachother,sowewilladdanewclass,atorpedo.
6.001StructureandInterpretationofComputerPrograms.Copyright2004byMassachusettsInstituteofTechnology.
Slide 13.4.6
Ifweaddtorpedoesweneedtoupdateourclassdiagram,and
hereitis.Noticethatthisclasssharesalotofcommon
informationwithships,apointtowhichwewillreturnlater.
Thetoplevelpointtonoteishowourdesignisevolving.We
startedwithasingleclass,andhavenowaddednewclassesas
ourdesiresforthesystemexpand.Eachclasshasasetoflocal
statevariables,andmethodsthatitiscapableofhandling.
Theotherchangetoourclassdiagramistheinclusionofanew
methodforeachobject,theabilitytoacceptasynchronization
signalfromtheclock,andthenupdatestate.
Again,notehowourdesignisevolving.Wecanaddnew
classes,andwecanextendexistingclassesbyaddingnew
methodsasourdesiredbehaviorsforthesystemdemandthem.
Slide 13.4.7
Wealsoneedawayofcoordinatingtheactionsandinteractions
ofobjectsinouruniverse. Onewaytodothisistouseaclock,
whichcouldsendasignaltoeachobjecttosynchronizethe
passageoftime. Forexample,aclocktickcouldcauseaship
tomoveasmallamount,orfireatorpedo,orlaunchashuttle.
Thereareseveralwaystoaccomplishthis;hereisasketchof
one. Ourclockmaintainsalistofthingstodooneachtickof
theclock. Inparticular,itdoesthisbystoring,asinternalstate,
alistofcallbacks,thatis,messagestosendtospecificobjects
toexecutespecificactions.
Wecanthensimulateourworldbyrunningtheclockthrougha
sequenceofticks. Oneachtick,theclockwalksdownitslistof
callbacks,andaskseachtoactivate. Intuitively,thismeansthatitasksasetofobjectstopassmessagestotarget
objects,likeourships.
Slide 13.4.8
Tomakethishappen,wesimplyneedtocreateanewobject,a
callback. Thisissimplyanewobjectthatstoresatarget
object,amessageandasetofarguments. Whenactivated(by
theclock),itsendsthetargetobjectthemessage,whichwill
causesomethingtohappenintheworld. Itcanbethoughtofas
abuttonthatexecutesanactioneverytickoftheclock. The
detailsarenotcrucial,whatmattersistheideathatasingle
object,aclock,cancontrolanothersetofobjects,the
callbacks,thatsynchronizetheactionsofobjectsinthe
universe.
6.001StructureandInterpretationofComputerPrograms.Copyright2004byMassachusettsInstituteofTechnology.
Slide 13.4.9
Wecanalsoevolveourclassdefinitions.Giventhatwewantto
addsomenewcapabilitiestoourships,wereturntothemaker
procedureandchangeit.Forexample,wecanaddamethodto
firetorpedoes,togetherwithmethodsthatupdatethestate
associatedwithtorpedoes.Alsonoteaspartofthishowweuse
amakertocreateatorpedo,andaddingthetorpedotothe
universewillpresumablycausethetorpedotosendacallback
messagetotheclocksothattheclockcankeeptrackofit.
Wealsoneedtoallowshipstoexplode,andnoticetheform
here.Theactualprocedureexplode takesasargumenta
ship,whichneedstoberemovedfromtheuniverse.Noticehow
tosupportthiswehavechangedthedefinitionofourmessage
passingobjecttousethat"dotted"argumentnotation,sothatwecanpassinarbitrarynumbersofargumentstoan
object.Weusethatheretoallowforthefactthatifsomethingcollidesinouruniverse,weasktheobjectto
"explode"andwepassinthepointertotheobjectitself.Thus,inthemethod,wecanthenremovethatobjectfrom
theuniverse(ifithasexplodeditshouldn'tstayaroundforfurthersimulation!).Thuswehaveawayofpassing
objectsasargumentstootherobjects.
Finally,notehowwesendacallbackobjecttotheclock,whichwillcreateamessagetobesenttothisobjecton
eachclocktick,inthiscase,justaskingthisshipobjecttomove.
Slide 13.4.10
Sowearealmostdone.Weneedtohavesomethingthatmakes
instancesoftorpedoes.Notethatithasalotofthesameformas
aship,buthasitsowninternalproceduresforexplodingandfor
moving.
Slide 13.4.11
Havingdoneallofthis,wecannowrunalittlesimulation.We
createsomeinstancesofobjects,weaddthemtothisuniverse,
andthenjustruntheclocktostartthesimulation.
6.001StructureandInterpretationofComputerPrograms.Copyright2004byMassachusettsInstituteofTechnology.
Slide 13.4.12
Soherearethekeymessagestotakeawayfromthisexercise.
You might also like
The Subtle Art of Not Giving a F*ck: A Counterintuitive Approach to Living a Good Life
From Everand
The Subtle Art of Not Giving a F*ck: A Counterintuitive Approach to Living a Good Life
Mark Manson
4/5 (6129)
Principles: Life and Work
From Everand
Principles: Life and Work
Ray Dalio
4/5 (627)
The Gifts of Imperfection: Let Go of Who You Think You're Supposed to Be and Embrace Who You Are
From Everand
The Gifts of Imperfection: Let Go of Who You Think You're Supposed to Be and Embrace Who You Are
Brené Brown
4/5 (1148)
Never Split the Difference: Negotiating As If Your Life Depended On It
From Everand
Never Split the Difference: Negotiating As If Your Life Depended On It
Chris Voss
4.5/5 (934)
The Glass Castle: A Memoir
From Everand
The Glass Castle: A Memoir
Jeannette Walls
4/5 (8215)
Grit: The Power of Passion and Perseverance
From Everand
Grit: The Power of Passion and Perseverance
Angela Duckworth
4/5 (631)
Sing, Unburied, Sing: A Novel
From Everand
Sing, Unburied, Sing: A Novel
Jesmyn Ward
4/5 (1253)
The Perks of Being a Wallflower
From Everand
The Perks of Being a Wallflower
Stephen Chbosky
4/5 (8365)
Shoe Dog: A Memoir by the Creator of Nike
From Everand
Shoe Dog: A Memoir by the Creator of Nike
Phil Knight
4.5/5 (860)
Her Body and Other Parties: Stories
From Everand
Her Body and Other Parties: Stories
Carmen Maria Machado
4/5 (877)
The Hard Thing About Hard Things: Building a Business When There Are No Easy Answers
From Everand
The Hard Thing About Hard Things: Building a Business When There Are No Easy Answers
Ben Horowitz
4.5/5 (361)
Hidden Figures: The American Dream and the Untold Story of the Black Women Mathematicians Who Helped Win the Space Race
From Everand
Hidden Figures: The American Dream and the Untold Story of the Black Women Mathematicians Who Helped Win the Space Race
Margot Lee Shetterly
4/5 (954)
Steve Jobs
From Everand
Steve Jobs
Walter Isaacson
4/5 (2923)
Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future
From Everand
Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future
Ashlee Vance
4.5/5 (484)
The Emperor of All Maladies: A Biography of Cancer
From Everand
The Emperor of All Maladies: A Biography of Cancer
Siddhartha Mukherjee
4.5/5 (277)
A Man Called Ove: A Novel
From Everand
A Man Called Ove: A Novel
Fredrik Backman
4.5/5 (4972)
Angela's Ashes: A Memoir
From Everand
Angela's Ashes: A Memoir
Frank McCourt
4.5/5 (444)
Brooklyn: A Novel
From Everand
Brooklyn: A Novel
Colm Toibin
3.5/5 (2061)
The Art of Racing in the Rain: A Novel
From Everand
The Art of Racing in the Rain: A Novel
Garth Stein
4/5 (4281)
The Yellow House: A Memoir (2019 National Book Award Winner)
From Everand
The Yellow House: A Memoir (2019 National Book Award Winner)
Sarah M. Broom
4/5 (100)
The Little Book of Hygge: Danish Secrets to Happy Living
From Everand
The Little Book of Hygge: Danish Secrets to Happy Living
Meik Wiking
3.5/5 (447)
Yes Please
From Everand
Yes Please
Amy Poehler
4/5 (1987)
Devil in the Grove: Thurgood Marshall, the Groveland Boys, and the Dawn of a New America
From Everand
Devil in the Grove: Thurgood Marshall, the Groveland Boys, and the Dawn of a New America
Gilbert King
4.5/5 (278)
The World Is Flat 3.0: A Brief History of the Twenty-first Century
From Everand
The World Is Flat 3.0: A Brief History of the Twenty-first Century
Thomas L. Friedman
3.5/5 (2283)
Bad Feminist: Essays
From Everand
Bad Feminist: Essays
Roxane Gay
4/5 (1068)
The Outsider: A Novel
From Everand
The Outsider: A Novel
Stephen King
4/5 (1993)
The Woman in Cabin 10
From Everand
The Woman in Cabin 10
Ruth Ware
3.5/5 (2641)
A Tree Grows in Brooklyn
From Everand
A Tree Grows in Brooklyn
Betty Smith
4.5/5 (1936)
The Sympathizer: A Novel (Pulitzer Prize for Fiction)
From Everand
The Sympathizer: A Novel (Pulitzer Prize for Fiction)
Viet Thanh Nguyen
4.5/5 (125)
A Heartbreaking Work Of Staggering Genius: A Memoir Based on a True Story
From Everand
A Heartbreaking Work Of Staggering Genius: A Memoir Based on a True Story
Dave Eggers
3.5/5 (692)
Team of Rivals: The Political Genius of Abraham Lincoln
From Everand
Team of Rivals: The Political Genius of Abraham Lincoln
Doris Kearns Goodwin
4.5/5 (1912)
Wolf Hall: A Novel
From Everand
Wolf Hall: A Novel
Hilary Mantel
4/5 (4074)
On Fire: The (Burning) Case for a Green New Deal
From Everand
On Fire: The (Burning) Case for a Green New Deal
Naomi Klein
4/5 (75)
Fear: Trump in the White House
From Everand
Fear: Trump in the White House
Bob Woodward
3.5/5 (830)
Manhattan Beach: A Novel
From Everand
Manhattan Beach: A Novel
Jennifer Egan
3.5/5 (901)
Rise of ISIS: A Threat We Can't Ignore
From Everand
Rise of ISIS: A Threat We Can't Ignore
Jay Sekulow
3.5/5 (143)
John Adams
From Everand
John Adams
David McCullough
4.5/5 (2544)
The Light Between Oceans: A Novel
From Everand
The Light Between Oceans: A Novel
M L Stedman
4.5/5 (790)
The Unwinding: An Inner History of the New America
From Everand
The Unwinding: An Inner History of the New America
George Packer
4/5 (45)
Little Women
From Everand
Little Women
Louisa Alcott
4/5 (105)
The Constant Gardener: A Novel
From Everand
The Constant Gardener: A Novel
John le Carré
3.5/5 (109)
Related titles
Click to expand Related Titles
Carousel Previous
Carousel Next
The Subtle Art of Not Giving a F*ck: A Counterintuitive Approach to Living a Good Life
From Everand
The Subtle Art of Not Giving a F*ck: A Counterintuitive Approach to Living a Good Life
Principles: Life and Work
From Everand
Principles: Life and Work
The Gifts of Imperfection: Let Go of Who You Think You're Supposed to Be and Embrace Who You Are
From Everand
The Gifts of Imperfection: Let Go of Who You Think You're Supposed to Be and Embrace Who You Are
Never Split the Difference: Negotiating As If Your Life Depended On It
From Everand
Never Split the Difference: Negotiating As If Your Life Depended On It
The Glass Castle: A Memoir
From Everand
The Glass Castle: A Memoir
Grit: The Power of Passion and Perseverance
From Everand
Grit: The Power of Passion and Perseverance
Sing, Unburied, Sing: A Novel
From Everand
Sing, Unburied, Sing: A Novel
The Perks of Being a Wallflower
From Everand
The Perks of Being a Wallflower
Shoe Dog: A Memoir by the Creator of Nike
From Everand
Shoe Dog: A Memoir by the Creator of Nike
Her Body and Other Parties: Stories
From Everand
Her Body and Other Parties: Stories
The Hard Thing About Hard Things: Building a Business When There Are No Easy Answers
From Everand
The Hard Thing About Hard Things: Building a Business When There Are No Easy Answers
Hidden Figures: The American Dream and the Untold Story of the Black Women Mathematicians Who Helped Win the Space Race
From Everand
Hidden Figures: The American Dream and the Untold Story of the Black Women Mathematicians Who Helped Win the Space Race
Steve Jobs
From Everand
Steve Jobs
Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future
From Everand
Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future
The Emperor of All Maladies: A Biography of Cancer
From Everand
The Emperor of All Maladies: A Biography of Cancer
A Man Called Ove: A Novel
From Everand
A Man Called Ove: A Novel
Angela's Ashes: A Memoir
From Everand
Angela's Ashes: A Memoir
Brooklyn: A Novel
From Everand
Brooklyn: A Novel
The Art of Racing in the Rain: A Novel
From Everand
The Art of Racing in the Rain: A Novel
The Yellow House: A Memoir (2019 National Book Award Winner)
From Everand
The Yellow House: A Memoir (2019 National Book Award Winner)
The Little Book of Hygge: Danish Secrets to Happy Living
From Everand
The Little Book of Hygge: Danish Secrets to Happy Living
Yes Please
From Everand
Yes Please
Devil in the Grove: Thurgood Marshall, the Groveland Boys, and the Dawn of a New America
From Everand
Devil in the Grove: Thurgood Marshall, the Groveland Boys, and the Dawn of a New America
The World Is Flat 3.0: A Brief History of the Twenty-first Century
From Everand
The World Is Flat 3.0: A Brief History of the Twenty-first Century
Bad Feminist: Essays
From Everand
Bad Feminist: Essays
The Outsider: A Novel
From Everand
The Outsider: A Novel
The Woman in Cabin 10
From Everand
The Woman in Cabin 10
A Tree Grows in Brooklyn
From Everand
A Tree Grows in Brooklyn
The Sympathizer: A Novel (Pulitzer Prize for Fiction)
From Everand
The Sympathizer: A Novel (Pulitzer Prize for Fiction)
A Heartbreaking Work Of Staggering Genius: A Memoir Based on a True Story
From Everand
A Heartbreaking Work Of Staggering Genius: A Memoir Based on a True Story
Team of Rivals: The Political Genius of Abraham Lincoln
From Everand
Team of Rivals: The Political Genius of Abraham Lincoln
Wolf Hall: A Novel
From Everand
Wolf Hall: A Novel
On Fire: The (Burning) Case for a Green New Deal
From Everand
On Fire: The (Burning) Case for a Green New Deal
Fear: Trump in the White House
From Everand
Fear: Trump in the White House
Manhattan Beach: A Novel
From Everand
Manhattan Beach: A Novel
Rise of ISIS: A Threat We Can't Ignore
From Everand
Rise of ISIS: A Threat We Can't Ignore
John Adams
From Everand
John Adams
The Light Between Oceans: A Novel
From Everand
The Light Between Oceans: A Novel
The Unwinding: An Inner History of the New America
From Everand
The Unwinding: An Inner History of the New America
Little Women
From Everand
Little Women
The Constant Gardener: A Novel
From Everand
The Constant Gardener: A Novel