Skip to content
Snippets Groups Projects
Commit 13a85f69 authored by Martin Odersky's avatar Martin Odersky
Browse files

Updates to week 2

parent 6a6afb64
No related branches found
No related tags found
No related merge requests found
...@@ -47,7 +47,7 @@ This definition introduces two entities: ...@@ -47,7 +47,7 @@ This definition introduces two entities:
- A \red{constructor} `Rational` to create elements of this type. - A \red{constructor} `Rational` to create elements of this type.
Scala keeps the names of types and values in \red{different namespaces}. Scala keeps the names of types and values in \red{different namespaces}.
So there's no conflict between the two defintions of `Rational`. So there's no conflict between the two definitions of `Rational`.
Objects Objects
======= =======
...@@ -106,11 +106,11 @@ Implementing Rational Arithmetic ...@@ -106,11 +106,11 @@ Implementing Rational Arithmetic
r.numer * s.denom + s.numer * r.denom, r.numer * s.denom + s.numer * r.denom,
r.denom * s.denom) r.denom * s.denom)
def makeString(r: Rational) = def makeString(r: Rational): String =
r.numer + "/" + r.denom s"${r.numer}/${r.denom}"
\begin{worksheet} \begin{worksheet}
\verb@makeString(addRational(new Rational(1, 2), new Rational(2, 3)))@ \wsf 7/6 \verb@makeString(addRational(Rational(1, 2), Rational(2, 3)))@ \wsf 7/6
\end{worksheet} \end{worksheet}
...@@ -137,12 +137,12 @@ Here's a possible implementation: ...@@ -137,12 +137,12 @@ Here's a possible implementation:
def numer = x def numer = x
def denom = y def denom = y
def add(r: Rational) = def add(r: Rational) =
new Rational(numer * r.denom + r.numer * denom, Rational(numer * r.denom + r.numer * denom,
denom * r.denom) denom * r.denom)
def mul(r: Rational) = ... def mul(r: Rational) = ...
... ...
override def toString = numer + "/" + denom override def toString = s"$numer/$denom"
} end Rational
\red{Remark}: the modifier `override` declares that `toString` \red{Remark}: the modifier `override` declares that `toString`
redefines a method that already exists (in the class `java.lang.Object`). redefines a method that already exists (in the class `java.lang.Object`).
...@@ -153,9 +153,9 @@ Calling Methods ...@@ -153,9 +153,9 @@ Calling Methods
Here is how one might use the new `Rational` abstraction: Here is how one might use the new `Rational` abstraction:
val x = new Rational(1, 3) val x = Rational(1, 3)
val y = new Rational(5, 7) val y = Rational(5, 7)
val z = new Rational(3, 2) val z = Rational(3, 2)
x.add(y).mul(z) x.add(y).mul(z)
Exercise Exercise
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment