-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathHigherOrderFuncDemo_7.scala
71 lines (55 loc) · 1.45 KB
/
HigherOrderFuncDemo_7.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package ScalaBasic
// https://www.youtube.com/watch?v=Bh66GdPPKuw&list=PLmOn9nNkQxJEqCNXBu5ozT_26xwvUbHyE&index=167
object HigherOrderFuncDemo_7 extends App {
/**
* Higher order func :
* -> A func that can get other func as input argument
*
* 1) test(f: Double => Double, n1: Double) is a higher order func
* 2) func input type : Double, output type : Double
* 3) input arg type : Double
*/
// example 1
def test(f: Double => Double, n1: Double) = {
f(n1)
}
def sum(d: Double): Double = {
d + d
}
// run
val r1 = test(sum, 7.7)
println("r1 = " + r1)
println("==============")
// example 2
/**
* Higher order func :
*
* 1) minusxy will return a func
* -> the func : (y: Int) => x - y
*
* 2) returned anonymous func uses outer var : x,
* the x and anonymous func now as a "closure"
*/
def minusxy(x: Int) = {
(y: Int) => x - y // anonymous func
}
val r2 = minusxy(3)(5)
println("r2 = " + r2)
println("==============")
// f1 is (y: Int) = { x - y } ( while x = 10 )
val f1 = minusxy(10) // f1 is a anonymous func
println("f1 = " + f1)
println(f1(1))
println(f1(1))
println(f1(2))
println("==============")
// anonymous func : y: Int) = { x - y } ( while x = 20 )
println(minusxy(20)(9))
println("==============")
// example 3
def test2(x: Double) = {
(y: Double) => x * x * y
}
val r3 = test2(2.0)(3.0)
println("r3 = " + r3)
}