Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
840 views
in Technique[技术] by (71.8m points)

scala - How to convert X => Option[R] to PartialFunction[X,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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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].


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...