Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala forall to compare two lists?

Tags:

scala

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?

like image 730
ggreeppy Avatar asked Mar 26 '15 17:03

ggreeppy


3 Answers

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.

like image 66
Travis Brown Avatar answered Nov 10 '22 00:11

Travis Brown


Your best bet is probably to use zip

p.zip(q).forall{case (fst, snd) => fst == snd * 2}
like image 22
Justin Pihony Avatar answered Nov 09 '22 23:11

Justin Pihony


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.

like image 2
niktrop Avatar answered Nov 10 '22 00:11

niktrop