如何在scala函数中正确使用左折叠
我对scala中的这部分代码有一个问题如何在scala函数中正确使用左折叠,scala,Scala,我对scala中的这部分代码有一个问题 object Test12 { def times(chars: List[Char]): List[(Char, Int)] = { val sortedChars = chars.sorted sortedChars.foldLeft (List[(Char, Int)]()) ((l, e) => if(l.head._1 == e){ (e, l.head._2 + 1) :: l.
object Test12 {
def times(chars: List[Char]): List[(Char, Int)] = {
val sortedChars = chars.sorted
sortedChars.foldLeft (List[(Char, Int)]()) ((l, e) =>
if(l.head._1 == e){
(e, l.head._2 + 1) :: l.tail
} else {
(e, 1) :: l
} )
}
val s = List('a', 'b')
val c = times s
}
最后一行给出了一个错误:
缺少方法时间的参数;如果需要,请使用“\u1”遵循此方法
要将其视为部分应用的函数吗
但我不明白为什么,因为我给了最后一个函数foldLeft两个参数
提前感谢您的帮助
代码的思想是计算每个字符在给定列表中出现的时间
val c = times s
如果没有这样的括号,就不能调用方法。尝试次
或此次
如果没有这样的括号,就不能调用方法。尝试
times(s)
或this times s s
times的语法很好,但调用时需要使用括号,即:
val c = times(s)
但是它不起作用,因为您使用l.head时没有检查l是否为Nil,并且空列表没有head。例如,您可以使用match检查:
def times(chars: List[Char]): List[(Char, Int)] = {
val sortedChars = chars.sorted
sortedChars.foldLeft (List[(Char, Int)]()) ((a,b) => (a,b) match {
case (Nil, e) => (e, 1) :: Nil
case ((e, count) :: l, f) =>
if (e == f) (e, count + 1) :: l
else (f, 1) :: (e, count) :: l
})
}
尽管更简单的方法是使用更高级别的收集功能:
def times(chars: List[Char]) = chars.groupBy(c=>c).map(x=>(x._1,x._2.length)).toList
times的语法很好,但调用时需要使用括号,即:
val c = times(s)
但是它不起作用,因为您使用l.head时没有检查l是否为Nil,并且空列表没有head。例如,您可以使用match检查:
def times(chars: List[Char]): List[(Char, Int)] = {
val sortedChars = chars.sorted
sortedChars.foldLeft (List[(Char, Int)]()) ((a,b) => (a,b) match {
case (Nil, e) => (e, 1) :: Nil
case ((e, count) :: l, f) =>
if (e == f) (e, count + 1) :: l
else (f, 1) :: (e, count) :: l
})
}
尽管更简单的方法是使用更高级别的收集功能:
def times(chars: List[Char]) = chars.groupBy(c=>c).map(x=>(x._1,x._2.length)).toList