相关疑难解决方法(0)

如何将enrich-my-library模式应用于Scala集合?

一个Scala中最强大的模式是充实,我的图书馆*模式,它采用隐式转换为出现添加方法,以现有的类,而不需要动态方法解析.例如,如果我们希望所有字符串都有spaces计算他们有多少个空格字符的方法,我们可以:

class SpaceCounter(s: String) {
  def spaces = s.count(_.isWhitespace)
}
implicit def string_counts_spaces(s: String) = new SpaceCounter(s)

scala> "How many spaces do I have?".spaces
res1: Int = 5
Run Code Online (Sandbox Code Playgroud)

不幸的是,这种模式在处理泛型集合时遇到了麻烦.例如,已经询问了许多关于按顺序对项目进行分组的问题.没有内置的东西可以一次性工作,所以这似乎是使用泛型集合C和泛型元素类型的rich-my-library模式的理想候选者A:

class SequentiallyGroupingCollection[A, C[A] <: Seq[A]](ca: C[A]) {
  def groupIdentical: C[C[A]] = {
    if (ca.isEmpty) C.empty[C[A]]
    else {
      val first = ca.head
      val (same,rest) = ca.span(_ == first)
      same +: (new SequentiallyGroupingCollection(rest)).groupIdentical
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

当然,除了它不起作用.REPL告诉我们:

<console>:12: error: not found: …
Run Code Online (Sandbox Code Playgroud)

collections scala enrich-my-library

92
推荐指数
3
解决办法
6354
查看次数

Scala List函数用于对连续的相同元素进行分组

鉴于例如:

List(5, 2, 3, 3, 3, 5, 5, 3, 3, 2, 2, 2)
Run Code Online (Sandbox Code Playgroud)

我想去:

List(List(5), List(2), List(3, 3, 3), List(5, 5), List(3, 3), List(2, 2, 2))
Run Code Online (Sandbox Code Playgroud)

我会假设有一个简单的List函数来执行此操作,但我无法找到它.

collections scala

16
推荐指数
5
解决办法
6501
查看次数

标签 统计

collections ×2

scala ×2

enrich-my-library ×1