# Scala的foldLeft和foldRight

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

def :\[B](z: B)(op: (A, B) => B): B = foldRight(z)(op)
OK，原来是foldLeft和foldRight的简写

foldLeft和foldRight直接翻译来向左折叠，向右折叠。

## foldLeft

def foldLeft[B](z: B)(op: (B, A) => B): B = {
var result = z
this.seq foreach (x => result = op(result, x))
result
}

def seq: TraversableOnce[A]

listA其实是实现了TraversableOnce这个trait的。

scala> listA.foldLeft(0)((sum,i)=>sum+i)
res26: Int = 6

val result = z， 这里其实就是0，x=>result=op(result, x) ， sum其实也是z

## foldRight

def foldRight[B](z: B)(op: (A, B) => B): B =
reversed.foldLeft(z)((x, y) => op(y, x))

 // for internal use
protected[this] def reversed = {
var elems: List[A] = Nil
self.seq foreach (elems ::= _)
elems
}

scala> ((1 to 5)).foldRight(100)((sum,i)=>sum-i)
res48: Int = -97

(x,y) => op（y,x）

scala> ((1 to 5)).foldRight(100)((i,sum)=>sum-i)
res49: Int = 85

## flodLeft的简写 /:

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

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

## foldRight的简写 :\

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

-EOF-

05-01 2069
02-26 516
04-22 157
12-19 6638
02-26 2367
04-16 137
01-06 5998
01-10 8252
05-23 9万+
04-10 160
08-28 5203
07-25 1559