Scala Learning: Simplifying Customer code

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.