gpt4 book ai didi

scala:向列表添加方法?

转载 作者:行者123 更新时间:2023-12-04 16:55:29 24 4
gpt4 key购买 nike

我想知道如何向列表添加“partitionCount”方法,例如:
(未测试,无耻地基于 List.scala):

我是否必须创建自己的子类和隐式类型转换器?

(我最初的尝试有很多问题,所以这里是一个基于@Easy 的回答):

class MyRichList[A](targetList: List[A]) {
def partitionCount(p: A => Boolean): (Int, Int) = {
var btrue = 0
var bfalse = 0
var these = targetList
while (!these.isEmpty) {
if (p(these.head)) { btrue += 1 } else { bfalse += 1 }
these = these.tail
}
(btrue, bfalse)
}
}

这是一个更通用的版本,对 Seq[...] 有好处:
implicit def seqToRichSeq[T](s: Seq[T]) = new MyRichSeq(s)

class MyRichList[A](targetList: List[A]) {
def partitionCount(p: A => Boolean): (Int, Int) = {
var btrue = 0
var bfalse = 0
var these = targetList
while (!these.isEmpty) {
if (p(these.head)) { btrue += 1 } else { bfalse += 1 }
these = these.tail
}
(btrue, bfalse)
}
}

最佳答案

您可以像这样使用隐式转换:

implicit def listToMyRichList[T](l: List[T]) = new MyRichList(l)

class MyRichList[T](targetList: List[T]) {
def partitionCount(p: T => Boolean): (Int, Int) = ...
}

而不是 this您需要使用 targetList .您不需要扩展 List .在这个例子中,我创建了简单的包装器 MyRichList这将被隐式使用。

您可以通过为 Traversable 定义它来进一步概括包装器,以便它适用于其他可能的集合类型,而不仅适用于 List s:
implicit def listToMyRichTraversable[T](l: Traversable[T]) = new MyRichTraversable(l)

class MyRichTraversable[T](target: Traversable[T]) {
def partitionCount(p: T => Boolean): (Int, Int) = ...
}

另请注意,仅当它在范围内时才会使用隐式转换。这意味着,您需要 import它(除非您在定义它的同一范围内使用它)。

关于scala:向列表添加方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6975754/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com