使用模式匹配的后卫(if)在体内的标量

问题描述 投票:0回答:1

我在Scala中经常使用模式匹配。很多时候,我需要在后卫部分做一些计算,有时它们很昂贵。有什么方法可以将计算值绑定到单独的值?

//i wan't to use result of prettyExpensiveFunc in body safely
Seq(1,2,3,4,5).collect {
  case ...
  case x if prettyExpensiveFunc(x) > 0 => prettyExpensiveFunc(x)
}

//ideally something like that could be helpful, but it doesn't compile:
Seq(1,2,3,4,5).collect {
  case ...
  case x if {val y = prettyExpensiveFunc(x); y > 0} => y
}

//this sollution works but it isn't safe for some `Seq` types and is risky when more cases are used.
var cache:Int = false
Seq(1,2,3,4,5).collect {
  case ...
  case x if {cache = prettyExpensiveFunc(x); cache > 0} => cache
}

有更好的解决方案吗?ps:示例已简化,我不希望看到答案表明这里不需要模式匹配。

scala pattern-matching
1个回答
0
投票

为什么不先为每个元素运行该函数,然后再使用元组呢?

Seq(1,2,3,4,5).map(e => (e, prettyExpensiveFunc(e))).collect {
  case ...
  case (x, y) if y => y
}
© www.soinside.com 2019 - 2024. All rights reserved.