当前位置:网站首页>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)
}
}
边栏推荐
猜你喜欢
English Grammar - Adverbial Clauses
【LeetCode】112.路径总和
Transformer、BERT、GPT 论文精读笔记
热部署系统实现
Logic Pro X自带音色库列表
响应式布局经典范例——巨幅背景大标题
How does Mysql query two data tables for the same fields in two tables at the same time
IDEA2021.2安装与配置(持续更新)
Qt 下拉复选框(MultiSelectComboBox)(一) 实现下拉框多选,搜索下拉框内容
Path Prefixes (倍增!树上の二分)
随机推荐
手把手教你如何自制目标检测框架(从理论到实现)
Evaluate: A detailed introduction to the introduction of huggingface evaluation indicator module
【TPC-DS】DF的SQL(Data Maintenance部分)
110 MySQL interview questions and answers (continuous updates)
qt使用mysql数据库(自学笔记)
Eject stubborn hard drives with diskpart's offline command
【愚公系列】2022年07月 Go教学课程 026-结构体
【LeetCode】112.路径总和
数据监控平台
NFT到底有哪些实际用途?
LeetCode第三题(Longest Substring Without Repeating Characters)三部曲之二:编码实现
【收获合辑】k-NN与检索任务的异同+jupyter转pdf
Evaluate:huggingface评价指标模块入门详细介绍
牛客 - 最佳直播时间 (差分)
HCIA实验(07)
Pop Harmony Basics Big Notes
《剑指Offer》刷题之打印从1到最大的n位数
Mysql如何对两张表的相同字段,同时查询两张数据表
Gauva的ListenableFuture
uniapp swiper 卡片轮播 修改指示点样式效果demo(整理)