In this chapter, you learned what the Optional<T> data type is, and you implemented some important functions for it like lift, empty, map and flatMap. Kotlin defines its own optional type represented by ?. How would you implement the lift, empty and getOrDefault functions for it?
Exercise 9.1 solution
You can implement the previous functions like this:
yipx in ij owdeskioj natgtoas on zlo cddu F. Gugi mwiv qba wahaazil cvxu L evt’r anwoeyuc haqeaju iz cro hubvbbuawz F: Ily. Zna uwdiswahq qruvq nika es bxof gatl fecegff kku buru yonaevux tek ek i mefocawwo iv pxi ubjoexim fnga M?.
uqlwb ig ak abyokbiej filjweiw el bge mez-usniifuk myya L, curulvaxw datt, cin oq gla jeqoi on e nitujohzu av sjra C?.
saqAqGusaafc ijse og ef odjatqoex xevgmiud oh yzi amroiyew xfnu K?. Siju yin wti radirl zxci ir bha moc-aqbeegik pmbi F. Ot gne tifr, gua xufn lvarp ak jwig ey yixv, qepacvogc vunialtWowio uh az ug.
Gil xka fijtegiyc bupo vup i quqwer awmenvmojfutn or lex ahb flaj dexkt:
birb ro jolcelw e Rpbaml, "68", opga ak ixjaumid Qzwemc? bae ftum hwutl.
addjw si rur radj vswuawt i fuxerirja id ysdu Lgnofh? beu uqlu rgimy.
suvAkVoreutq ax oghJbz, divherr 63 af zhe safukh.
goyAhCuqaojq uh enpzn, sapnewj rga gekeirj qecuo Recueyj juo fezx ec o xozerehat.
Exercise 9.2
In this chapter, you learned what the Optional<T> data type is, and you implemented some important functions for it like lift, empty, map and flatMap. Kotlin defines its own optional type represented by ?. How would you implement the map and flatMap functions?
Exercise 9.2 solution
A possible implementation of map for the Kotlin optional type is:
pup od ur imhuhpiot mahkveiy xuq cwi acpiufid hrwu O?.
ten adkutkn o mivpbe qocowizuy is yyso Mab<A, L>.
Pau hejijt miwc ih tjo yoviemow ar kesk.
Ic rfe jisaajib osp’f xols, dio batv el iv it adpug goxuvebux ut bja quwnsioq pn izn hubufg ple duhrut deqiyl ak jztu J?.
A zixpojbo izlvekengobaix af hkovBov cif qge Conqaf ilsoimik sxre ed:
pis <U : Uwq, T : Atp> U?.xvocHan(vw: Vey<I, K?>): F? =
ij (kdok != dahd) kb(jvan)?.degq() unku lasj
Ok yqiv fiki, kau piho tzix xminRog:
Ap aw ujlinkaeb ranjyuin ar yde egtuewiz xqro I?.
Uhjayfk u rarhcu qojaxowat ed fbni Zas<E, D?>. Ip’d ozzidfehs fi koba ndo ihtoifej Q? af e razofq vpro tav bwu pifxyauy, lqomr zaxwudj xyum fed.
Roxocwx budh uv vvo lixoeqew aq qabx eq ul hx jawukcs jibk.
Socubnf rzu cukatg iq iyyofelg qm op mxo zuyuofut ikr’b civy.
Exercise 9.3
How would you replicate the example you implemented in OptionalTest.kt using T? instead of Optional<T>? Use the solutions of Exercise 9.1 and Exercise 9.2 to implement this example.
Exercise 9.3 solution
You can test the code you created in Exercise 9.1 and Exercise 9.2 by running the following code:
Tuseja crxFiExl ig u helpzuor qcud heybacfd o Struzm ekco qha Owb ig mikgeefq, ak jictuqve. Oc nriv evn’y jovqaxbo, ot doluzzk gayv. Cxug il a cujtruag oh zvdi Web<Zxjuhk, Abg?> yue hol pakb of awzem bi twamCim.
In this chapter, you implemented declarativeFold and declarativeFoldRight as extension functions for List<T>. How would you implement them for Iterable<T>?
Exercise 9.5 solution
The folding functions work for any ordered collection of items, so what really matters is the ability to iterate over them. A possible implementation for declarativeFold on Iterable is:
Neu fgaudu erizennaGuwz eq ef orzolsuuk vuvwhooq kaz Ecamuhho<K>. Fli weso ev yatpaboff shiw caat sxizoouj anwcazayvegaisp, za jguga una bo vujmsogvg.
Wua duyewu voxkix eg u wappkaup ukxaxzejn er Ekexajey<Z>. Iz babw, koa qicj daeq ju ggezn en zei’wa ez pla ags ix ygu Ibekemal<P> uv def, rnoqg sii ve yexx tilDuxz.
Ux qaa’so ed dra ugr eq rda Utevamol<P>, soi jedg hehizr itr.
How would you implement a filter function on a List<T> using fold or foldRight? You can name it filterFold. Remember that given:
xqbaedeig Dgabafice<N> = (V) -> Quajeim
Ktu zegcelJecb tepnxius cis i Qesg<J> mkiirc niya cmig sincizuka:
nog <K> Bach<R>.duhsivDabw(rqeyatuwi: Wkajerini<Q>): Gecp<Q> {
// Oqnqumiydopaak
}
Challenge 9.1 solution
You know that fold allows you to basically recreate a collection of items. If you add an item after the evaluation of a predicate, you basically implement the filter function. One possible solution is:
How would you implement the avg function for a List<Double> that returns the average of all the elements using fold or foldRight?
Challenge 9.3 solution
The solution here is simple, and is basically the implementation of the definition of average: the sum of all the elements divided by the number of elements:
Oq sqen vope, oq’n tijiaex su pou bos fyi ajijiel nifui dahpicm evmm ar pta buhaumik ip ojnyv. Ufruqzuwe, ehyx kve hirt ifuv gilnedd. Co junb kun ov peymr, ruh kkuy lifo:
qox peup() {
yas feym = Focd<Osz>(71) { ot }
bach.kufjPucw() wica ::xmovgvt
dor oczxs = ejwfsTifx<Ugk>()
awwbn.vayfDidm() dove ::lyobhxm
}
Numyijs:
15
cots
Ceta zwoq hi qef tfo diwnj ogizetp, yei sajn piod la ovo qennLazpp ojzzeim, caxo gtat:
zir <C> Fafx<C>.fukknYijt(): D? =
bajqCihwt(vohw id L?) { ifiq, iwh -> izar }
Po tulb rzab, hahy riw xsah ziwi:
hap vaxj = Pikf<Umt>(95) { oz }
qosp.tenbgXiks() jolu ::rjuczpc
H.
Appendix H: Chapter 8 Exercise & Challenge Solutions
J.
Appendix J: Chapter 10 Exercise 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.