reduceLeft神语法
val a = Array(20, 12, 6, 15, 2, 9)
1
2
3
4
5
6
7
8
|
scala> a.reduceLeft(
_
+
_
)
// 数组求和
res
0
:
Int
=
64
scala> a.reduceLeft(
_
*
_
)
// 数组求乘积
res
1
:
Int
=
388800
scala> a.reduceLeft(
_
min
_
)
// 数组求最小值
res
2
:
Int
=
2
scala> a.reduceLeft(
_
max
_
)
// 数组求最大值
res
3
:
Int
=
20
|
使用函数
自定义函数实现数组求最大值功能
1
2
3
4
|
scala>
val
a
=
Array(
20
,
12
,
6
,
15
,
2
,
9
)
scala>
val
f
=
(x
:
Int, y
:
Int)
=
> x max y
scala> a.reduceLeft(f)
res
0
:
Int
=
20
|
实现原理
第一、第二个数的比较结果再与第三个数进行比较,以此类推。x为上一次结果,y为本次比较数值
使用神语法
scala> val a = Array(20, 12, 6, 15, 2, 9)
1
2
3
4
5
6
7
8
|
scala> a.reduceLeft(
_
+
_
)
// 数组求和
res
0
:
Int
=
64
scala> a.reduceLeft(
_
*
_
)
// 数组求乘积
res
1
:
Int
=
388800
scala> a.reduceLeft(
_
min
_
)
// 数组求最小值
res
2
:
Int
=
2
scala> a.reduceLeft(
_
max
_
)
// 数组求最大值
res
3
:
Int
=
20
|
使用函数
自定义函数实现数组求最大值功能
1
2
3
4
|
scala>
val
a
=
Array(
20
,
12
,
6
,
15
,
2
,
9
)
scala>
val
f
=
(x
:
Int, y
:
Int)
=
> x max y
scala> a.reduceLeft(f)
res
0
:
Int
=
20
|
实现原理
第一、第二个数的比较结果再与第三个数进行比较,以此类推。x为上一次结果,y为本次比较数值