blue-sky blue-sky - 1 month ago 6
Scala Question

Summing with foldLeft

In this code I'm attempting to sum the xor values of two Strings :

val s1 = "1c0111001f010100061a024b53535009181c";
val s2 = "686974207468652062756c6c277320657965";
val zs : IndexedSeq[(Char, Char)] = s1.zip(s2);
zs.foldLeft(0)((a , b) => (a._1 ^ a._2) + (b._1 ^ b._2))


I receive error message :

value _1 is not a member of Int
[error] zs.foldLeft(0)((a , b) => (a._1 ^ a._2) + (b._1 ^ b._2))
[error] ^
[error] one error found
[error] (test:compileIncremental) Compilation failed
[error] Total time: 2 s, completed Oct 20, 2016 12:51:11 PM


As I'm folding over
(Char, Char)
should summing over xor of corresponding values be valid ?

Answer

The problem is that a is not a Tuple. If you annotate the function you pass to foldLeft you should see the problem:

val s1 = "1c0111001f010100061a024b53535009181c";
val s2 = "686974207468652062756c6c277320657965";
val zs : IndexedSeq[(Char, Char)] = s1.zip(s2);
val sum = zs.foldLeft(0)((a: Int , b: (Char, Char)) => a + (b._1 ^ b._2))

Remember that a is the accumulator and b is the current value. You want to accumulate Ints so a has to be of the same type as the seed you specify (0).

Of course you could write the above without the explicit annotations:

zs.foldLeft(0)((a, b) => a + (b._1 ^ b._2))

An even easier way would be to map it to an Int beforehand and then use the sum function:

val sum = s1.zip(s2)
  .map(cs => cs._1 ^ cs._2)
  .sum
Comments