Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Function values

Exercise 1: Filter List with Function Parameter

Task: Implement a function filterList that takes a List[Int] and a predicate function from Int to Boolean. It should return a new list containing only the elements that satisfy the predicate.

Exercise 2: Implement a Custom map Function

Task: Define a function mapList that behaves like the map method for lists. It should take a List[A] and a function from A to B, and return a List[B].

Exercise 3: A Higher-order Function that Returns a Function

Task: Write a higher-order function multiplier that takes an Int and returns a new function that takes an Int and multiplies it by the first number.

Exercise 4: Sorting with a Custom Comparator

Task: Write a function sortWithFunction that takes a List[A] and a comparison function (A, A) => Boolean which returns true if the first element should come before the second. It should return a list sorted according to this function.

Solutions

Exercise 1: Filter List with Function Parameter

def filterList(lst: List[Int], predicate: Int => Boolean): List[Int] = lst.filter(predicate)

// Test
println(filterList(List(1, 2, 3, 4, 5), _ % 2 == 0)) // Should print: List(2, 4)

Exercise 2: Implement a Custom map Function

def mapList[A, B](lst: List[A], func: A => B): List[B] = lst.map(func)

// Test
println(mapList(List("1", "2", "3"), _.toInt)) // Should print: List(1, 2, 3)

Exercise 3: A Higher-order Function that Returns a Function

def multiplier(factor: Int): Int => Int = number => number * factor

// Test
val triple = multiplier(3)
println(triple(5)) // Should print: 15

Exercise 4: Sorting with a Custom Comparator

def sortWithFunction[A](lst: List[A], comparator: (A, A) => Boolean): List[A] = lst.sortWith(comparator)

// Test
println(sortWithFunction(List(3, 1, 4, 2), (x: Int, y: Int) => x < y)) // Should print: List(1, 2, 3, 4)