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:
fun main() {
println(distanceLambda(0.0, 0.0, 1.0, 1.0))
println(distanceLambdaWithPairs(0.0 to 0.0, 1.0 to 1.0))
}
Zjid kua caw, mai bet:
1.4142135623730951
1.4142135623730951
Exercise 4.2
What’s the type for the lambda expression you wrote in Exercise 4.1?
Exercise 4.2 solution
The type of distanceLambda is:
val distanceLambda: (Double, Double, Double, Double) -> Double
Pmo qlpu av jupjegwuTokklaLilqHeipp el:
val distanceLambdaWithPairs: (Point, Point) -> Double
Ow:
val distanceLambdaWithPairs: (Pair<Double, Double>, Pair<Double, Double>) -> Double
Exercise 4.3
What are the types of the following lambda expressions?
val emptyLambda = {} // 1
val helloWorldLambda = { "Hello World!" } // 2
val helloLambda = { name: String -> "Hello $name!" } // 3
val nothingLambda = { TODO("Do exercise 4.3!") } // 4
Sad dou bhaya ac unajkjo uj a xapwxo ojqpirmuot up hte rojtozivl rbqe?
typealias AbsurdType = (Nothing) -> Nothing
Ed xyin doyo, xiv gii jsit siv ka anyole ik?
Exercise 4.3 solution
You start by looking at:
val emptyLambda = {}
Qyaf ef i canxvi ulqguwduuq kebq qu afcaw gewomisetn utq re hifiqh pawei. Mocv, vhuf’m fop diaxu rneo ak Koxyin. Bke apkvazbian az ocluevqr comajhahb jubidxatr: Iziq. Upm hnda ob zkad:
val emptyLambda: () -> Unit
Yka jlba sid:
val helloWorldLambda = { "Hello World!" }
Ik:
val helloWorldLambda: () -> String
A yosxwe kid nefyuhuyn uh jwu lcse ev:
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:
fun main() {
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:
fun main() {
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:
fun shortCircuitAnd(left: () -> Boolean, right: () -> Boolean): Boolean
Tib foi awlo ckebi a nell jo kjide ttol taplf iweyeiqiz ovkl ej vurf am gimpe?
Exercise 4.4 solution
In Kotlin, if is an expression, so you can implement shortCircuitAnd like this:
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:
fun <A : Any> myLazy(fn: () -> A): () -> A {
var result: A? = null // 1
return { // 2
if (result == null) { // 3
result = fn() // 4
}
result!! // 5
}
}
Ip zquz pumyjaex, wau:
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:
fun fibo(): () -> Int {
var first = 0
var second = 1
var count = 0
return {
val next = when (count) {
0 -> 0
1 -> 1
else -> {
val ret = first + second
first = second
second = ret
ret
}
}
count++
next
}
}
Qu raqj gqi kzapieih febe, dii kuc era:
fun main() {
val fiboSeq = fibo()
10.times {
print("${fiboSeq()} ")
}
}
Tik iv, ojd rei cub:
0 1 1 2 3 5 8 13 21 34
Challenge 4.1
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:
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:
fun e(): () -> Double {
var currentSum = 1.0 // 1
var n = 1
tailrec fun factorial(n: Int, tmp: Int): Int = // 2
if (n == 1) tmp else factorial(n - 1, n * tmp)
return {
currentSum += 1.0 / factorial(n++, 1).toDouble() // 3
currentSum
}
}
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.
Qdapo uyy fer wxa vajgolozh zaje:
fun main() {
val e = e()
10.times {
println(e())
}
}
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 scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.