scala 偏函數與 map/collect

0. collect 與 map 的區別
由於collect方法接收的是一個偏函數類型,所以它並不能接收一個lambda表達式:

scala> List(1, 3, 5, "seven").collect(i => i + 1)
error: type mismatch;

scala> List(1, 3, 5, "seven").collect{case i => i + 1}
error: type mismatch;

scala> List(1, 3, 5, "seven").collect{case i:Int => i + 1}
List[Int] = List(2, 4, 6)


我們在使用collect時,可以利用偏函數的原理,同時實現filter與map的特性。例如:

List(1, 2, 3, 4, 5, 6) collect { case i if i % 2 == 0 => i * i }
// 等價於
List(1, 2, 3, 4, 5, 6).filter(i => i % 2 == 0).map(i => i * i)


1. 普通函數與偏函數
普通函數的定義中,有指定的輸入類型,所以可以接受任意該類型下的值。比如一個(Int) => String的函數可以接收任意Int值,並返回一個字符串。

偏函數的定義中,也有指定的輸入類型,但是偏函數不接受所有該類型下的值。比誒如(Int) => String的偏函數不能接收所有Int值爲輸入(通過 case 進行指定)。

def one:PartialFunction[Int, String] = {
    case 1 => "one"
}

one(1) // "one"
one(2) // 報錯

def two: PartialFunction[Int, String] = {
    case 2 => "two"
}

two(1) // 報錯
two(2) // "two"

def wildcard: PartialFunction[Int, String] = {
    case _ => "something else"
}

wildcard(1) // "something else"
wildcard(2) // "something else"


由於偏函數只會接收部分參數,所以可以使用 “orElse” 方法進行組合:

val partial = one orElse two orElse wildcard

partial(1) // "one"
partial(2) // "two"
partial(3) // "something else"


2. 偏函數常見成員
orElse

isDefinedAt:判斷偏函數是否對參數中的參數有效

one.isDefinedAt(1) // true
one.isDefinedAt(2) // false


case語句其實是偏函數定義的語法糖,當我們編寫一個case語句時,其實等同於創建了一個具有apply與isDefineAt方法的偏函數對象。

當我們使用PartialFunction類型定義一個偏函數的時候,scala會被自動轉換:

def int2Char: PartialFunction[Int, Char] = {
    case 1 => 'a'
    case 3 => 'c'
}


會被轉化爲:

val int2Char = new PartialFunction[Int, Char] {
    def apply(i: Int) = {
        case 1 => 'a'
        case 3 => 'c'
    }
    def isDefinedAt(i: Int): Boolean = i match {
        case 1 => true
        case 3 => true
        case _ => false
    }
}


3. map/collect 的區別
map 與 collect 等價的情況:

val languageToCount = Map("Scala" -> 10, "Java" -> 20, "Ruby" -> 5)
languageToCount map { case (_, count) => count + 1 }
languageToCount collect { case (_, count) => count + 1 }


collect 運行正常,map 運行失敗:

List(1, 3, 5, "seven") map { case i: Int => i + 1 } //won't work
//scala.MatchError: seven (of class java.lang.String)
List(1, 3, 5, "seven") collect { case i: Int => i + 1 } //it works


map 與 collect 的 api:

def map[B](f: (A) ⇒ B): List[B]

def collect[B](pf: PartialFunction[A, B]): List[B]

兩個方法的定義如出一轍,區別就在於前者接收的是一個函數類型的參數,而後者接收的是一個偏函數(partial function)類型的參數:

map: Builds a new collection by applying a function to all elements of this list.

colect: Builds a new collection by applying a partial function to all elements of this list on which the function is defined.

我們可以對比map方法和collect方法的實現:

def map[B, That](f: A => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = {
  def builder = {
      val b = bf(repr)
      b.sizeHint(this)
      b
  }
  val b = builder  
  for (x <- this) b += f(x)  
  b.result
}

def collect[B, That](pf: PartialFunction[A, B])(implicit bf: CanBuildFrom[Repr, B, That]): That = {
   val b = bf(repr)
   for (x <- this) if (pf.isDefinedAt(x)) b += pf(x)  
   b.result
}


在調用map方法時,一旦遍歷到值"seven",並調用f(x),因爲類型不符合模式匹配中的Int類型,導致拋出MatchError錯誤。而collect方法在調用pf(x)之前,調用了pf的isDefinedAt(x)作了一次過濾。
————————————————
文章出處:https://blog.csdn.net/lanchunhui/article/details/86707702

發佈了18 篇原創文章 · 獲贊 49 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章