Chapters

Hide chapters

Functional Programming in Kotlin by Tutorials

Before You Begin

Section 0: 5 chapters
Show chapters Hide chapters

Section I: Functional Programming Fundamentals

Section 1: 8 chapters
Show chapters Hide chapters

Appendix

Section 4: 13 chapters
Show chapters Hide chapters

A. Appendix A: Chapter 1 Exercise Solutions
Written by Massimo Carli

Heads up... You're reading this book for free, with parts of this chapter shown beyond this point as scrambled text.

Exercise 1.1

Implement the function sumInRange that sums the values in a List<String> within a given interval. The signature is:

 fun sumInRange(input: List<String>, range: IntRange): Int

Exercise 1.1 solution

A possible solution is the following:

fun sumInRange(input: List<String>, range: IntRange): Int = // 1
  input
    .filter(::isValidNumber) // 2
    .map(String::toInt) // 3
    .filter { it in range } // 4
    .sum() // 5
fun main() {
  println(sumInRange(listOf("1", "10", "a", "7", "ad2", "3"), 1..5))
}
4

Exercise 1.2

Implement chrono, which accepts a function of type () -> Unit as input and returns the time spent to run it. The signature is:

fun chrono(fn: () -> Unit): Long

Exercise 1.2 solution

A possible implementation for chrono is the following:

fun chrono(fn: () -> Unit): Long { // 1
  val start = System.currentTimeMillis() // 2
  fn() // 3
  return System.currentTimeMillis() - start // 4
}
fun main() {
  val waitOneSec = { Thread.sleep(1000) } // 1
  println(chrono(waitOneSec)) // 2
}
1005
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.
© 2023 Kodeco Inc.

You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.

Unlock now