feat:ChatGPT第 5 课:函数作为参数

This commit is contained in:
2026-09-13 19:24:24 +08:00
parent f6cb9d96b4
commit 22892f7f50
6 changed files with 184 additions and 0 deletions
+21
View File
@@ -0,0 +1,21 @@
package practise5.demo
/*
doSomething
↓
需要一个函数
↓
x => x * 2
↓
把这个函数交给 doSomething
这就是:
函数作为参数传递。
*/
object Demo {
def main(args: Array[String]): Unit = {
doSomething(x => x * 2)
}
private def doSomething(f: Int => Int): Unit = {
println(f(10))
}
}
@@ -0,0 +1,29 @@
package practise5.exercises
/*
练习 1
定义:
def operate(a: Int, b: Int, f: (Int, Int) => Int): Int = {
// ...
}
要求让它能够这样使用:
println(operate(10, 20, (a, b) => a + b))
输出:
30
提示:
函数参数 f 可以这样调用:
f(a, b)*/
object Exercises1 {
def main(args: Array[String]): Unit = {
println(operate(10, 20, (a, b) => a + b))
}
def operate(a: Int, b: Int, f: (Int, Int) => Int): Int = {
f(a, b)
}
}
@@ -0,0 +1,34 @@
package practise5.exercises
/*
让下面这些都能正常工作:
println(operate(10, 20, (a, b) => a + b))
println(operate(10, 20, (a, b) => a - b))
println(operate(10, 20, (a, b) => a * b))
输出:
30
-10
200
注意:
operate 自己并不知道你要做加法、减法还是乘法。
它只负责:
接收两个数字
+
接收一个函数
+
执行这个函数
*/
object Exercises2 {
def main(args: Array[String]): Unit = {
println(operate(10, 20, (a, b) => a + b))
println(operate(10, 20, (a, b) => a - b))
println(operate(10, 20, (a, b) => a * b))
}
def operate(a: Int, b: Int, f1: (Int, Int) => Int): Int = {
f1(a, b)
}
}
@@ -0,0 +1,29 @@
package practise5.exercises
/*
练习 3
自己定义:
def calculate(a: Int, f: Int => Int): Int
要求:
println(calculate(10, x => x * 2))
输出:
20
以及:
println(calculate(10, x => x * 3))
输出:
30
*/
object Exercises3 {
def main(args: Array[String]): Unit = {
println(calculate(10, x => x * 2))
println(calculate(10, x => x * 3))
}
private def calculate(a: Int, f: Int => Int): Int = {
f(a)
}
}
@@ -0,0 +1,35 @@
package practise5.exercises
/*
练习 4
给:
val nums = List(1, 2, 3, 4, 5)
先自己定义一个函数:
val double = (x: Int) => x * 2
然后不要直接写:
nums.map(x => x * 2)
而是:
nums.map(double)
观察结果。
也就是说:
x => x * 2
和:
double
都可以作为 map 的参数。
*/
object Exercises4 {
def main(args: Array[String]): Unit = {
val nums = List(1, 2, 3, 4, 5)
val double = (x: Int) => x * 2
println(nums.map(double))
println(nums.map(x => x * 2))
}
}
@@ -0,0 +1,36 @@
package practise5.exercises
/*
练习 5 ⭐⭐⭐
最后做一道非常接近真实 Scala/Spark 的:
val nums = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
完成:
1. 过滤出偶数
2. 每个偶数乘 10
3. 最终得到 List(20, 40, 60, 80, 100)
要求使用:
filter
map
并且尽量使用函数值变量,例如:
val isEven = ...
val multiply10 = ...
最终类似:
nums
.filter(isEven)
.map(multiply10)
*/
object Exercises5 {
def main(args: Array[String]): Unit = {
val nums = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val isEven = (x:Int) => x%2==0
val multiply10 = (x:Int) => x * 10
val result = nums.filter(isEven).map(multiply10)
println(result)
}
}