scala,所有对象的通用变换函数
我想要一些如下的东西:scala,所有对象的通用变换函数,scala,Scala,我想要一些如下的东西: val onlyNice = true; val users: List[String] = getNames() val result = users .filter(_.contains("john") .map(._toUpperCase) .filter(p => isNice) // here i would need to apply this filter only if `onlyNice` is true .map(p =&g
val onlyNice = true;
val users: List[String] = getNames()
val result = users
.filter(_.contains("john")
.map(._toUpperCase)
.filter(p => isNice) // here i would need to apply this filter only if `onlyNice` is true
.map(p => countryOf(p));
val tmp = users
.filter(_.contains("john")
.map(._toUpperCase)
val tmp2 = if (onlyNice) tmp.filter(isNice) else tmp
val result = tmp2.
.map(p => countryOf(p));
也就是说,我只想在onlyNice==true
时应用isNice
过滤器。
我可以这样做:
val result = users
.filter(_.contains("john")
.map(._toUpperCase)
.filter(p => !onlyNice || isNice)
.map(p => countryOf(p));
但这会降低性能,因为即使onlyNice为false,我们也会遍历所有列表
我们可以这样做:
val onlyNice = true;
val users: List[String] = getNames()
val result = users
.filter(_.contains("john")
.map(._toUpperCase)
.filter(p => isNice) // here i would need to apply this filter only if `onlyNice` is true
.map(p => countryOf(p));
val tmp = users
.filter(_.contains("john")
.map(._toUpperCase)
val tmp2 = if (onlyNice) tmp.filter(isNice) else tmp
val result = tmp2.
.map(p => countryOf(p));
但这更难阅读
对我来说,这似乎是一个很好的通用解决方案:
implicit class ObjectHelper[A](o: A) {
def transform[B](f: A => B): B = f(o)
}
val result = users
.filter(_.contains("john")
.map(._toUpperCase)
.transform(list => if (onlyNice) list.filter(isNice) else list)
.map(p => countryOf(p));
你觉得怎么样
这个
transform
函数是否已经在标准scala库的某个地方实现了?您的transform
本质上是一个翻转形式的函数应用程序
我不知道标准库中有什么实现,但它在Scalaz库中作为|>
操作符实现,例如
import scalaz.syntax.id._
users |> (list => if (onlyNice) list.filter(isNice) else list)
请注意,因为在这种情况下,函数的类型是A=>A
,而不是A=>B
(即它是List[String]=>List[String]
),所以您可以等效地使用identity
函数,例如
users |> (if (onlyNice) (_.filter(isNice)) else identity)
您的
转换
本质上是一种翻转形式的函数应用程序
我不知道标准库中有什么实现,但它在Scalaz库中作为|>
操作符实现,例如
import scalaz.syntax.id._
users |> (list => if (onlyNice) list.filter(isNice) else list)
请注意,因为在这种情况下,函数的类型是A=>A
,而不是A=>B
(即它是List[String]=>List[String]
),所以您可以等效地使用identity
函数,例如
users |> (if (onlyNice) (_.filter(isNice)) else identity)
该示例未编译(错误“未找到:值|>”)。我将依赖项添加到scalaz-core_2.10 7.0.0中,并导入scalaz。_我是否需要其他东西来编译它?还有,有API文档吗?我只在general doc页面上找到了,您需要从
scalaz.syntax.id.导入隐式。我已经在我的答案中添加了这个。太好了,谢谢!有api文档吗?我应该如何找到syntax.id?对于API文档,请尝试。示例未编译(错误“not found:value |>”)中的隐式语法有很好的解释。我将依赖项添加到scalaz-core_2.10 7.0.0中,并导入scalaz。_我是否需要其他东西来编译它?还有,有API文档吗?我只在general doc页面上找到了,您需要从scalaz.syntax.id.导入隐式。我已经在我的答案中添加了这个。太好了,谢谢!有api文档吗?我应该如何找到syntax.id?对于API文档,请尝试。对其隐含的语法有很好的解释