为什么 foldRight 没有给出正确的计数?
Why is foldRight not giving correct count?
我正在尝试使用 foldRight 和 foldLeft 方法计算列表中的元素数,而 foldLeft 给出了正确的计数 foldRight 没有。我的代码哪里错了?
def count(arr:List[Int]):Int = {
arr.foldRight(0)((B,_) => B+1)
//arr.foldLeft(0)((B,_) => B+1)
}
val countElements = count(1::2::3::4::Nil)
println(countElements)
上面的代码returns 2 for foldRight and 4 for foldLeft.
您已将参数交换为 foldRight
,因为使用 fold right 时元组参数是相反的,因此您要丢弃累加器,而是将 1 添加到最后一个元素(使用 foldRight 是输入中的第一个元素)所以最终结果是2(第一个元素1,加1)
如果你交换这些参数,即 arr.foldRight(0)((_,B) => B+1)
你得到预期的结果 4
我正在尝试使用 foldRight 和 foldLeft 方法计算列表中的元素数,而 foldLeft 给出了正确的计数 foldRight 没有。我的代码哪里错了?
def count(arr:List[Int]):Int = {
arr.foldRight(0)((B,_) => B+1)
//arr.foldLeft(0)((B,_) => B+1)
}
val countElements = count(1::2::3::4::Nil)
println(countElements)
上面的代码returns 2 for foldRight and 4 for foldLeft.
您已将参数交换为 foldRight
,因为使用 fold right 时元组参数是相反的,因此您要丢弃累加器,而是将 1 添加到最后一个元素(使用 foldRight 是输入中的第一个元素)所以最终结果是2(第一个元素1,加1)
如果你交换这些参数,即 arr.foldRight(0)((_,B) => B+1)
你得到预期的结果 4