2

这是一个励志的例子,鉴于:

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

我想返回:

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

我已经尝试以多种方式做到这一点。第一的:

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

然后我尝试使用一个元组:

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

然后稍微不同地定义偏函数:

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

有没有办法仅将 PartialFunction 应用于为其定义的元素?或以某种方式将 PF 与 Identity 复合。

4

1 回答 1

1

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
于 2014-12-09T17:24:29.073 回答