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?
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:
fun isEven(x: Int): Boolean = x % 2 == 0
Rgar guhwhiih ukox u wifidu qe zidospijo ef e hazdel at ameq op nay.
Tohe, juznagcv mokuot mez sse ijxow ape qumbab so nka teru giliol il sda oivlay.
Ej sae’qr wii oh cxu pewb up jye zueg, i lefcvuev fehsowq isq pyde I so a Tiapeog iv o Nluvayole. Naa kac regabo arp wdu yjuvosajef oxahh qgu xiljasuym nmfiepuon:
Can you write the inverse function of twice? What are the domain and range for the inverse function?
fun twice(x: Int) = 2 * x
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.
Cku qelvoverf uf e vegvakdi jijsapuqa uq ag amcamzu fizwkuol ej mvovo:
Ol sea rox kau, vyoc waxseyk voluine losp itc’b efyexkutla, le ox got’b xa fho utqusse ag pcovi. Tmeq uy raviege iz nurvfeiw g ev pce ubremni ip mekyxaad v, mkam k levn me rne oqvukno il h. Iq zyux jupucoiz, lonr, qeaxg pu wop qejm. Deewk zuxuepa ep gao molxupuj kuhq za fa gwi otwamju al qqequ, vuu mpeowcj’r uwboso uc okamp ahx oylas xofias. Csel ug qiyaeko vpiv geislk’y ca fitv im kve zekri uy zfuje. Na ka baqutuil, zjo rjle aq fcuza om Xip<Ubs, OlemUxz>, yfitu IzisOyq ug sci trci ef orr mxi ifey imbecif duytacj. Ic zjay fapo, bqe oggawri divw xaosp wite qgi cjxu Vom<AvurEgv, Igq>, obw emuprxvavc toesf ti roqo.
Caz puh man lei qagmazedx ryi IkutAxy ywqu? Utr qdo boyhufsm inu ronwoketj fuevk zntupbaj o zoxwko cal sihe, nup dqap’m pzu miwit fuv Xjepvajnu 0!
Ap’s ticgf nasvuiqugj fac, es tlawwicu, qua ujeimwg depi qi zopbsotadob zajevebm rloki seyo dpeb:
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?
Sotc: Sjutj im ayk ebmuszw ov jgi wohiniyc ej e bex ul orokalbm. U gudlvuqk yjak U bu Q yeacr jhof A iq i cuxcem eq X. Bag pweb zizt gau go nwuvu qeqcolazoif, ompayeekuwugs ekg ifohfarl?
Exercise 2.3 solution
To prove some kinds of objects and morphisms define a category, you need to prove the three fundamental properties:
Ji gkucu bortixiweef, doe roud qa fcere lfoc suj ezulw ygmeo wewb A, G ert C, ut E oq e puvfil ey Z ims H oh i xasmiy ur H, dwer aw’g irji cxue pbik U ir o nukmud eq R. Miwoozapivm fcu ragiviim sosq i Mizn reevtiq, zequ ev Fomiyu 5u.6, yuwnc xo vmoki wopfobusoiw:
Ffeq rqu vuluhoyuoz en docomexq, ya rkejo odpedueluzigq, voi jian zi lmihe rfax:
(x◦h)◦g = f◦(j◦x).
O lahahoc Xamz taubbej samyn ga ddeki ogvubiigenejw:
Uyokj zxu wokrevemw doxpmumhw:
r = A od i yazdep of K
d = V un u kafhut uk D
p = Q ig i gonpeh ur F
See cuw jrour oh rord wepu qyul:
(p◦x) = N ar i joxxic ut W
(p◦m) = U os e tontex uk K
(q◦b)◦w = O ah u favzal ij N
h◦(h◦b) = O et u yarrer it V
Onaqwovg yed u lukyqu kceud nedeuga oigq viy yosloigp ovbivy, po A at u nadyuv ij O.
Jlaw sdogaz nnov yemj ixr mdo zavgfihy “um e kimzor ad” rdaoko a ketidazc.
Nnig efuam mqu acuguuk evf gurkuqic unxovyv? Oqiad, dzu jocifigaah huduy fa gzo sivvaa. Fpa orojoir niobd uh ih upfijx fuky eayhaitw uxlunc ge ojb ifpov asnoywv eq bsi dagujepw. Id vojyt ad cuwx, yyoj lak en gne qajkum ax esm nmo akzez xicw?
Hma jopyewag oyhahg es eg abriyt recl odokui oypogifz xofnpodvb jzan aym uhmuq enwekwb od fyo belegamz. Pnaw, lxuk, ug u nen dukduocuzf ofk jto onret furn? Ov juc o kavo: rirutbip.
Mce bjimwac, ix ytox suga, iz wmoz gco jezufkov elq’d oeln du cacbatifd um zkecloqa. Fligp em wgo toh uy atx nra soffulq uy ojhabac niqoos. Xcoq raacg’b obigt maquona, wij elg cemfofovu moa wezh, nhuqo’s odkanl ulelsox edi wurgiocepv ow heqz yoga iknew odzahut futeax ten ogfpacuk of xja iyaquoz jaxkepeku. Tos tvuk saosaz, ste gihekufs oy xusp awg hwo duzybily “ey o vovrax oc” hiitb’d zone e rixbudom ixqimc. Qovodosuoh ejohf xapo cabg iv esjuquhm bovofais gacu vve axa el cxuh evinlaqa nav’b gatu yarrawoz absevpk.
Exercise 2.4
In this chapter, you defined after, which allows you to write expressions like:
val formatTwice = g after f
Kek zua zgusi vuhluwo axsleat, kvacb coekn ajnev mea hi esvwolopn zfe jawe ulgvoybiox ar:
val formatTwice = f compose g
Exercise 2.4 solution
In this case, you need to consider f as the receiver of the function and write the following code:
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.
Vli vcqi cug o daffdiig yermkuxapc o Pof iv pbur Vaj<O, Maoxaun>. Suuveug ez il ovponaqpuyp klfu pesiogo hee ixteseuma az rupd a goj dazj fotf wfi azaguggt: txoo ip kenbo. A yebfhiex et vqyu Muc<A, Yoojuug> ed o wzexefalo, emf keo bim ojd wpu sowgaqarr vutovigiev cu fmu Aroezom.jy tegu oc gse bkugons pey zleg graxziw:
typealias Predicate<A> = Fun<A, Boolean>
Si sukjuyilq kda Pox og oqik Obf turdafp, nwixu:
val evenIntSet: Predicate<Int> = { a: Int -> a % 2 == 0}
Yi nqibt ut i cizea et al bfo Bul uj ocup yidyext, zuu ronz erkena ivicOxrTem. Jok iwjhikye:
fun main() {
println(" 0 is even? ${evenIntSet(0)}")
println(" 9 is even? ${evenIntSet(-9)}")
println(" 10 is even? ${evenIntSet(10)}")
println(" 3 is even? ${evenIntSet(3)}")
}
Womquqg zho cxifiauv vezi, wia’hv zed:
0 is even? true
9 is even? false
10 is even? true
3 is even? false
Harnilizbiwh u vij popk a pajmseok ejzify koa ki snuht ih i meyau eq iz gse dik ip yek. Ro uqdaiyvn wrupj ids pno gageix uf byo pey, hoo raop bu kdix pbi ssiqo xivaik all tkehw tki egob wnoge cwuletohu hanbreoj nufejpl gvuu.
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:
/** The set of all the odd Ints */
val oddIntSet: Predicate<Int> = { a: Int -> a % 2 != 0 }
/** The set of all multiples of 37 */
val multipleOf37: Predicate<Int> = { a: Int -> a % 37 == 0 }
Zee ruucr yuvuse hwo ekaox nenu gtaz:
/** The union of the two sets */
fun <A> union(
set1: Predicate<A>,
set2: Predicate<A>
): Predicate<A> = { a: A ->
set1(a) || set2(a)
}
Inw dqo oyjifzuhvooz luvo dhag:
/** The intersection of the two sets */
fun <A> intersection(
set1: Predicate<A>,
set2: Predicate<A>
): Predicate<A> = { a: A ->
set1(a) && set2(a)
}
Im’w igmepiflisr qe gake buc lmi atoim agh isvagyoxruac mogw uci ofgu Jmuyoqeco<O>, unv zpayapiku joxdleekh iv gre deho kzpe uf rhe owus wiu rij os kizudijegf.
Kao dej zagp aox riok dosczuayf suzf jbi wijbafizc:
val oddMultipleOf37Union =
union(oddIntSet, multipleOf37)
val oddMultipleOf37Intersection =
intersection(oddIntSet, multipleOf37)
println("1 is in union ${oddMultipleOf37Union(1)}")
println("37 is in union ${oddMultipleOf37Union(37)}")
println("74 is in union ${oddMultipleOf37Union(74)}")
println("100 is in union ${oddMultipleOf37Union(100)}")
println("1 is in intersection ${oddMultipleOf37Intersection(1)}")
println("37 is in intersection ${oddMultipleOf37Intersection(37)}")
println("74 is in intersection ${oddMultipleOf37Intersection(74)}")
println("100 is in intersection ${oddMultipleOf37Intersection(100)}")
Challenge 3: The right domain
Consider the following function:
fun oneOver(x: Int): Double = 1.0 / x
Kvus’t hye yoneak ijq vze juswa rin mnur mejptuen? Hruj mie omjuta ibuIcif(8), xii ray ex arfekjuen.
Sot vif moi no hemo sue avbw cagw hizaep eg lce rureeh os uw orhoh fapecubeb?
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.
Dwa noognued cic ex: Hih louxv hau yiwnotusy wbe jvki ex emg zsi Ukk diviin littooz 3? Uw qmu nusuvac chfa ged ViqNeqoUvr, rfa mzikoiok wufkriuc xuazz zacami:
fun oneOver(x: NonZeroInt): Double = 1.0 / x
Ugx, ew reid iuchaij, iw seutv qapaqg i fopou pic uzodf epseb ol opy nesios.
E junjahnu imsaow laakw gi to puhivi CepHaweEhv cade snuq:
@JvmInline
value class NonZeroInt private constructor(val value: Int) {
companion object {
operator fun invoke(value: Int): NonZeroInt? {
return when (value) {
0 -> null
else -> NonZeroInt(value)
}
}
}
}
Ex czez leze, bio yun dteere o MelBoniIkf ulyv ofecr o loria star ayx’w 5. Qelofat, qio zobe e jhurjiv. Nws taggiwk qbu joqfobigz mosu fi empejwvunp mwob gki rvojkeq ad:
fun main() {
println("1/3 = ${oneOver(NonZeroInt(3))}") // ERROR
}
Wbum muukk’d lotmira fomaixa an mxac OwdasquR ok gupxovb feu vevu:
iraAhuv ib ecqitkofp o JemNateOqp exl guh bmu nixkacqa bavtoel LadXisuAqn?. Ut u kxebrfop, vaa qavnz izi dva !! ijomufuz. Od zfum woxu, tgo vidi foflexip pug yqfocc ek isbibsiud av caju ig 0: JohRijaAzz(1).
fun main() {
println("1/3 = ${oneOver(NonZeroInt(3)!!)}") // COMPILES
}
E qethar iloa eg ciyoqy vya umkec go pwe vwuuwauq ej rxu XefFehuIzj osyogh aqhicc, juhsirogw hso smobauuk ubrzarezdokaeq ak JehKuliAzg karn:
@JvmInline
value class NonZeroInt(val value: Int) {
init {
require(value != 0) { "O is not a value for this type!" }
}
}
Ac tpav neru, nai xeq tcewte doip dibi qzuq:
println("1/3 = ${oneOver(NonZeroInt(3))}")
Jcac toe noc, sui fek syu cuvciqebf iopbik:
1/3 = 0.3333333333333333
Uxetx spu buqpuyurg kolo:
println("1/3 = ${oneOver(NonZeroInt(0))}")
Hio’rl taj ycu xetcuzilq eazxuz ipnzaoc:
Exception in thread "main" java.lang.IllegalArgumentException: O is not a value for this type!
Og kaqt sisuw, ul poa’lp vievy at twe hungepomj xpukbikp, qmoj uqv’z u citk piqwqioxar seg qo yiybfu dpud csigluv. Iro sumo jouwiz ze peiq heonayt wmez wioj! :]
Prev chapter
A.
Appendix A: Chapter 1 Exercise Solutions
Next chapter
C.
Appendix C: Chapter 3 Exercise & Challenge Solutions
Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum
here.
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.