Applying partial functions where defined and a different function where not

272 Views Asked by At

This is a motivational example, Given:

List((1,2), (2,1), (3,1))

I'd like to return:

List((1,2),(3,1))

I've tried to do this in several ways. First:

List((1,2), (2,1), (3,1)) map { case (a,b) => if (a > b) (a,b) else (b,a) } 
distinct

Then I tried to use a tuple:

List((1,2), (3,4), (2,1)) map { t => if (t._1 <= t._2) t else t.swap }

then defining the partial function a little differently:

val pf: PartialFunction[(Int,Int), (Int,Int)] = {
  case (i, j) if i >= j => (j, i)
}

List((1,2), (3,4), (2,1)) map pf distinct

Is there a way that apply the PartialFunction only to the elementes that is defined for? or compound the PF with Identity in some how.

1

There are 1 best solutions below

5
On BEST ANSWER

Here's another form for the sake of completeness

List((1,2), (2,1), (3,1)) map { case x@(i,j) => if (i >= j) (j,i) else x } distinct

Which is basically the same several of your other forms.

Is there a way that apply the PartialFunction only to the elementes that is defined for? or compound the PF with Identity in some how.

Yes. applyOrElse.

In this case there's very little reason to check where your partial function is and isn't defined because the amount of work required to check definedness is going to be the same as the work the total function has to do before figuring out what to do (i.e. comparing the two elements).

But if you really want to

List((1,2), (3,4), (2,1)) map {x => pf.applyOrElse(x, identity[(Int, Int)])} distinct