5 def push
[B
>: A
](elem
: B
): Stack
[B
]
10 case class EmptyStack
[A
]() extends Stack
[A
] {
11 def push
[B
>: A
](elem
: B
): Stack
[B
] = ElemStack(elem
, this)
12 def top
: A
= throw new Exception
13 def pop
: Stack
[A
] = throw new Exception
16 case class ElemStack
[A
](top
: A
, rest
: Stack
[A
]) extends Stack
[A
] {
17 def push
[B
>: A
](elem
: B
): Stack
[B
] = ElemStack(elem
, this)
18 def pop
: Stack
[A
] = rest
19 override def toString
= s
"${top.toString()},${rest.toString()}"
24 // Construction, pop and toString.
25 val a
= EmptyStack().push("hello").push("world").push("it's fun").pop
27 assert(a
.toString() == "world,hello,EmptyStack()")
30 val b
= EmptyStack().push(1).push(3)
31 println(s
"b.top: ${b.top}")
37 val c
: Stack
[Bar
] = EmptyStack().push(new Bar()).push(new Bar())
38 assert(c
.top
.isInstanceOf
[Bar
])
39 assert(c
.top
.isInstanceOf
[Foo
])
42 val d
: Stack
[Foo
] = EmptyStack().push(new Bar()).push(new Bar())
43 assert(d
.top
.isInstanceOf
[Foo
])
47 abstract sealed class Temperature
{
51 case class Celsius(v
: Double
) extends Temperature
{
53 override def toString
= s
"$v° C"
56 case class Kelvin(v
: Double
) extends Temperature
{
58 override def toString
= s
"$v° K"
62 implicit def toCelsius(temp
: Kelvin
): Celsius
= new Celsius(temp
.v
+ 273.15)
63 implicit def toCelsius(temp
: Int
): Celsius
= new Celsius(temp
)
64 implicit def toKelvin(temp
: Celsius
): Kelvin
= new Kelvin(temp
.v
- 273.15)
65 implicit def toKelvin(temp
: Int
): Kelvin
= new Kelvin(temp
)
72 val c
: Kelvin
= Celsius(10)
74 val e
: Temperature
= d
81 def addStream(s1
: Stream
[Int
], s2
: Stream
[Int
]): Stream
[Int
] =
82 (s1
.head
+ s2
.head
) #
:: addStream(s1
.tail
, s2
.tail
)
84 lazy val fib
: Stream
[Int
] = 0 #
:: 1 #
:: addStream(fib
, fib
.tail
)
87 println(fib
.take(30).toList
)
90 def main(args
: Array
[String
]): Unit
= {