用foldLeft求和

时间:2016-10-20 11:56:32

标签: scala

在这段代码中,我试图将两个字符串的xor值相加:

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))

我收到错误消息:

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

当我折叠(Char, Char)时,应该对相应值的xor求和是否有效?

2 个答案:

答案 0 :(得分:3)

问题是a不是Tuple。如果您注释传递给foldLeft的函数,您应该会看到问题:

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))

请记住,a是累加器,b是当前值。您希望累积Int s,因此a必须与您指定的种子(0)具有相同的类型。

当然,您可以在没有明确注释的情况下编写上述内容:

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

更简单的方法是事先将其映射到Int,然后使用sum函数:

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

答案 1 :(得分:0)

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

试试