Using Scala to achieve the difference between adjacent elements in a set

Source: Internet
Author: User

Welcome reprint, Reprint please indicate the source, emblem Shanghai one lang.

Profile

Code this thing, do not write definitely not, the newly-learned Scala soon, will actually encounter some problems recorded, in the future look.

Today is about how to calculate the difference between element 22 in the same set, that is, the Start collection (a,b,c,d) (B-A,C-B,D-C)

Solution
val l1 = 1 to 10 toListval l2 = l1.taill1.zip(l2).map(p=>(p._2 - p._1)

The above code will be able to find the 22 difference value. The meaning of the code is explained slightly:

  1. Tail represents the remaining elements in a collection other than the first element, and is also a collection.
  2. Zip sets up two sets into a set of values, such as the original two sets (A,b,c,d), (1,2,3,4), after using zip, forming ((a,1), (b,2), (c,3), (d,4))
  3. P._1 and P._1 in map operations represent the first and second elements of a tuple
Derivative

Now that the first and remaining elements are spoken, the opposite is certainly the case. Separately quoted as follows

  • Head|tail head represents the header element, and tail represents the remaining collection of elements in addition to the head
  • Init|last last represents the tail element, and Init represents the remaining collection of elements in addition to the tail element

Using Scala to achieve the difference between adjacent elements in a set

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.