9.2 The previous example demonstrates that higher-order functions can help reduce code duplication when you implement the API. Another important application of higher-order functions is to put them in the API to make the client code more concise. A good example is provided by the specific purpose loop method of the Scala collection type. These specific use cycle methods are defined in trait iterable, List,set,array, and map extensions. Many have been listed in Table 3.1 of chapter Iii. But now, notice one of the examples to see why these methods are so useful.
Consider exists, a method that determines whether an incoming value is contained in a collection. Of course you can also initialize a var as false, loop through the collection type, check each element, and if you find what you're looking for, set Var to true, and look for elements in this way. The following is a way to determine whether the incoming list contains a negative example:
def Containsneg (Nums:list[int]): Boolean = {
var exists = False for
(Num <-nums)
if (Num < 0)
exists = True
exists
}
If you define this method in an interpreter, you can call it this way:
Scala> Containsneg (List (1, 2, 3, 4))
Res0:boolean = False
scala> Containsneg (List (1, 2, 3,-4))
R Es1:boolean = True
But the simpler way to define this approach is to call higher-order function exists on the incoming list, such as:
def Containsneg (nums:list[int]) = nums.exists (_ < 0)
This version of Containsneg can produce the same results as the previous one:
Scala> Containsneg (Nil)
Res2:boolean = False
scala> Containsneg (List (0, 1,-2))
Res3:boolean = True