Instructor: James Riely
foreach
, map
, filter
are higher-order functions
def add1(x:Int, y:Int) = x+y
add1(11, 21)
add1: (x: Int, y: Int)Int
res1: Int = 32
normaldefinition
def add2(x:Int)(y:Int) = x+y
add2(11)(21)
add2: (x: Int)(y: Int)Int
res2: Int = 32
(y: Int)Int
val add3 = (x:Int, y:Int) => x+y
add3(11, 21)
add3: (Int, Int) => Int = $$Lambda$4576/0x00000008018d1840@6ae4d2ad
res3: Int = 32
val add4 = (x:Int) => (y:Int) => x+y
add4(11)(21)
add4: Int => (Int => Int) = $$Lambda$...
res4: Int = 32
Int=>Int
def add5(x:Int) = (y:Int) => x+y
add5(11)(21)
add5: (x: Int)Int => Int
res5: Int = 32
add2
Int=>Int
def add2(x:Int)(y:Int) = x+y
add2(11)(21)
add2: (x: Int)(y: Int)Int
res2: Int = 32
(y: Int)Int
def add1(x:Int, y:Int) = x+y
def add2(x:Int)(y:Int) = x+y
val add1f = add1
val add2f = add2
add1: (x: Int, y: Int)Int
add2: (x: Int)(y: Int)Int
add1f: (Int, Int) => Int = $$Lambda$...
add2f: Int => (Int => Int) = $$Lambda$...
val add4 = (x:Int) => (y:Int) => x+y
def add5(x:Int) = (y:Int) => x+y
val add4p = add4(11)
val add5p = add5(11)
val r4 = add4p(21)
val r5 = add5p(21)
add4: Int => (Int => Int) = $$Lambda$
add5: (x: Int)Int => Int
add4p: Int => Int = $$Lambda$
add5p: Int => Int = $$Lambda$
r4: Int = 32
r5: Int = 32
def add1(x:Int, y:Int) = x+y
def add2(x:Int)(y:Int) = x+y
val add3 = (x:Int, y:Int) => x+y
val add4 = (x:Int) => (y:Int) => x+y
def add5(x:Int) = (y:Int) => x+y
val add1p = add1(11, _) /* x=>add1(11, x) */
val add2p = add2(11)
val add3p = add3(11, _) /* x=>add3(11, x) */
val add4p = add4(11)
val add5p = add5(11)
val fs = List(add1p, add2p, add3p, add4p, add5p)
for f <- fs yield f(21)
fs: List[Int => Int] = List($$Lambda$,$$Lambda$,$$Lambda$,$$Lambda$,$$Lambda$)
res1: List[Int] = List(32, 32, 32, 32, 32)
foldLeft
is curried
xss.foldLeft (z) (f)
xss.foldLeft (z, f)
def a (x:Int) = x + 1;
val b = (x:Int) => x + 1;
val c = new Function[Int,Int] { def apply(x:Int) = x + 1 }
val d : PartialFunction[Int, Int] = { case i: Int => i + 1 }
val fs = List(a,b,c,d)
for f <- fs yield f(4)
fs: List[Int => Int] = List($$Lambda$, $$Lambda$, <function1>, <function1>)
res1: List[Int] = List(5, 5, 5, 5)
def
defines a method
=>
defines a function
apply
e:X=>Y
e(args)
=== e.apply(args)
class C:
var n = 5
def add(x:Int) =
this.n + x
var x = C()
var f = x.add
scala> x.add(10)
val res2: Int = 15
scala> f(100)
val res3: Int = 105
class C {
n = 5;
add(x) {
return this.n + x; } }
var x = new C()
var f = x.add
> x.add(10)
15
> f(100)
Uncaught TypeError: Cannot read properties of undefined (reading 'n')
at add (REPL6:4:16)
class C {
n = 5;
add(x) {
return this.n + x; } }
var x = new C()
var f = x.add.bind(x)
> x.add(10)
15
> f(100)
105