是否有任何隐式提供`some.long.expression.let(x => ...)`语法
Is there any implicit providing `some.long.expression.let(x => ...)` syntax
例如,我想在我的长表达式的末尾得到 x * (x - 1)
,而不是将它分成两行并引入不必要的变量。我可以用简单的隐式实现它:
scala> implicit class Rich[T](x: T) { def let[U](f: T => U) = f(x)}
defined class Rich
scala> List(1,2,3).map(_ + 1).sum.let(x => x * (x - 1))
res199: Int = 72
但是在 Scala、Scalaz、Twitter Utils 或其他库中是否有任何此类内置隐式?
我找到的最接近的方法是:
import scalaz.syntax.std.option._
scala> List(1,2,3).map(_ + 1).sum.some.map(x => x * (x - 1)).get
res201: Int = 72
Scalaz 将其设为 part of its IdOps
implicits。它被称为|>
。
long.complex(expression) |> { x => x*(x+1) }
也就是说,将所有 Scalaz 都拉到一行中效率有点低。
此外,不要忘记 match
已经以这种方式工作,只是优先级有点尴尬。
((long.complex(expression)) match { case x => x*(x+1) })
由于这种尴尬,它并没有比[=18]好多少(尽管它比每个其他替代方案更有效,至少在优化器改进更多之前) =]
Some(long.complex(expression)).map(x => x*(x+1)).get
你也可以
long.complex(expression) :: Nil map (x => x*(x+1)) head
如果您愿意启用一元后缀运算符。
例如,我想在我的长表达式的末尾得到 x * (x - 1)
,而不是将它分成两行并引入不必要的变量。我可以用简单的隐式实现它:
scala> implicit class Rich[T](x: T) { def let[U](f: T => U) = f(x)}
defined class Rich
scala> List(1,2,3).map(_ + 1).sum.let(x => x * (x - 1))
res199: Int = 72
但是在 Scala、Scalaz、Twitter Utils 或其他库中是否有任何此类内置隐式?
我找到的最接近的方法是:
import scalaz.syntax.std.option._
scala> List(1,2,3).map(_ + 1).sum.some.map(x => x * (x - 1)).get
res201: Int = 72
Scalaz 将其设为 part of its IdOps
implicits。它被称为|>
。
long.complex(expression) |> { x => x*(x+1) }
也就是说,将所有 Scalaz 都拉到一行中效率有点低。
此外,不要忘记 match
已经以这种方式工作,只是优先级有点尴尬。
((long.complex(expression)) match { case x => x*(x+1) })
由于这种尴尬,它并没有比[=18]好多少(尽管它比每个其他替代方案更有效,至少在优化器改进更多之前) =]
Some(long.complex(expression)).map(x => x*(x+1)).get
你也可以
long.complex(expression) :: Nil map (x => x*(x+1)) head
如果您愿意启用一元后缀运算符。