abstract class List case class Nil extends List case class Cons(Int head, List tail)
Warm-up exercise: In C/C++, we have primitive types (int,
double, char, etc.) and derived types (pointer to T,
array of T) such as int* or int[10]. Model this with
three case classes that extend a common superclass Type
int,
double, char, etc.) or reference types (objects,
arrays)def fac(n : Int) : Int = if (n == 0) 1 else n * fac(n - 1) fac: (Int)Int val c = fac _ c: (Int) => Int = <function>
(Int)Int vs. (Int) => Int.
When you work with functions, you always use the =>fac must either be followed by an argument
(to make an Int) or by an _ (to make an (Int) =>
Int)1 -> 1 2 -> 2 3 -> 6 4 -> 24 5 -> 120 ... 10 -> 3628800
def table(from: Int, to : Int, f : (Int) => Int)
def table(from : int, to : Int, f : (Int) => Int) {
var i = from;
while (i <= to) {
println(i + " -> " + f(i))
i += 1
}
}
table: (Int,Int,(Int) => Int)Unit
table(1, 10, fac _)
y = 2 * x + 1
val a = 2 val b = 1 y = a * x + b
"Hello"table(10, (x : Int) => x * x)
def sq(x : Int) = x * x table(10, sq _)
fac(-1) or
sqrt(-1) doesn't blow upprotect(f)(x) = if (x >= 0) f(x) else 0protect takes a function and produces a
function
def protect(f : (Int) => Int) : (Int) => Int = result
λ x . if (x >= 0) f(x) else 0
x : Type => body instead of λ
x . body
(x : Int) => if (x >= 0) f(x) else 0
def protect(f : (Int) => Int) = (x : Int) => if (x >= 0) f(x) else 0 protect: ((Int) => Int)(Int) => Int table(-3, 3 ,protect(fac _)) -3 -> 0 -2 -> 0 -1 -> 0 0 -> 1 1 -> 1 2 -> 2 3 -> 6
List[A] class
count(p : (A) => Boolean) : Int filter(p : (A) => Boolean) : List[A] map(f: (A) => B) : List[B]
val lst = List("Mary", "had", "a", "little", "lamb")
val cnt = lst.count((s : String) => s.length <= 3)
val cnt = lst.count((s) => s.length <= 3)
val cnt = lst.count(s => s.length <= 3)
val cnt = lst.count(_.length <= 3)
int cnt = 0; for (String s : lst) if (s.length() <= 3) cnt++;
