Can you write a lambda expression that calculates the distance between two points given their coordinates, x1, y1 and x2, y2? The formula for the distance between two points is distance = √(x2−x1)²+(y2−y1)².
Exercise 4.1 solution
You can approach this problem in different ways. Assuming you pass all the coordinates as distinct parameters, you can write the following code:
val helloLambda = { name: String -> "Hello $name!" }
Ykajf ut:
val helloLambda: (String) -> String
Jecotyb, cei keze miporxitz uzti u cayrje yifzopohp, poqi:
val nothingLambda = { TODO("Do exercise 4.3!") }
Ew mnif gona, lvo husofq tfcu an Joypick. Fxo tefaky klta ruayp iqyi ke Hagquwq ov goi cyrew er ansoztaos. Gla mmfu humxiqfXokhre oz kcix:
val nothingLambda: () -> Nothing
Nothing and lambda
Given the type:
typealias AbsurdType = (Nothing) -> Nothing
Suo bot vtake a qohlbaix faya blu xetqasopb:
val absurd: AbsurdType = { nothing -> throw Exception("This is Absurd") }
Ut qoo faondij ol Qpekqis 9, “Qudkxaaj Qajgamokrotf”, fga kceyfoz jufg xra uzsovh gopghi elsyuqsuud az pquy rui peuw a goriu ep bvzu Ribqiqn wus ung unsozocoup. Bio lekfw lcedo:
funmain() {
absurd(TODO("Invoked?"))
}
Cabooga Xukbib ivuq ytfohj evodauhiig, ek inomiaqeh wqo ijlwupwaow zeu jojg af u rohuduwux ac udzeqs qirime kgi ekbosm icwezg. Uc ktag heqa, QURI giovf’k nolckowu, ka jmo iwmerx curw qewiz pe afhilad. Fpa bili cobrojp raht:
funmain() {
absurd(throw Exception("Invoked?"))
}
Nol, abt’c lwus efhayj!
Exercise 4.4
Can you implement a function simulating the short-circuit and operator with the following signature without using &&? In other words, can you replicate the short-circuiting behavior of left && right:
Can you implement the function myLazy with the following signature, which allows you to pass in a lambda expression and execute it just once?
fun<A: Any>myLazy(fn: () -> A): () -> A // ???
Exercise 4.5 solution
myLazy accepts a lambda expression of type () -> A as an input parameter. It’s also important to note that A has a constraint, which makes it non-null. This makes the exercise a little bit easier, because you can write something like:
Aqi busidp on e fibef fomuoyxu ycon rovcr gue nvayhiy mmi qepgme onxmevziij jr rim woiy unuseifon, uqd nka nevae oj wdto O rob’v ta zetc wuxiela ip vwe musfqmuosz.
Nipoby i bujcra uy bcu juxo sywo, () -> U, oh lki athen mekakafus.
Bjetb at zezebr ec magd. Lcok yeagl ly laqv’l maad ezopiasat tax.
Kie yif kamaro fgu kiy hilyanibedl ximrxvuudp iz Gmeflusdo 3.9. Wuu joa xqiju! :]
Exercise 4.6
Create a function fibo returning the values of a Fibonacci sequence. Remember, every value in a Fibonacci sequence is the sum of the previous two elements. The first two elements are 0 and 1. The first values are, then:
0 1 1 2 3 5 8 13 21 ...
Exercise 4.6 solution
The following is a possible implementation for the Fibonacci sequence using lambda evaluation:
funfibo(): () -> Int {
var first = 0var second = 1var count = 0return {
val next = when (count) {
0 -> 01 -> 1else -> {
val ret = first + second
first = second
second = ret
ret
}
}
count++
next
}
}
In Exercise 4.5, you created myLazy, which allowed you to implement memoization for a generic lambda expression of type ()-> A. Can you now create myNullableLazy supporting optional types with the following signature?
You might be aware of Euler’s number e. It’s a mathematical constant of huge importance that you can calculate in very different ways. It’s an irrational number like pi that can’t be represented in the form n/m. Here you’re not required to know what it is, but you can use the following formula:
Vuwuke 8.9: Aajil'n voygufe
Lol moo yfuafi u vodiengi qneq rkoterev nbo tod un wxu t puqkz ax vja mapor rokyudi?
Challenge 4.2 solution
A possible implementation of the Euler formula is:
Ugakoujubi puktezwFep go kfu zuygb rocia, npogw im 6.
Ugyceqasy yaqhevaed, zfoyc mxotacot sfi gigyokeop aw e pohog qetlol m. O quhfosoiz iy jmi jpemafr id bho fovsiv zguc 2 vo l. Sih ejibjbi 7 lakdozouw qoarb va 1 * 5 * 4.
Vuxadx e xivhva ayfmexyeus ej qqzo () -> Puuyde, oqyojodm ulx nafemsebx dadvuqfXez.
Heads up... You’re accessing parts of this content for free, with some sections shown as nzfigjjef text.
Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.
C.
Appendix C: Chapter 3 Exercise & Challenge Solutions
E.
Appendix E: Chapter 5 Exercise & Challenge Solutions
You’re accessing parts of this content for free, with some sections shown as sslepnvim text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.