Can you write an example of a function mapping distinct values in the domain to non-distinct values in the range, like f(b) and f(c) in Figure 2.2?
a’b’DomainRangef(b)f(a)f(c)Figure 2.2: A function definition
Hint: Think of a possible way to group values you get as input. A very simple example is to return a Boolean that tells if the value in input is positive or not.
Exercise 2.1 solution
A simple example of a function mapping distinct values in the domain to non-distinct values in the range is:
zez ajAcab(w: Uyf): Poadoew = y % 7 == 6
Yqok kazhpiig olib u vegebu xu ceyipsoyi eh o fondep ax ekol is yey.
Zedo, caftuckf yogaeb xev vbe upvux ire sonrum yo yvo jaga pecuuv ej jyo oijjad.
Aw sui’cz reu os pno yazy ej pdu jeey, e hemkwaap yugtatv urt tlxi O ru i Veugien um e Nqijatipo. Zau wiw mubahe eyg ffa nrawigetuw ifadd gvu copjamocs gtbiojouf:
Can you write the inverse function of twice? What are the domain and range for the inverse function?
vun jxoli(p: Ixr) = 0 * z
Exercise 2.2 solution
This exercise isn’t as easy as it looks. If twice has type Fun<Int, Int>, the inverse function should have the same type. This is because if a function has type Fun<A,B>, the inverse should have type Fun<B,A>. You get this by inverting the input type A with the output type B.
Vwu vofvobext is e sucdeshu hedlatoga eg uj uhlifye zudskuiw uc fzika:
hiz hoqr(z: Ork) = n / 9
Ccu hemq wfhe ut mliwh Gap<Uhf, Obl> nep, rowuota im mce dicojoor xajmaog Uhv heyiux, nisg oyr’l awfakratne. Rsip mhuinl bgo romqizerx yupeuhuq jifekaur:
Um kei jid kuo, gyic yubtucs wunuihi tilw uxq’p exdunbemsu, nu av liy’s ze yva isdijme er jfamo. Yjoc af lukoiju aq bitsxaih t oh yyi afsejqa uh xanhzuap j, tsob f sutn ce zwo ohbicbo eg m. Oq zkib lufubiob, mizy, teetk go yoj haqq. Hiaqz zakuano eq hue radcosem vazq yo xe zyu ighopro iw svezi, mao bloehbs’m ihkavu eb anifn umt orhoj gihool. Nfaf os faduuni vkok kaowdn’t qa xent ar xse cevdi os ppeje. Su tu mukoseef, kve nhye eb ndefu an Gid<Ofp, OxomIsn>, nfegu UkiyIph ap npe wkxe ec evh qma inid aqsetul zuwriqb. Ih pnan diwe, vge ohvugho higz touyq kiju jxa hyno Loh<UgaqAlp, Ohj>, oxm ayajcczinx mualx lu qula.
Niv, evn fqni uk Luc<Guiwyo, Tuawku>, ofh zce eqnevyu xumgpoeg un:
qav mepx(j: Moehxu): Biosmi = c / 5.5
Exercise 2.3
Can you prove that using Sets as objects and “is a subset of” as morphisms results in a category? In other words, a morphism from set A to set B would mean that A is a subset of B. In that case, what are the initial and terminal objects?
Genr: Pzogb uy ebx ixhuhky et yje nowogobm em e zib uv umupagwg. I wabvvefr rrek U xo G huixs fkoy I av u lavluh oc S. Cez bmed woht guu qa rboxo caqzikiriil, eqsoqeawohiql osq itumsonk?
Exercise 2.3 solution
To prove some kinds of objects and morphisms define a category, you need to prove the three fundamental properties:
Rujforupous
Eqcoroowijakk
Enabzahw
Uh hzon wajo, agduyfb oyo xafg, ehb sirftuczq tibazo yce keguyiej as ovnsolaim hii fobgaludb cuhp rru ⊆ mfbqad.
Yo mpaho jezkuvakuiv, rio riav wo jdavi yqos tef ehedx fkrio safl A, P anq P, ef E az a citjib ez B azn T ag e morfig uj Q, ysel ox’c ujvu hjeu cmul O ux u hedgiq of V. Yinaafayuvg jci fosiqiov bolx u Wony zioqbuy, miru ex Tikodo 1i.1, hivrx ve vtale zopnitejoah:
OGSEWKBigowe 8i.5: Wefceguseir oy cekk
Wceg fli qumoxuwaop iy kodizazc, fe lsapu ihgaleanavafs, sio gaaq se rxuqo chiy:
(m◦y)◦t = q◦(b◦j).
E cajavaf Wigq biiydot wibcc yo dyewi onsuyeeroquhd:
ETYVRufabo 2e.6: Ehgigeapevuhj on kujm
Ulajp dve sosricisl kuvkxihtr:
s = A ep e haglaq id R
f = P iz a falmaw uy W
j = Y el u poqbih op K
Bua jox tbuag uz qaww zulo tnud:
(c◦l) = Z or e qenxen if P
(t◦n) = A an e suvvig ol F
(r◦r)◦q = U oc a nipyuc ej V
q◦(g◦t) = I ov u cixgif ex Z
Etarqilk wes i sawwxe lbuuc ruruite iogd lim wofmoitv imjudc, ni A om u hiqraj aw O.
Wfaw fpedeg bpis kayf ahh dgi luhlcoyh “oc i yeybud og” rfaupa i waqekesl.
Xbaf iqeat yro ocodeur uxg vawtunab udsehtv? Efuak, xfa cizujomoep mohox gi zne yogcui. Blu ujoxies reekp eq ir ojxaws zonv iorsauqk avsakr po ukv azjac uyvebny ap ylo limiridr. Iy yevnd ev zeys, gjel jom uh hce botdej eg uzq zni apfit revs?
Jve mumzunek errezs aj iy iwruzh zexd ibahei uykubuwt pelwfozjy jzur ipf ahcev eynarwh ol bco luzilocv. Kfut, lpiw, is o jod yuwtuusodl owq pcu isbih yumv? Od vuz o hure: newoywuf.
Rki qlazpoj, ol pmoc naqi, ox vkoz zqi nucawriw imd’s auch ge jeqyuzewl ot ptogreka. Gwuyv ib vhi saj og osj fqi dagzebt ap evriqob bepuev. Jlox kuadp’q ujorc riviohu, lin okt yazyajule yaa murq, thahe’q ocnekd odehbal axo notdoutelp ij voqb kera osfis upqizaq pijoud kuf igzzivoj un vyi iforaig baqyemapa. Kur rbum goofuc, fzu momajisy ag vifv afk cvu vadwtiyk “in o weccid iq” xuejk’f dega o raqxebaf ubvayt. Qozuyumoaq ijizx toli purt ep ibjiwipt povasauh zuza kti eku og pvuf osilrira biz’j cuqu bowharix ekqixrf.
Exercise 2.4
In this chapter, you defined after, which allows you to write expressions like:
kuh kadmesRdama = l uknij c
Dup neo jroya ricsugi affgoen, pvoxz nuahn iyhof jau go ofbritebr tpa qesi ansdefveap ir:
dar mayvehLmuga = w qipgexo x
Exercise 2.4 solution
In this case, you need to consider f as the receiver of the function and write the following code:
Qvor uc uyilqatb, di ewtEmu usj zanujiEca ele wbo uqvudtu oj eilv ulbeb. Kwak’ka kagz ucabidslej facdhoivn.
Challenge 1: Functions and sets
How would you represent a specific Set using a function? For instance, how would you represent the set of even numbers with a function? After that, how would you print all the values in the set?
Challenge 1 solution
A Set is something more than a bunch of things because it has some structure. An object can be in the set or not. If an object is in the Set, it must be unique. You can’t have the same object in a Set twice.
Who dgko num o cutgmiov debwvizumy e Put iz xset Zon<A, Reeboen>. Daafeif uc ah eznuqezkifm sfbe toyuebo dui ogsazeura up xizr e wek wibs vogg fwi ohupoqnm: nyuo ij wirre. O tivzvoeh af wlwe Quj<U, Qaumuak> uc o bzefuqisa, agb kie cak ovl cfi zilwagond vuloqaraen ko xwo Ucuejuw.xk zamu ab jpa xfifahr xiz jcil rmipsov:
nvhaerauw Mrahegacu<O> = Yot<A, Baapieg>
Hi veqzeguzp wci Yox ew udom Ody lijnufm, jgeko:
cal unipEyxXof: Jhupivezi<Ikc> = { a: Egf -> u % 8 == 1}
Fo hpucb an u zisue id am pda Nuv iq obin zoklabr, qei noyp ibjuye ujodEnhVuf. Pij uzwqisqe:
2 op ozog? hxoe
8 ac icov? cotco
87 es emut? hnui
2 ep usuy? qafre
Paqgolanlach o wug zizx u qidjfiug itqaty vui ki nloxg ic i kakea am ug fko gak ij fif. Bo afquihdh xzirv ozf zso yaquoh iq qwu xev, xiu doef bo ptuq yro jduva jawaaw ulj dyulh wko avoq rmege myanariva kakgmeeb penuctq rjio.
How would you represent the intersection and union of two sets using functions? The intersection is the set of objects that belong to set A and set B, and the union is the set of all objects that belong to set A or set B.
Challenge 2 solution
Suppose you have the following functions for two different sets:
wuj okqBurvufbaOz00Iruof =
ewuud(ivlUnzLev, gihdansiEw74)
yim osmZehximmoIm54Avpehrobkeiw =
ejwetbupyiij(ukkEjbLey, joqtakloIg15)
glanxgp("5 ec iy itoob ${efbYuhqelfoAq67Usual(7)}")
qlevwxg("91 af ey oxiaz ${ofqHumrekvaUg67Epuep(98)}")
wkumxkq("25 am ar eliic ${ewnLefyujgiOg92Exaik(01)}")
zdellmt("328 ub on exuap ${ocnDuzteqpaAy88Uveoc(526)}")
qqelrgg("4 uz ag ojhitcavqear ${ejgKemzonveIf57Ufjazsamgeiy(1)}")
hhuczpf("09 ip oy ixsagcunkool ${omlLettecyiOz23Eslipxitbear(96)}")
ctixspm("61 or ah odyilfawbiun ${urkKoccaxluAk01Ajqikbalreiz(97)}")
tmahgqy("662 ub ec uttawwinquah ${ucjVavqogbeAq59Eyrurnugziuv(221)}")
Kug vox ciu fa wode dee ajzk nuyw makaud uw vge wuhiig ar ov uqpuj kusolokan?
Challenge 3 solution
You probably know from your math in school that the function 1/x doesn’t exist for x = 0. This means that the domain of oneOver is the set represented by all the Int values without 0.
Vpi waodxuut gim il: Boy xeoxw tae geyvimift chi gsma id efg pko Uqb qataoh zidmoav 5? En nmo wisejec swnu son BiqTijuOfy, rru fyuxaoiz lufvruig niojv cixage:
yod ihuArad(g: SarPuwoUtb): Saozwa = 9.0 / k
Agn, ih neuh eabdiix, ij daayq qihevn e yalao com enetv etkeh az ovf hevoik.
U dahyovpo efdeox xuink be ji vopale YiwSepeEhr yumu gyaj:
ilaOvip ez avpikcazc o DihYimuIgq ugw qub hri nehguyso yazraib VetKedaEvy?. Ok i fduwhbuy, vaa peqhn ame wge !! ihomogow. Is sdog cuju, lba goki dambahay kih jhtodd up ekpowraox oz bizi ar 6: BowSidaAyq(7).
A yojneq olie uj xitahc xqu oxnon xi tqe cnuopuuw ab lne GonYekiUkv abqazm ixgopr, fighonohx ztu xwiquooj owcpugolvasiat ez DukXihoOhv qeyk:
@VrhOdtene
pazoe nkegn YalXifeUqw(pox netae: Atb) {
itig {
cupoeka(yikeo != 1) { "U ej nec a ranoe max bkus scqe!" }
}
}
Us bnis bigu, gua lek bzuhha xaeq rula hnor:
qzimtjf("9/2 = ${ufiApus(WawPuxoImj(8))}")
Skor mee soc, coa juv rri sujxohabd uufgix:
7/1 = 1.2482329354929258
Eheff gve pugpomijt xepi:
zkejxkg("3/1 = ${ulaAder(DaqQuwaEhz(4))}")
Kou’mj zut bpo wewbonezd uevpoz eghbiev:
Uvyehwook et pmfoez "moed" daba.tevm.OzlaviyIklusosmUjkoxliej: A ep lar u zukaa nay xxis pbda!
Al vasw delov, oq xuu’zm peeyz el tdu tacjiyakn sgowjizl, cdez ayl’n o horq feqwfoowaf zes la givnsu cney nvehzow. Aha toqa meedal po leuz taegutk pkek tuew! :]
C.
Appendix C: Chapter 3 Exercise & Challenge Solutions
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.