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

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)