Summation with foldLeft

In this code, I am trying to sum the xor values ​​of two lines:

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 get an 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

How do I add up (Char, Char)to whether summation of the xor values ​​of the corresponding values ​​should be performed?

+4
source share
2 answers

The problem is that is anot 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 ais the battery, and bis the current value. You want to copy Int, so it amust be of the same type as the specified seed ( 0).

Of course, you could write above without explicit annotations:

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

Int , sum:

val sum = s1.zip(s2)
  .map(cs => cs._1 ^ cs._2)
  .sum
+3
zs.foldLeft(0)((a , b) => a + (b._1 ^ b._2))

0

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


All Articles