[英]How to properly use fold left in a scala function
我在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.tail
} else {
(e, 1) :: l
} )
}
val s = List('a', 'b')
val c = times s
}
最后一行给出一个错误:
方法时间缺少参数; 如果要将其视为部分应用的函数,请在此方法后加上“ _”
但是我不知道为什么,因为我给了最后一个函数2个参数-foldLeft。
在此先感谢您的帮助!
代码的想法是计算给定列表中每个字符出现的时间
time的语法很好,但是在调用它时需要使用括号,即:
val c = times(s)
但这是行不通的,因为您在不检查l是否为Nil的情况下使用l.head,并且空列表中没有head。 您可以例如通过匹配检查:
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
val c = times s
没有方括号,就无法调用方法。 尝试times(s)
或this times s
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.