Scala实现了Haskell的groupBy

San*_*der 6 haskell scala

我正在寻找Haskell的groupBy的Scala实现.

行为应该是这样的:

isD :: Char -> Bool
isD c = elem c "123456789-_ "

groupBy (\a b -> isD a == isD b) "this is a line with 0123344334343434343434-343 3345"
["this"," ","is"," ","a"," ","line"," ","with"," 0123344334343434343434-343 3345"]
Run Code Online (Sandbox Code Playgroud)

我尝试了Scala groupBy函数,但它只需要一个参数的函数,而不是Haskell的2.我也查看了分区,但它只返回一个元组.

我正在寻找的函数应该对每个与谓词匹配的连续元素进行分组.

Lui*_*hys 2

类似这样的问题似乎经常出现,这在我看来是一个很好的迹象,表明 Rex Kerr 的groupedWhile方法应该包含在标准集合库中。但是,如果您不想将其复制/粘贴到您的项目中......

我喜欢你的递归解决方案,但它实际上并没有输出正确的东西(即字符串),所以我将如何更改它:

def groupBy(s: String)(f: (Char, Char) => Boolean): List[String] = s match {
  case "" => Nil
  case x => 
    val (same, rest) = x span (i => f(x.head, i))
    same :: groupBy(rest)(f)
}
Run Code Online (Sandbox Code Playgroud)

然后,使用您的函数并在 REPL 中尝试它:

val isD = (x: Char) => "123456789-_ " contains x
groupBy("this is a line with 0123344334343434343434-343 3345")(isD(_) == isD(_))
Run Code Online (Sandbox Code Playgroud)

结果是 a List[String],这可能是您真正想要的。