-
Notifications
You must be signed in to change notification settings - Fork 30
/
scala_sample.scala
78 lines (62 loc) · 1.9 KB
/
scala_sample.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
72
73
74
75
76
77
78
package fpinscala.datastructures
sealed trait List[+A]
case object Nil extends List[Nothing]
case class Cons[+A](head: A, tail: List[A]) extends List[A]
object List {
def foldLeft[A,B](as: List[A], z: B)(f: (B, A) => B): B = {
@annotation.tailrec
def g(rest: List[A], ret: B) : B = {
rest match {
case Nil => ret
case Cons(x, xs) => g(xs, f(ret, x))
}
}
g(as, z)
}
def foldRight[A,B](as: List[A], z: B)(f: (A, B) => B): B =
foldLeft(reverse(as), z)((b,a) => f(a,b))
def concat[A](l: List[List[A]]): List[A] =
foldRight[A,List[A]](reverse(l), (Cons(a,Nil)))(Cons(_,_))
def append[A](l: List[A])(a:A): List[A] =
foldRight[A,List[A]](reverse(l), (Cons(a,Nil)))(Cons(_,_))
def reverse[A](l: List[A]): List[A] =
foldLeft[A,List[A]](l, Nil)((b,a) => Cons(a,b))
def drop[A](l: List[A], n: Int): List[A] = {
@annotation.tailrec
def g(rest: List[A], n: Int) : List[A] = {
if (n > 0) g(tail(rest), n-1)
else rest
}
g(l, n)
}
def productL(ns: List[Double]) =
foldLeft(ns, 1.0)(_ * _)
def length2[A](as: List[A]): Int =
foldRight(as, 0)((_,b) => 1 + b)
@annotation.tailrec
def dropWhile[A](as: List[A])(f: A => Boolean): List[A] =
as match {
case Cons(h,t) if f(h) => dropWhile(t)(f)
case _ => as
}
def init[A](l: List[A]): List[A] = {
@annotation.tailrec
def g(rest: List[A], ret: List[A]) : List[A] = {
rest match {
case Cons(x, Nil) => ret
case Cons(x, Cons(_, Nil)) => Cons(x, ret)
case Cons(x, Cons(y, ys)) => g(Cons(y, ys), Cons(x, ret))
case Nil => Nil
}
}
reverse(g(l, Nil))
}
def lengthL[A](as: List[A]): Int =
foldLeft(as, 0)((b,_) => 1 + b)
def sumL(ns: List[Int]) =
foldLeft(ns, 0)(_ + _)
def sum2(ns: List[Int]) =
foldRight(ns, 0)(_ + _)
def product2(ns: List[Double]) =
foldRight(ns, 1.0)(_ * _)
}