Upload
tooba-aamir
View
216
Download
0
Embed Size (px)
Citation preview
7/30/2019 Workshop Extra
1/2
QUESTION1Questionabout[a]vs[[a]]vsMaybe[a]vs[Maybea]-whichismostappropriatewhen.EgMattGiuca'sLMSposting:
Let'sassumewe'rewritinga"sportsteamsignupsheet"program,whereaTeamconsistsofanumberofPlayers.Naturally,wewoulddefineitlikethis:
typeTeam=[Player]
ThereisnoimmediatereasontohaveaMaybetypeeitherinsideoroutsideofthelist.Ifyouinsteadmadeit[MaybePlayer],youwouldhavetobeexplicitlycheckingeachentrytoseeifit'sNothingorJust(asanaside,notethatinJavayouwouldalwayshavetocheckfornull--it'sakeyadvantageofHaskell/Mercurythatnullisn'tallowedunlessyouexplicitlydeclaresomethingMaybe).Ifyouwantedtoprintoutthelist,youwouldhavetodeleteallthenon-Nothingentries.And[],[Nothing]and[Nothing,Nothing,Nothing]wouldrepresentthesameteam--sowhyallowthisredundantdatastructure.Similarly,ifyoumadeitaMaybe[Player],nowan"empty"teamcouldberepresentedas"Nothing"or"Just[]",soyouwouldhavespecialcasesfortheemptyteamallovertheplace.
ButtherearesomereasonstocombineaListandaMaybe.Considerthat
thisprogramnowallowsaTeamtobecreated,butitcan'thavePlayersinituntiltheyhavepaidtheirsignupfee.Nowmaybeitmakessensetodefineitas:
typeTeam=Maybe[Player]
ATeamofNothingdoesexist,buthasn'tpaiditssignupfee,sotheplayerlistismorethanjustempty--itisn'tthereatall.ATeamofJust[]haspaidtheirsignupfee,buthasn'tenrolledanyPlayersyet.Theimportantthingisthatboth"Nothing"and"Just[]"haveadistinctmeaning,sotheMaybeListtypeisjustified(thoughthereareprobablybetterwaystorepresentthis).
Alternatively,considerthattheprogramnowallows"undecided"signups--ateamcannominatethattheyintendtoputaplayerinaparticularplace,buthaven'tdecidedonapersonyet.Nowmaybeitmakessensetodefine:
typeTeam=[MaybePlayer]
TheemptyTeam,[],actuallyhasnoplayers.TheTeam[Nothing,Nothing,Nothing]hasthreeplayerspotsnominated,buthavenotappointedanyspecificpeoplethereyet.Still,lengthwilltellustheplannedteamsize.Thisisausefulrepresentation.
Thekeyistoconsider,foreveryvalidvalueofthisdatatype,a)does
itmeansomethingsensible,andb)isittheonlywaytorepresentthatmeaninginthisdatatype.(a)ishighlydesirable,(b)islessdesirablebutstillgood.Again,theyaren'talwayspossible.
QUESTION2Aquestionthatshowscodethatusesavariableinsteadofaconstructorinapattern,leadingtoabug.Askstudentstofindthebug.
QUESTION3Heapimplementation.
7/30/2019 Workshop Extra
2/2
QUESTION4Writedefinitions(assimpleaspossible)oftheHaskellfunctionsmysumandmyproduct,whichreturnthesumandproductofalistofnumbers,respectively.Thesedefinitionshaveasimilarstructure;whatotherdefinitionsyouhaveseenhavethesamestructure?Note:laterwewillconsidera"higherorderfunction"whichallowsyoutowritedefinitionsofsuchfunctionsmuchmoreconcisely.XXXdonotuse:willbediscussedinlectures
ANSWER
>my_sum[]=0>my_sum(x:xs)=x+my_sumxs
>my_product[]=1>my_product(x:xs)=x*my_productxs
Thesehavesimilarstructuretosome_not_pos,all_pos,len(andmanymore):
f[]=BASE_CASEf(x:xs)=SOME_FUNCTIONx(fxs)
QUESTION5Writeafunctioncalledfilter_mapthatdoesthejobsoffilterandmapatthesametime.Thetypeoffilter_mapshouldbe
filter_map::(a->Maybeb)->[a]->[b]XXXdonotuse:willbediscussedinlectures
QUESTION6Usestandardhigherorderfunctionsandoperatorsectionstowritesinglelinedefinitionsofsum,product,all_pos,some_not_posandlength(seequestioninprevioustutorial).Whataretheadvantagesanddisadvantagesofsuchdefinitions.XXXdonotuse:willbediscussedinlectures
ANSWER
Hereweusethe"curried"styleofdefinition,avoidinganyexplicitmentionofthelist,andmakingthedefinitionsevenmoreconcise.Wehaveadded"1"suffixtoavoidnameconflictswithpreviousversions.
>my_sum1=foldr(+)0>my_product1=foldr(*)1>all_pos1=foldr((&&).(>0))True>some_not_pos1=foldr((||).(len1=foldr((+).(const1))0
Anadvantageisthedefinitionsareveryshortandemphasisetheyaresimilarmathematically.Adisadvantageisistheycanberathercryptic,especiallyifyouarenotusedtothisstyle.Itsalwaysimportanttousesensiblenamesforfunctionsandhavecommentsdescribingwhattheycompute.