If I wan't to see if each element in a list corresponds correctly to an element of the same index in another list, could 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 the x isn't an index of of q, and thats the problem I'm having, is there any way to make this work?
The most idiomatic way to handle this situation would be to zip the two lists:
scala> p.zip(q).forall { case (x, y) => x == y * 2 }
res0: Boolean = true
You could also use zipped
, which can be slightly more efficient in some situations, as well as letting you be a bit more concise (or maybe just obfuscated):
scala> (p, q).zipped.forall(_ == _ * 2)
res1: Boolean = true
Note that both of these solutions will silently ignore extra elements if the lists don't have the same length, which may or may not be what you want.
Your best bet is probably to use zip
p.zip(q).forall{case (fst, snd) => fst == snd * 2}
Sequences from scala collection library have corresponds
method which does exactly what you need:
p.corresponds(q)(_ == _ * 2)
It will return false if p
and q
are of different length.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With