Scala 中的FordLeft

foldLeft

scala> numbers.foldLeft(0)((m: Int, n: Int) => m + n)
res0: Int = 55

0为初始值(记住numbers是List[Int]类型),m作为一个累加器。

直接观察运行过程:

scala> numbers.foldLeft(0) { (m: Int, n: Int) => println("m: " + m + " n: " + n); m + n }
m: 0 n: 1
m: 1 n: 2
m: 3 n: 3
m: 6 n: 4
m: 10 n: 5
m: 15 n: 6
m: 21 n: 7
m: 28 n: 8
m: 36 n: 9
m: 45 n: 10
res0: Int = 55


下面是我写的一些学习的例子


import java.io.File
import java.net.URL
import sys.process._
import java.io.FileWriter
import java.io.BufferedWriter


/**
 * def foldLeft[B](z: B)(op: (B, A) ⇒ B): B


Applies a binary operator to a start value and all elements of this sequence, going left to right.

Note: will not terminate for infinite-sized collections.

B
    the result type of the binary operator.
z
    the start value.
op
    the binary operator.
    
returns

    the result of inserting op between consecutive elements of this sequence,
    going left to right with the start value z on the left:
 */

object ListTest {



 
  def main(args: Array[String]) {
    val site1 = "https:"::("www."::("seeburger." :: ("de"::Nil)))
    val nums = 1 :: (2 :: (3 :: (6 :: Nil)))
    println(sum1(nums))
    println(sum2(nums))
    println(product1(nums))
    println(count(nums))
    println(average(nums))
    println(last(site1))
    println(contains(site1,"https:"))
    println(get(site1,0))
     println( "head: " + site1.head )
      println( "tail: " + site1.tail )
      println( "empty or not: " + site1.isEmpty )  
      
    downloadFile("systemLoadAverage")
    //new URL("http://10.11.22.36:82/render/?width=588&height=310&target=servers.bdq-cassandra3_7199.Stage.ReadStage.CompletedTasks&format=csv") #> new File("./src/download.csv") !!  
  }
 
 
def sum1(list: List[Int]): Int =   list.foldLeft(0){(r,c)=> println("r:"+r+ "c: "+ c + "results: "+(r+c));r+c}

def sum2(list: List[Int]): Int = list.foldLeft(0)( _ + _ )

def product1(list: List[Int]): Int = list.foldLeft(1)(_*_)

def count(list: List[Any]): Int = list.foldLeft(0){(sum,_)=> println("sum:"+sum); sum + 15}

def average(list: List[Int]): Int = list.foldLeft(0)(_+_)/list.foldLeft(0)((sum,_)=> sum + 1)

def last[A](list: List[A]): A =  list.foldLeft[A](list.head){(_,c) => println("c: "+c);c}

def contains[A](list: List[A], item: A): Boolean = list.foldLeft(false)(_||_==item)

def get[A](list: List[A], idx: Int): A = list.tail.foldLeft((list.head,0)){
  (r,c) => if(r._2 == idx) r else (c, r._2 +1)}match{
    case (result, index) if (idx == index ) => result
    case _ => throw new Exception("Bad Index")
  }

OUTPUT:

r:0c: 1results: 1
r:1c: 2results: 3
r:3c: 3results: 6
r:6c: 6results: 12
12
12
36
sum:0
sum:15
sum:30
sum:45
60
3
c: https:
c: www.
c: seeburger.
c: de
de
true
https:
head: https:
tail: List(www., seeburger., de)
empty or not: false


你可能感兴趣的:(scala,Foldleft)