閱讀127 返回首頁    go 阿裏雲 go 技術社區[雲棲]


Scala的foldLeft和foldRight


Scala的foldLeft和foldRight

FoldLeft

定義如下:

  override /*TraversableLike*/
  def foldLeft[B](z: B)(f: (B, A) => B): B = {
    var acc = z
    var these = this
    while (!these.isEmpty) {
      acc = f(acc, these.head)
      these = these.tail
    }
    acc
  }
  • z the start value
  • f 操作函數(累積器,these.head)

注意:類型

也可以這麼寫 /: 或者 :\ ,scala做了簡化:

def /:[B](z: B)(op: (B, A) => B): B = foldLeft(z)(op)

def :\[B](z: B)(op: (A, B) => B): B = foldRight(z)(op)

舉個簡單的例子:

List(1,2,3).foldLeft(0)((sum,i)=>sum+i)
res21: Int = 6

acc = z
acc = 0 + List.head
List = List.tail
acc = acc + List.head
...

再舉個比較複雜的例子:

 //times(List('a', 'b', 'a')) --> List(('a', 2), ('b', 1))
  def times(chars: List[Char]): List[(Char, Int)] = {
    def incr(pairs: List[(Char, Int)], C: Char): List[(Char, Int)] =
      pairs match {
        case Nil => List((C, 1))
        case (C, n) :: ps => (C, n+1) :: ps
        case p :: ps => p :: incr(ps, C)
      }
    chars.foldLeft(List[(Char,Int)]())(incr)
  }

也可以用富操作的寫法:

(list foldLeft 0)(sum)
(chars foldLeft List[(Char, Int)]())(incr)

總結一下

foldRight就是逆序集合,然後調用foldLeft. (Ps:我的scala版本2.9.3)

foldLeft的簡寫 /:
這個是foldLeft的簡寫吧,個人理解。
如果我寫一個累加的程序

scala> (0/:(1 to 100))(_+_)  
res32: Int = 5050

其實是等價於

scala> (1 to 100).foldLeft(0)(_+_)  
res33: Int = 5050

foldRight的簡寫 :\
這個就是foldRight的簡寫吧,個人理解。
如果我寫一個遞減的程序

scala> ((1 to 5):\100)((i,sum)=> sum-i)

Reference

https://blog.csdn.net/oopsoom/article/details/23447317


最後更新:2017-04-03 05:39:11

  上一篇:go Android 通過網頁打開自己的APP(scheme)
  下一篇:go C雙向鏈表