编写通用的“填充”;方法
我正在尝试编写一个通用的 fill
方法,以下是我到目前为止所想到的:
scala> import collection.generic.{GenericTraversableTemplate => GTT}
import collection.generic.{GenericTraversableTemplate=>GTT}
scala> import collection.generic.{TraversableFactory => TF}
import collection.generic.{TraversableFactory=>TF}
scala> def fill[A, CC[X] <: Traversable[X] with GTT[X, CC]]
| (n: Int)(elem: => A)(tf: TF[CC]) = tf.fill(n)(elem)
fill: [A, CC[X] <: Traversable[X] with scala.collection.generic.GenericTraversab
leTemplate[X,CC]](n: Int)(elem: => A)(tf: scala.collection.generic.TraversableFa
ctory[CC])CC[A]
scala> fill(3)('d')(List)
res42: List[Char] = List(d, d, d)
这适用于除数组之外的所有可遍历集合。如何使此代码与数组一起使用?
I am trying to write a generic fill
method, and following is what I have come up with so far:
scala> import collection.generic.{GenericTraversableTemplate => GTT}
import collection.generic.{GenericTraversableTemplate=>GTT}
scala> import collection.generic.{TraversableFactory => TF}
import collection.generic.{TraversableFactory=>TF}
scala> def fill[A, CC[X] <: Traversable[X] with GTT[X, CC]]
| (n: Int)(elem: => A)(tf: TF[CC]) = tf.fill(n)(elem)
fill: [A, CC[X] <: Traversable[X] with scala.collection.generic.GenericTraversab
leTemplate[X,CC]](n: Int)(elem: => A)(tf: scala.collection.generic.TraversableFa
ctory[CC])CC[A]
scala> fill(3)('d')(List)
res42: List[Char] = List(d, d, d)
This works with all traversable collections except arrays. How do I make this code work with arrays?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您不介意创建一个额外的对象,那么
它无法绕过反对意见(2),但用法很好:
If you don't mind creating an extra object, there's
It doesn't get around objection (2), but the usage is nice:
可以稍微改变一下 Rex 解决方案的语法:
因为运算符符号只允许用于括号,所以我们不能省略括号。
It is possible to change the syntax of Rex' solution a little bit:
Because operator notation is only allowed for parentheses, we can't omit the brackets.
我通过使用 Builder 的 ++= 方法改进了 Rex 的解决方案。使用任何集合,对其执行您想要执行的任何操作,然后最终将其添加到构建器对象中,然后获取其结果。
I have bettered Rex's solution here by using
Builder
's++=
method. Use any collection, perform on it whatever operations you want to perform, and then finally add it to the builder object and then take its result.