如何转换 X =>Option[R] 到 PartialFunction[X,R] [英] How to convert X => Option[R] to PartialFunction[X,R]
问题描述
只要我们有一个 PartialFunction[X,R]
,很容易将它转换成一个返回 Option[R]
的函数,例如
def pfToOptf[X, R](f: PartialFunction[X,R])(x: X) =if (f.isDefinedAt(x)) Some(f(x))其他 无
但是,如果任务相反怎么办:假设我有一个函数 f
获取 X
作为参数并返回 Option[R]
因此.我想用它制作一个 PartialFunction[X,R]
.最好的方法是什么?
我想出的东西在我看来很丑陋:
def optfToPf[X,R](f: X => Option[R]) : PartialFunction[X,R] = {对象提取器{def unapply(x: X): Option[R] = f(x)}{案例提取器(r)=>r }}
我错过了更好的方法吗?
Starting Scala 2.9
, Function.unlift
正是这样做的:
def unlift[T, R](f: (T) => Option[R]): PartialFunction[T, R]
<块引用>
将函数 T => Option[R] 转换为 PartialFunction[T, R].
As long as we have a PartialFunction[X,R]
it's very easy to convert it to a function returning Option[R]
, e.g.
def pfToOptf[X, R](f: PartialFunction[X,R])(x: X) =
if (f.isDefinedAt(x)) Some(f(x))
else None
However, what if the task is opposite: suppose I have a function f
getting X
as an argument and returning Option[R]
as a result. And I want to make a PartialFunction[X,R]
out of it. What is the best way?
What I've come up with looks pretty ugly to my taste:
def optfToPf[X,R](f: X => Option[R]) : PartialFunction[X,R] = {
object extractor {
def unapply(x: X): Option[R] = f(x)
}
{ case extractor(r) => r }
}
Is there some better way I missed?
Starting Scala 2.9
, Function.unlift
does precisely this:
def unlift[T, R](f: (T) => Option[R]): PartialFunction[T, R]
Turns a function T => Option[R] into a PartialFunction[T, R].
这篇关于如何转换 X =>Option[R] 到 PartialFunction[X,R]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!