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:
- Tail represents the remaining elements in a collection other than the first element, and is also a collection.
- 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))
- 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