zoukankan      html  css  js  c++  java
  • fold()操作和reduce()操作的区别

    reduce()——规约操作,包含reduceLeft()和reduceRight()两种操作。

    fold()——折叠操作,包含foldLeft()和foldRight()两种操作。

    两者功能相似,不同之处在于:

    fold()操作需要从一个初始值开始,并以该值作为上下文,处理集合中的每个元素。

    reduce()操作举例:

    1.  
      scala> val list = List(1,2,3,4,5)
    2.  
      list: List[Int] = List(1, 2, 3, 4, 5)
    3.  
       
    4.  
      scala> list.reduceLeft((x:Int,y:Int)=>{println(x,y);x+y})
    5.  
      (1,2)
    6.  
      (3,3)
    7.  
      (6,4)
    8.  
      (10,5)
    9.  
      res0: Int = 15
    10.  
       
    11.  
      scala> list.reduceRight((x:Int,y:Int)=>{println(x,y);x+y})
    12.  
      (4,5)
    13.  
      (3,9)
    14.  
      (2,12)
    15.  
      (1,14)
    16.  
      res1: Int = 15
    1.  
      scala> val list = List(1,2,3,4,5)
    2.  
      list: List[Int] = List(1, 2, 3, 4, 5)
    3.  
       
    4.  
      scala> list.reduceLeft((x:Int,y:Int)=>{println(x,y);x-y})
    5.  
      (1,2)
    6.  
      (-1,3)
    7.  
      (-4,4)
    8.  
      (-8,5)
    9.  
      res2: Int = -13
    10.  
       
    11.  
      scala> list.reduceRight((x:Int,y:Int)=>{println(x,y);x-y})
    12.  
      (4,5)
    13.  
      (3,-1)
    14.  
      (2,4)
    15.  
      (1,-2)
    16.  
      res3: Int = 3

    fold()操作举例:

    1.  
      scala> val list = List(1,2,4,3,5)
    2.  
      list: List[Int] = List(1, 2, 4, 3, 5)
    3.  
       
    4.  
      scala> list.fold(10)(_*_)
    5.  
      res0: Int = 1200
    1.  
      scala> list.foldLeft(0)((x:Int,y:Int)=>{println(x,y);x+y})
    2.  
      (0,1)
    3.  
      (1,2)
    4.  
      (3,4)
    5.  
      (7,3)
    6.  
      (10,5)
    7.  
      res1: Int = 15
    8.  
       
    9.  
      scala> list.foldRight(0)((x:Int,y:Int)=>{println(x,y);x+y})
    10.  
      (5,0)
    11.  
      (3,5)
    12.  
      (4,8)
    13.  
      (2,12)
    14.  
      (1,14)
    15.  
      res2: Int = 3

    上面fold(10)(_*_),fold(0)中,10和0就是进行fold()操作所附的初值。

  • 相关阅读:
    获取Mac地址
    GbkToUtf8 Utf8ToGbk PackHttp
    first Automation
    win32 Dll 中添加afx.h 出现如下错误 error LNK2005: _DllMain@12 already defined
    OpenSUSE 开启SSH 和网络设置
    systemctl命令用法详解
    浅谈Python的列表和链表
    用Python实现最大堆
    写一个解二阶魔方的程序
    暴力破解SixPack问题
  • 原文地址:https://www.cnblogs.com/ExMan/p/14357801.html
Copyright © 2011-2022 走看看