2

What is the best way to mix a function input parameter with the output.

Here is my current code :

def zip[A,B](f: A => B) : A => (A, B) = (a: A) => (a, f(a))
def zip[A,B](pf: PartialFunction[A,B]) : PartialFunction[A, (A, B)] = { 
  case a if pf.isDefinedAt(a) => (a, pf(a)) 
}

Is there a better way ? Is there a better naming for that ?

Ben Reich
  • 16,222
  • 2
  • 38
  • 59
Yann Moisan
  • 8,161
  • 8
  • 47
  • 91

1 Answers1

0

If you lift then match, you only have to evaluate pf once (unlike in your solution, which evaluates twice):

def zip[A,B](pf: PartialFunction[A,B]): PartialFunction[A, (A, B)] = 
    x => pf.lift(x) match { case Some(res) => x -> res }

Or you can use unlift which takes a function to Option and returns the equivalent PartialFunction:

def zip[A,B](pf: PartialFunction[A,B]) = Function.unlift((x:A) => pf.lift(x).map(x -> _))
Ben Reich
  • 16,222
  • 2
  • 38
  • 59