Scala to compare two lists?

If I donโ€™t see if each item in the list matches the correct item in the same index in another list, can I use forall to do this? For example, something like

val p=List(2,4,6) val q=List(1,2,3) p.forall(x=>x==q(x)/2) 

I understand that x is not an q index, and I have this problem, is there any way to make this work?

+5
source share
3 answers

The most idiomatic way to deal with this situation is to fasten two lists:

 scala> p.zip(q).forall { case (x, y) => x == y * 2 } res0: Boolean = true 

You can also use zipped , which may be slightly more efficient in some situations, and also allow you to be more concise (or perhaps just confusing):

 scala> (p, q).zipped.forall(_ == _ * 2) res1: Boolean = true 

Note that both of these solutions silently ignore additional elements if the lists do not have the same length, which may or may not be what you want.

+10
source

Best use zip

 p.zip(q).forall{case (fst, snd) => fst == snd * 2} 
+2
source

The sequences from the scala collection library have a corresponds method that does exactly what you need:

 p.corresponds(q)(_ == _ * 2) 

It will return false if p and q have different lengths.

+1
source

Source: https://habr.com/ru/post/1216213/


All Articles