我们可以在比赛中重用守卫中的中间变量吗? [英] Can we reuse an intermediate variable from within a guard inside a match?

查看:40
本文介绍了我们可以在比赛中重用守卫中的中间变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个方法 foo 为:

Say I have a method foo as:

def foo(i:Int):Option[Int] = ??? // some code

现在我想对IntSeq进行如下操作:

Now I want to operate on a Seq of Int as follows:

Seq(1, 2).map{
  case int => foo(int)
}.collect{
  case Some(int) => int
}

将其结合起来的一种方法是:

One way to combine this would be to do:

Seq(1, 2).collect{
  case int if foo(int).isDefined => foo(int)
}

有什么办法可以避免两次调用 foo 吗?

Is there any way I can avoid calling foo twice?

所以基本上我希望在 => 的 LHS 上定义 foo(int) 作为准备在 RHS 上使用的变量,而不必计算它再次.

So basically I want foo(int) to be defined on the LHS of => as a variable ready for use on the RHS rather than having to compute it again.

推荐答案

对于你给出的情况,如果 foo 是一个偏函数,你可以这样做

For the case you gave, if foo were a partial function, you could just do

Seq(1, 2).collect{foo}

方便的是,我们可以将 foo 变成这样一个偏函数(仅在 foo 返回 Some(...) 时定义),使用Function.unlift

Conveniently, we can turn foo into such a partial function (defined only where foo returns Some(...)), using Function.unlift

让我们定义一个合适的foo

def foo(i:Int) = i match { case 1 => Some(42) ; case _ => None }

测试一下

Seq(1, 2).collect{
  case int if foo(int).isDefined => foo(int)
}
// Seq[Option[Int]] = List(Some(42))

现在将其解除"为部分功能

Now "unlift" it to a partial function

val partialFoo = Function.unlift(foo)

并测试:

Seq(1, 2).collect{partialFoo}
// Seq[Int] = List(42)

所以你没有得到包裹在 Some(...) 中的值,但我假设你无论如何都会解开它,因为你的原始代码将在 中包含每个元素一些(...)

So you don't get the value wrapped in Some(...), but I assume you would have unwrapped that anyway since your original code would have had every element in a Some(...)

这篇关于我们可以在比赛中重用守卫中的中间变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆