Re: Proposal: create an Extractor for PartialFunction
杨博 <[email protected]>
| Newsgroups | gmane.comp.lang.scala |
|---|---|
| Message-ID | <CA+nJC97BBhqCa8BD8WK97JU7=_-WbJuL3vc8DhRXSN6YfDC4Gg@mail.gmail.com> |
No, neither lift nor applyOrElse is an extractor. In fact, the extractor I proposed calls condOpt, which calls applyOrElse internally. Alec Zorab <[email protected]>于2015年7月9日周四 下午4:12写道: > Don't either PartialFunction.lift or PartialFunction.applyOrElse do pretty > much exactly what you want? > > On Thu, 9 Jul 2015 at 05:56 杨博 <[email protected]> wrote: > >> Sometimes, when I create a method, I need an extractor parameter for >> pattern matching, while there is not a generic extractor trait in the Scala >> Standard Library. So we have to use a PartialFunction as the parameter >> instead. >> >> >> When I use the PartialFunction, I had to create pattern matching >> expression like this. >> >> >> input match { >> >> case x if partialFunction.isDefined(x) => >> >> val data = partialFunction.apply(x) >> >> doSomethingWith(data) >> >> } >> >> >> This approach is not perfect because: >> >> >> 1. partialFunction.isDefined and partialFunction.apply checked x >> twice, which is slow if isDefined has complex logical, checking >> whether a file exists for example. >> 2. The if condition around temporary variable x is too trivial. >> >> I think the better approach is converting the PartialFunction to an >> extractor and matching with that extractor >> >> >> implicit final class PartialFunctionAsExtractor[A, B](pf: >> PartialFunction[A, B]) { >> >> object Extractor { >> >> def unapply(a: A) = PartialFunction.condOpt(a)(pf) >> >> } >> >> } >> >> >> input match { >> case partialFunction.Extractor(data) => >> doSomethingWith(data) >> } >> >> Since this is a common approach, I hope adding the >> PartialFunctionAsExtractor to scala.Predef . >> >> I would like to create a pull request if people like this idea. >> >> -- >> > You received this message because you are subscribed to the Google Groups >> "scala-language" group. >> To unsubscribe from this group and stop receiving emails from it, send an >> email to [email protected]. > > >> For more options, visit https://groups.google.com/d/optout. >> > -- > You received this message because you are subscribed to a topic in the > Google Groups "scala-language" group. > To unsubscribe from this topic, visit > https://groups.google.com/d/topic/scala-language/g0-hbN5qerQ/unsubscribe. > To unsubscribe from this group and all its topics, send an email to > [email protected]. > For more options, visit https://groups.google.com/d/optout. > -- 杨博 (Yang Bo) -- You received this message because you are subscribed to the Google Groups "scala-language" group. To unsubscribe from this group and stop receiving emails from it, send an email to [email protected]. For more options, visit https://groups.google.com/d/optout.