当前位置:网站首页>scala减少,reduceLeft reduceRight,折叠,foldLeft foldRight
scala减少,reduceLeft reduceRight,折叠,foldLeft foldRight
2022-08-03 08:41:00 【But he that doeth good mo ask future】
1. 归约函数
1.1 reduce
聚合: N -> 1
,如 sum函数统计List中所有元素的和; 在scalaThe bottom layer uses pairwise aggregation,The type of the aggregated result is ANDreduce方法的返回值类型相同
object T27 {
def main(args: Array[String]): Unit = {
val dataList = List(1, 2, 3, 4,5)
val i = dataList.reduce(_ - _)
println(i)
}
}
1.2 reduceLeft
从左往右
,Performs an operator on the elements in the collection
object T28 {
def main(args: Array[String]): Unit = {
val dataList = List(1, 2, 3, 4,5)
val i = dataList.reduceLeft(_ - _)
println(i)
}
}
注:The operation logic is( ( ( (1 - 2) - 3) - 4) - 5)
,即 op( op( ... op(x_1, x_2) ..., x_{n-1}), x_n)
1.3 reduceRight
从右往左
,Performs an operator on the elements in the collection
object T29 {
def main(args: Array[String]): Unit = {
val dataList = List(1, 2, 3, 4, 5)
val i = dataList.reduceRight(_ - _)
println(i)
}
}
注:The operation logic is(1 - (2 - (3 - (4 - 5) ) ) )
,即 op(x_1, op(x_2, ..., op(x_{n-1}, x_n)...))
2. fold、foldLeft 、foldRight
fold函数的本质是Aggregate with the initial value and each piece of data in the collection
;fold方法实际是函数柯里化
,有2个参数,第一个参数表示初始值
,The second parameter represents the calculation rule
.foldThere are two variants of the method:foldLeft()和foldRight()
:foldLeft(),第一个参数为累计值
,The direction in which the collection is traversed is 从左到右
;foldRight(),第二个参数为累计值
,The direction in which the collection is traversed is 从右到左
如:合并2个map并keyThe same summation
object T30 {
def main(args: Array[String]): Unit = {
val map1 = mutable.Map("a" -> 1, "b" -> 1, "c" -> 3)
val map2 = mutable.Map("a" -> 1, "d" -> 1, "c" -> 3)
map1.foldLeft(map2)((map, element) => {
val k = element._1
val v = element._2
val newV = map.getOrElse(k, 0) + v
map.update(k, newV)
map
})
println(map2)
}
}
边栏推荐
- WPS EXCEL 筛选指定长度的文本 内容 字符串
- Mysql如何对两张表的相同字段,同时查询两张数据表
- Laya中关于摄像机跟随人物移动或者点击人物碰撞器触发事件的Demo
- Scala parallel collections, parallel concurrency, thread safety issues, ThreadLocal
- IDEA的database使用教程(使用mysql数据库)
- AcWing 3391. 今年的第几天?(简单题)
- Gauva的ListenableFuture
- vim 折叠函数
- flutter 应用 抓包
- AI mid-stage sequence labeling task: three data set construction process records
猜你喜欢
随机推荐
阿里云·短信发送
Nacos使用实践
ArcEngine (1) Loading vector data
Docker starts mysql
MySQL2
Batch PNG format can be converted to JPG format
【论文笔记】基于动作空间划分的MAXQ自动分层方法
JMeter接口自动化发包与示例
数仓4.0(二)------ 业务数据采集平台
dflow入门3——dpdispatcher插件
Redis分布式锁
MySQL1
线程介绍与使用
MySQL数据库————数据库与vs的连接
Pop Harmony Basics Big Notes
flutter 应用 抓包
ceph简介
Evaluate: A detailed introduction to the introduction of huggingface evaluation indicator module
gpnmb+ gpnmb-AT2 cell空转映射 上皮细胞的空转映射
英文语法-状语从句