summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--03-lexical-syntax.md102
-rw-r--r--04-identifiers-names-and-scopes.md8
-rw-r--r--05-types.md86
-rw-r--r--06-basic-declarations-and-definitions.md94
-rw-r--r--07-classes-and-objects.md96
-rw-r--r--08-expressions.md146
-rw-r--r--09-implicit-parameters-and-views.md46
-rw-r--r--10-pattern-matching.md66
-rw-r--r--11-top-level-definitions.md24
-rw-r--r--12-xml-expressions-and-patterns.md12
-rw-r--r--13-user-defined-annotations.md4
-rw-r--r--14-the-scala-standard-library.md40
-rw-r--r--15-syntax-summary.md6
-rw-r--r--_includes/numbering.css4
-rw-r--r--_layouts/default.yml2
15 files changed, 367 insertions, 369 deletions
diff --git a/03-lexical-syntax.md b/03-lexical-syntax.md
index 503445da3f..c1b4d7f4ba 100644
--- a/03-lexical-syntax.md
+++ b/03-lexical-syntax.md
@@ -16,7 +16,7 @@ to _Scala mode_, and literal characters `‘c’` refer to the ASCII fragment `\
In Scala mode, _Unicode escapes_ are replaced by the corresponding
Unicode character with the given hexadecimal code.
-```
+```ebnf
UnicodeEscape ::= ‘\‘ ‘u‘ {‘u‘} hexDigit hexDigit hexDigit hexDigit
hexDigit ::= ‘0’ | … | ‘9’ | ‘A’ | … | ‘F’ | ‘a’ | … | ‘f’
```
@@ -45,7 +45,7 @@ classes (Unicode general category given in parentheses):
## Identifiers
-```
+```ebnf
op ::= opchar {opchar}
varid ::= lower idrest
plainid ::= upper idrest
@@ -70,7 +70,7 @@ of all characters excluding the backquotes themselves.
As usual, a longest match rule applies. For instance, the string
-```
+```scala
big_bob++=`def`
```
@@ -85,7 +85,7 @@ User programs should not define identifiers which contain `‘$’` characters.
The following names are reserved words instead of being members of the
syntactic class `id` of lexical identifiers.
-```
+```scala
abstract case catch class def
do else extends false final
finally for forSome if implicit
@@ -100,15 +100,15 @@ _ : = => <- <: <% >: # @
The Unicode operators `\u21D2 $\Rightarrow$` and `\u2190 $\leftarrow$`, which have the ASCII
equivalents `=>` and `<-`, are also reserved.
-### Example:
+### Example
-```
+```scala
x Object maxIndex p2p empty_?
+ `yield` αρετη _y dot_product_*
__system _MAX_LEN_
```
-### Example:
+### Example
When one needs to access Java identifiers that are reserved words in Scala, use backquote-enclosed strings.
For instance, the statement `Thread.yield()` is illegal, since
`yield` is a reserved word in Scala. However, here's a
@@ -117,7 +117,7 @@ work-around: `` Thread.`yield`() ``
## Newline Characters
-```
+```ebnf
semi ::= ‘;’ | nl {nl}
```
@@ -132,7 +132,7 @@ as the special token “nl” if the three following criteria are satisfied:
The tokens that can terminate a statement are: literals, identifiers
and the following delimiters and reserved words:
-```
+```scala
this null true false return type <xml-start>
_ ) ] }
```
@@ -140,7 +140,7 @@ _ ) ] }
The tokens that can begin a statement are all Scala tokens _except_
the following delimiters and reserved words:
-```
+```scala
catch else extends finally forSome match
with yield , . ; : = => <- <: <%
>: # [ ) ] }
@@ -207,12 +207,12 @@ A single new line token is accepted
- in front of a [parameter clause](06-basic-declarations-and-definitions.html#function-declarations-and-definitions), and
- after an [annotation](13-user-defined-annotations.html#user-defined-annotations).
-### Example:
+### Example
The newline tokens between the two lines are not
treated as statement separators.
-```
+```scala
if (x > 0)
x = x - 1
@@ -226,9 +226,9 @@ type
IntList = List[Int]
```
-### Example:
+### Example
-```
+```scala
new Iterator[Int]
{
private var x = 0
@@ -240,7 +240,7 @@ new Iterator[Int]
With an additional newline character, the same code is interpreted as
an object creation followed by a local block:
-```
+```scala
new Iterator[Int]
{
@@ -250,9 +250,9 @@ new Iterator[Int]
}
```
-### Example:
+### Example
-```
+```scala
x < 0 ||
x > 10
```
@@ -260,15 +260,15 @@ new Iterator[Int]
With an additional newline character, the same code is interpreted as
two expressions:
-```
+```scala
x < 0 ||
x > 10
```
-### Example:
+### Example
-```
+```scala
def func(x: Int)
(y: Int) = x + y
```
@@ -276,15 +276,15 @@ def func(x: Int)
With an additional newline character, the same code is interpreted as
an abstract function definition and a syntactically illegal statement:
-```
+```scala
def func(x: Int)
(y: Int) = x + y
```
-### Example:
+### Example
-```
+```scala
@serializable
protected class Data { ... }
```
@@ -293,7 +293,7 @@ With an additional newline character, the same code is interpreted as
an attribute and a separate statement (which is syntactically
illegal).
-```
+```scala
@serializable
protected class Data { ... }
@@ -311,7 +311,7 @@ each case as in Java.
particular float and double.
-->
-```
+```ebnf
Literal ::= [‘-’] integerLiteral
| [‘-’] floatingPointLiteral
| booleanLiteral
@@ -324,7 +324,7 @@ Literal ::= [‘-’] integerLiteral
### Integer Literals
-```
+```ebnf
integerLiteral ::= (decimalNumeral | hexNumeral | octalNumeral)
[‘L’ | ‘l’]
decimalNumeral ::= ‘0’ | nonZeroDigit {digit}
@@ -356,16 +356,16 @@ is _pt_. The numeric ranges given by these types are:
|`Char` | $0$ to $2^{16}-1$ |
-### Example:
+### Example
-```
+```scala
0 21 0xFFFFFFFF -42L
```
### Floating Point Literals
-```
+```ebnf
floatingPointLiteral ::= digit {digit} ‘.’ digit {digit} [exponentPart] [floatType]
| ‘.’ digit {digit} [exponentPart] [floatType]
| digit {digit} exponentPart [floatType]
@@ -385,24 +385,24 @@ If a floating point literal in a program is followed by a token
starting with a letter, there must be at least one intervening
whitespace character between the two tokens.
-### Example:
+### Example
-```
+```scala
0.0 1e30f 3.14159f 1.0e-100 .1
```
-### Example:
+### Example
The phrase `1.toString` parses as three different tokens:
the integer literal `1`, a `.`, and the identifier `toString`.
-### Example:
+### Example
`1.` is not a valid floating point literal because the mandatory digit after the `.` is missing.
### Boolean Literals
-```
+```ebnf
booleanLiteral ::= ‘true’ | ‘false’
```
@@ -412,7 +412,7 @@ members of type `Boolean`.
### Character Literals
-```
+```ebnf
characterLiteral ::= ‘'’ (printableChar | charEscapeSeq) ‘'’
```
@@ -420,9 +420,9 @@ A character literal is a single character enclosed in quotes.
The character is either a printable unicode character or is described
by an [escape sequence](#escape-sequences).
-### Example:
+### Example
-```
+```scala
'a' '\u0041' '\n' '\t'
```
@@ -435,7 +435,7 @@ the octal escape `'\12'` ([see here](#escape-sequences)).
### String Literals
-```
+```ebnf
stringLiteral ::= ‘"’ {stringElement} ‘"’
stringElement ::= printableCharNoDoubleQuote | charEscapeSeq
```
@@ -447,16 +447,16 @@ contains a double quote character, it must be escaped,
i.e. `"\""`. The value of a string literal is an instance of
class `String`.
-### Example:
+### Example
-```
+```scala
"Hello,\nWorld!"
"This string contains a \" character."
```
#### Multi-Line String Literals
-```
+```ebnf
stringLiteral ::= ‘"""’ multiLineChars ‘"""’
multiLineChars ::= {[‘"’] [‘"’] charNoDoubleQuote} {‘"’}
```
@@ -469,9 +469,9 @@ must not necessarily be printable; newlines or other
control characters are also permitted. Unicode escapes work as everywhere else, but none
of the escape sequences [here](#escape-sequences) are interpreted.
-### Example:
+### Example
-```
+```scala
"""the present string
spans three
lines."""
@@ -479,7 +479,7 @@ of the escape sequences [here](#escape-sequences) are interpreted.
This would produce the string:
-```
+```scala
the present string
spans three
lines.
@@ -489,7 +489,7 @@ The Scala library contains a utility method `stripMargin`
which can be used to strip leading whitespace from multi-line strings.
The expression
-```
+```scala
"""the present string
|spans three
|lines.""".stripMargin
@@ -497,7 +497,7 @@ The expression
evaluates to
-```
+```scala
the present string
spans three
lines.
@@ -536,7 +536,7 @@ string literal does not start a valid escape sequence.
### Symbol literals
-```
+```ebnf
symbolLiteral ::= ‘'’ plainid
```
@@ -544,7 +544,7 @@ A symbol literal `'x` is a shorthand for the expression
`scala.Symbol("x")`. `Symbol` is a [case class](07-classes-and-objects.html#case-classes),
which is defined as follows.
-```
+```scala
package scala
final case class Symbol private (name: String) {
override def toString: String = "'" + name
@@ -580,7 +580,7 @@ angle bracket '<' in the following circumstance: The '<' must be
preceded either by whitespace, an opening parenthesis or an opening
brace and immediately followed by a character starting an XML name.
-```
+```ebnf
( whitespace | ‘(’ | ‘{’ ) ‘<’ (XNameStart | ‘!’ | ‘?’)
XNameStart ::= ‘_’ | BaseChar | Ideographic // as in W3C XML, but without ‘:’
@@ -600,12 +600,12 @@ The scanner switches from XML mode to Scala mode if either
Note that no Scala tokens are constructed in XML mode, and that comments are interpreted
as text.
-### Example:
+### Example
The following value definition uses an XML literal with two embedded
Scala expressions:
-```
+```scala
val b = <book>
<title>The Scala Language Specification</title>
<version>{scalaBook.version}</version>
diff --git a/04-identifiers-names-and-scopes.md b/04-identifiers-names-and-scopes.md
index 96b4f283e9..0a3f9ca3cf 100644
--- a/04-identifiers-names-and-scopes.md
+++ b/04-identifiers-names-and-scopes.md
@@ -39,7 +39,7 @@ scopes.
Note that shadowing is only a partial order. In a situation like
-```
+```scala
val x = 1
{
import p.x
@@ -71,11 +71,11 @@ namespace as the identifier. It is an error if $T$ is not a [value type](05-type
The type of $e.x$ is the member type of the referenced entity in $T$.
-### Example:
+### Example
Assume the following two definitions of a objects named `X` in packages `P` and `Q`.
-```
+```scala
package P {
object X { val x = 1; val y = 2 }
}
@@ -88,7 +88,7 @@ package Q {
The following program illustrates different kinds of bindings and
precedences between them.
-```
+```scala
package P { // `X' bound by package clause
import Console._ // `println' bound by wildcard import
object A {
diff --git a/05-types.md b/05-types.md
index c2996ddb4b..f614d15f8f 100644
--- a/05-types.md
+++ b/05-types.md
@@ -6,7 +6,7 @@ chapter: 3
# Types
-```
+```ebnf
Type ::= FunctionArgTypes ‘=>’ Type
| InfixType [ExistentialClause]
FunctionArgTypes ::= InfixType
@@ -66,7 +66,7 @@ the corresponding anonymous type function directly.
## Paths
-```
+```ebnf
Path ::= StableId
| [id ‘.’] this
StableId ::= id
@@ -103,7 +103,7 @@ forms.
### Singleton Types
-```
+```ebnf
SimpleType ::= Path ‘.’ type
```
@@ -117,7 +117,7 @@ declared to be a subtype of trait `scala.Singleton`.
### Type Projection
-```
+```ebnf
SimpleType ::= SimpleType ‘#’ id
```
@@ -132,7 +132,7 @@ If $x$ references an abstract type member, then $T$ must be a
### Type Designators
-```
+```ebnf
SimpleType ::= StableId
```
@@ -149,7 +149,7 @@ A qualified type designator has the form `p.t` where `p` is
a [path](#paths) and _t_ is a type name. Such a type designator is
equivalent to the type projection `p.type#t`.
-### Example:
+### Example
Some type designators and their expansions are listed below. We assume
a local type parameter $t$, a value `maintable`
@@ -166,7 +166,7 @@ with a type member `Node` and the standard class `scala.Int`,
### Parameterized Types
-```
+```ebnf
SimpleType ::= SimpleType TypeArgs
TypeArgs ::= ‘[’ Types ‘]’
```
@@ -182,10 +182,10 @@ well-formed if each actual type parameter
_conforms to its bounds_, i.e. $\sigma L_i <: T_i <: \sigma U_i$ where $\sigma$ is the
substitution $[ a_1 := T_1 , \ldots , a_n := T_n ]$.
-### Example:
+### Example
Given the partial type definitions:
-```
+```scala
class TreeMap[A <: Comparable[A], B] { … }
class List[A] { … }
class I extends Comparable[I] { … }
@@ -197,7 +197,7 @@ class G[M[ Z <: I ], I] { … }
the following parameterized types are well formed:
-```
+```scala
TreeMap[I, String]
List[I]
List[List[Boolean]]
@@ -206,12 +206,12 @@ F[List, Int]
G[S, String]
```
-### Example:
+### Example
Given the [above type definitions](example-parameterized-types),
the following types are ill-formed:
-```
+```scala
TreeMap[I] // illegal: wrong number of parameters
TreeMap[List[I], Int] // illegal: type parameter not within bound
@@ -226,7 +226,7 @@ G[S, Int] // illegal: S constrains its parameter to
### Tuple Types
-```
+```ebnf
SimpleType ::= ‘(’ Types ‘)’
```
@@ -240,7 +240,7 @@ class and product trait are defined at least as follows in the
standard Scala library (they might also add other methods and
implement other traits).
-```
+```scala
case class Tuple$n$[+T1, … , +$T_n$](_1: T1, … , _n: $T_n$)
extends Product_n[T1, … , $T_n$]
@@ -254,7 +254,7 @@ trait Product_n[+T1, … , +$T_n$] {
### Annotated Types
-```
+```ebnf
AnnotType ::= SimpleType {Annotation}
```
@@ -262,18 +262,18 @@ An annotated type $T$ `$a_1 , \ldots , a_n$`
attaches [annotations](13-user-defined-annotations.html#user-defined-annotations)
$a_1 , \ldots , a_n$ to the type $T$.
-### Example:
+### Example
The following type adds the `@suspendable` annotation to the type `String`:
-```
+```scala
String @suspendable
```
### Compound Types
-```
+```ebnf
CompoundType ::= AnnotType {‘with’ AnnotType} [Refinement]
| Refinement
Refinement ::= [nl] ‘{’ RefineStat {semi RefineStat} ‘}’
@@ -310,12 +310,12 @@ A compound type may also consist of just a refinement
`{ $R$ }` with no preceding component types. Such a type is
equivalent to `AnyRef{ R }`.
-### Example:
+### Example
The following example shows how to declare and use a method which
a parameter type that contains a refinement with structural declarations.
-```
+```scala
case class Bird (val name: String) extends Object {
def fly(height: Int) = …
@@ -345,7 +345,7 @@ a value `callsign` and a `fly` method.
### Infix Types
-```
+```ebnf
InfixType ::= CompoundType {id [nl] CompoundType}
```
@@ -374,7 +374,7 @@ $t_0 \mathit{op_1} (t_1 \mathit{op_2} ( \ldots \mathit{op_n} t_n) \ldots)$.
### Function Types
-```
+```ebnf
Type ::= FunctionArgs ‘=>’ Type
FunctionArgs ::= InfixType
| ‘(’ [ ParamType {‘,’ ParamType } ] ‘)’
@@ -397,7 +397,7 @@ $(T_1 , \ldots , T_n) \Rightarrow U$ is a shorthand for the class type
`Function$_n$[T1 , … , $T_n$, U]`. Such class
types are defined in the Scala library for $n$ between 0 and 9 as follows.
-```
+```scala
package scala
trait Function_n[-T1 , … , -T$_n$, +R] {
def apply(x1: T1 , … , x$_n$: T$_n$): R
@@ -410,7 +410,7 @@ result type and contravariant in their argument types.
### Existential Types
-```
+```ebnf
Type ::= InfixType ExistentialClauses
ExistentialClauses ::= ‘forSome’ ‘{’ ExistentialDcl
{semi ExistentialDcl} ‘}’
@@ -479,7 +479,7 @@ fresh type name and $T'$ results from $T$ by replacing every occurrence of
#### Placeholder Syntax for Existential Types
-```
+```ebnf
WildcardType ::= ‘_’ TypeBounds
```
@@ -499,7 +499,7 @@ $T$ is a wildcard type `_$\;$>:$\,L\,$<:$\,U$`. Then $T$ is equivalent to the
existential
type
-```
+```scala
$p.c[\mathit{targs},t,\mathit{targs}']$ forSome { type $t$ >: $L$ <: $U$ }
```
@@ -510,18 +510,18 @@ or [tuple types](#tuple-types).
Their expansion is then the expansion in the equivalent parameterized
type.
-### Example:
+### Example
Assume the class definitions
-```
+```scala
class Ref[T]
abstract class Outer { type T } .
```
Here are some examples of existential types:
-```
+```scala
Ref[T] forSome { type T <: java.lang.Number }
Ref[x.T] forSome { val x: Outer }
Ref[x_type # T] forSome { type x_type <: Outer with Singleton }
@@ -530,35 +530,35 @@ Ref[x_type # T] forSome { type x_type <: Outer with Singleton }
The last two types in this list are equivalent.
An alternative formulation of the first type above using wildcard syntax is:
-```
+```scala
Ref[_ <: java.lang.Number]
```
-### Example:
+### Example
The type `List[List[_]]` is equivalent to the existential type
-```
+```scala
List[List[t] forSome { type t }] .
```
-### Example:
+### Example
Assume a covariant type
-```
+```scala
class List[+T]
```
The type
-```
+```scala
List[T] forSome { type T <: java.lang.Number }
```
is equivalent (by simplification rule 4 above) to
-```
+```scala
List[java.lang.Number] forSome { type T <: java.lang.Number }
```
@@ -606,7 +606,7 @@ def c (x: Int) (y: String, z: String): String
produce the typings
-```
+```scala
a: => Int
b: (Int) Boolean
c: (Int) (String, String) String
@@ -628,14 +628,14 @@ take type arguments `$S_1 , \ldots , S_n$` which
The declarations
-```
+```scala
def empty[A]: List[A]
def union[A <: Comparable[A]] (x: Set[A], xs: Set[A]): Set[A]
```
produce the typings
-```
+```scala
empty : [A >: Nothing <: Any] List[A]
union : [A >: Nothing <: Comparable[A]] (x: Set[A], xs: Set[A]) Set[A] .
```
@@ -671,7 +671,7 @@ same name, we model
An overloaded type consisting of type alternatives $T_1 \commadots T_n (n \geq 2)$ is denoted internally $T_1 \overload \ldots \overload T_n$.
-### Example:
+### Example
```
def println: Unit
def println(s: String): Unit = $\ldots$
@@ -689,7 +689,7 @@ println: => Unit $\overload$
[A] (A) (A => String) Unit
```
-### Example:
+### Example
```
def f(x: T): T = $\ldots$
val f = 0
@@ -944,7 +944,7 @@ The least upper bound or greatest lower bound
of a set of types does not always exist. For instance, consider
the class definitions
-```
+```scala
class A[+T] {}
class B extends A[B]
class C extends A[C]
@@ -980,7 +980,7 @@ to a type $T$, written $S <:_w
T$, if $S <: T$ or both $S$ and $T$ are primitive number types
and $S$ precedes $T$ in the following ordering.
-```
+```scala
Byte $<:_w$ Short
Short $<:_w$ Int
Char $<:_w$ Int
diff --git a/06-basic-declarations-and-definitions.md b/06-basic-declarations-and-definitions.md
index 4507dab63f..e0fdf051c2 100644
--- a/06-basic-declarations-and-definitions.md
+++ b/06-basic-declarations-and-definitions.md
@@ -7,7 +7,7 @@ chapter: 4
# Basic Declarations and Definitions
-```
+```ebnf
Dcl ::= ‘val’ ValDcl
| ‘var’ VarDcl
| ‘def’ FunDcl
@@ -102,7 +102,7 @@ case object Blue extends Color .
## Value Declarations and Definitions
-```
+```ebnf
Dcl ::= ‘val’ ValDcl
ValDcl ::= ids ‘:’ Type
PatVarDef ::= ‘val’ PatDef
@@ -128,7 +128,7 @@ its right hand side $e$ the first time the value is accessed.
A _constant value definition_ is of the form
-```
+```scala
final val x = e
```
@@ -145,7 +145,7 @@ value definition `val $p$ = $e$` is expanded as follows:
1. If the pattern $p$ has bound variables $x_1 , \ldots , x_n$, where $n > 1$:
-```
+```scala
val $\$ x$ = $e$ match {case $p$ => ($x_1 , \ldots , x_n$)}
val $x_1$ = $\$ x$._1
$\ldots$
@@ -156,13 +156,13 @@ Here, $\$ x$ is a fresh name.
2. If $p$ has a unique bound variable $x$:
-```
+```scala
val $x$ = $e$ match { case $p$ => $x$ }
```
3. If $p$ has no bound variables:
-```
+```scala
$e$ match { case $p$ => ()}
```
@@ -170,7 +170,7 @@ $e$ match { case $p$ => ()}
The following are examples of value definitions
-```
+```scala
val pi = 3.1415
val pi: Double = 3.1415 // equivalent to first definition
val Some(x) = f() // a pattern definition
@@ -179,7 +179,7 @@ val x :: xs = mylist // an infix pattern definition
The last two definitions have the following expansions.
-```
+```scala
val x = f() match { case Some(x) => x }
val x$\$$ = mylist match { case x :: xs => (x, xs) }
@@ -200,7 +200,7 @@ sequence of value definitions `val $p_1: T$ = $e$; ...; val $p_n: T$ = $e$`.
## Variable Declarations and Definitions
-```
+```ebnf
Dcl ::= ‘var’ VarDcl
PatVarDef ::= ‘var’ VarDef
VarDcl ::= ids ‘:’ Type
@@ -211,7 +211,7 @@ VarDef ::= PatDef
A variable declaration `var $x$: $T$` is equivalent to the declarations
of both a _getter function_ $x$ *and* a _setter function_ `$x$_=`:
-```
+```scala
def $x$: $T$
def $x$_= ($y$: $T$): Unit
```
@@ -268,7 +268,7 @@ seconds. Its implementation contains tests that allow only legal
values to be assigned to these fields. The user code, on the other
hand, accesses these fields just like normal variables.
-```
+```scala
class TimeOfDayVar {
private var h: Int = 0
private var m: Int = 0
@@ -304,7 +304,7 @@ the sequence of variable definitions
<!-- TODO: Higher-kinded tdecls should have a separate section -->
-```
+```ebnf
Dcl ::= ‘type’ {nl} TypeDcl
TypeDcl ::= id [TypeParamClause] [‘>:’ Type] [‘<:’ Type]
Def ::= type {nl} TypeDef
@@ -354,7 +354,7 @@ an abstract type is directly or indirectly its own upper or lower bound.
The following are legal type declarations and definitions:
-```
+```scala
type IntList = List[Integer]
type T <: Comparable[T]
type Two[A] = Tuple2[A, A]
@@ -363,7 +363,7 @@ type MyCollection[+X] <: Iterable[X]
The following are illegal:
-```
+```scala
type Abs = Comparable[Abs] // recursive type alias
type S <: T // S, T are bounded by themselves.
@@ -384,7 +384,7 @@ objects of type $S$.
The `Predef` object contains a definition which establishes `Pair`
as an alias of the parameterized class `Tuple2`:
-```
+```scala
type Pair[+A, +B] = Tuple2[A, B]
object Pair {
def apply[A, B](x: A, y: B) = Tuple2(x, y)
@@ -396,14 +396,14 @@ As a consequence, for any two types $S$ and $T$, the type
`Pair[$S$, $T\,$]` is equivalent to the type `Tuple2[$S$, $T\,$]`.
`Pair` can also be used as a constructor instead of `Tuple2`, as in:
-```
+```scala
val x: Pair[Int, String] = new Pair(1, "abc")
```
## Type Parameters
-```
+```ebnf
TypeParamClause ::= ‘[’ VariantTypeParam {‘,’ VariantTypeParam} ‘]’
VariantTypeParam ::= {Annotation} [‘+’ | ‘-’] TypeParam
TypeParam ::= (id | ‘_’) [TypeParamClause] [‘>:’ Type] [‘<:’ Type] [‘:’ Type]
@@ -443,7 +443,7 @@ The above scoping restrictions are generalized to the case of nested type parame
###### Example
Here are some well-formed type parameter clauses:
-```
+```scala
[S, T]
[@specialized T, U]
[Ex <: Throwable]
@@ -457,7 +457,7 @@ Here are some well-formed type parameter clauses:
The following type parameter clauses are illegal:
-```
+```scala
[A >: A] // illegal, `A' has itself as bound
[A <: B, B <: C, C <: A] // illegal, `A' has itself as bound
[A, B, C >: A <: B] // illegal lower bound `A' of `C' does
@@ -518,7 +518,7 @@ appear anywhere without restricting its legal variance annotations.
###### Example
The following variance annotation is legal.
-```
+```scala
abstract class P[+A, +B] {
def fst: A; def snd: B
}
@@ -528,14 +528,14 @@ With this variance annotation, type instances
of $P$ subtype covariantly with respect to their arguments.
For instance,
-```
+```scala
P[IOException, String] <: P[Throwable, AnyRef]
```
If the members of $P$ are mutable variables,
the same variance annotation becomes illegal.
-```
+```scala
abstract class Q[+A, +B](x: A, y: B) {
var fst: A = x // **** error: illegal variance:
var snd: B = y // `A', `B' occur in invariant position.
@@ -545,7 +545,7 @@ abstract class Q[+A, +B](x: A, y: B) {
If the mutable variables are object-private, the class definition
becomes legal again:
-```
+```scala
abstract class R[+A, +B](x: A, y: B) {
private[this] var fst: A = x // OK
private[this] var snd: B = y // OK
@@ -557,7 +557,7 @@ abstract class R[+A, +B](x: A, y: B) {
The following variance annotation is illegal, since $a$ appears
in contravariant position in the parameter of `append`:
-```
+```scala
abstract class Sequence[+A] {
def append(x: Sequence[A]): Sequence[A]
// **** error: illegal variance:
@@ -568,15 +568,15 @@ abstract class Sequence[+A] {
The problem can be avoided by generalizing the type of `append`
by means of a lower bound:
-```
+```scala
abstract class Sequence[+A] {
def append[B >: A](x: Sequence[B]): Sequence[B]
}
```
-### Example:
+### Example
-```
+```scala
abstract class OutputChannel[-A] {
def write(x: A): Unit
}
@@ -591,7 +591,7 @@ on which one can write only strings.
## Function Declarations and Definitions
-```
+```ebnf
Dcl ::= ‘def’ FunDcl
FunDcl ::= FunSig ‘:’ Type
Def ::= ‘def’ FunDef
@@ -655,7 +655,7 @@ be pairwise distinct.
###### Example
In the method
-```
+```scala
def compare[T](a: T = 0)(b: T = a) = (a == b)
```
@@ -664,7 +664,7 @@ type. When applying `compare()`, the default value `0` is inserted
and `T` is instantiated to `Int`. The methods computing the default
arguments have the form:
-```
+```scala
def compare$\$$default$\$$1[T]: Int = 0
def compare$\$$default$\$$2[T](a: T): T = a
```
@@ -673,7 +673,7 @@ def compare$\$$default$\$$2[T](a: T): T = a
### By-Name Parameters
-```
+```ebnf
ParamType ::= ‘=>’ Type
```
@@ -693,7 +693,7 @@ by-name modifier is also disallowed for
###### Example
The declaration
-```
+```scala
def whileLoop (cond: => Boolean) (stat: => Unit): Unit
```
@@ -703,7 +703,7 @@ call-by-name.
### Repeated Parameters
-```
+```ebnf
ParamType ::= Type ‘*’
```
@@ -732,7 +732,7 @@ with a repeated parameter.
The following method definition computes the sum of the squares of a
variable number of integer arguments.
-```
+```scala
def sum(args: Int*) = {
var result = 0
for (arg <- args) result += arg * arg
@@ -743,7 +743,7 @@ def sum(args: Int*) = {
The following applications of this method yield `0`, `1`,
`6`, in that order.
-```
+```scala
sum()
sum(1)
sum(1, 2, 3)
@@ -751,27 +751,27 @@ sum(1, 2, 3)
Furthermore, assume the definition:
-```
+```scala
val xs = List(1, 2, 3)
```
The following application of method `sum` is ill-formed:
-```
+```scala
sum(xs) // ***** error: expected: Int, found: List[Int]
```
By contrast, the following application is well formed and yields again
the result `6`:
-```
+```scala
sum(xs: _*)
```
### Procedures
-```
+```ebnf
FunDcl ::= FunSig
FunDef ::= FunSig [nl] ‘{’ Block ‘}’
```
@@ -791,7 +791,7 @@ E.g., `def $f$($\mathit{ps}$) {$\mathit{stats}$}` is equivalent to
###### Example
Here is a declaration and a definition of a procedure named `write`:
-```
+```scala
trait Writer {
def write(str: String)
}
@@ -802,7 +802,7 @@ object Terminal extends Writer {
The code above is implicitly completed to the following code:
-```
+```scala
trait Writer {
def write(str: String): Unit
}
@@ -826,7 +826,7 @@ as $R$ conforms to $R'$.
###### Example
Assume the following definitions:
-```
+```scala
trait I {
def factorial(x: Int): Int
}
@@ -859,7 +859,7 @@ $T_j$ have the same erasure (\sref{sec:erasure}).
## Import Clauses
-```
+```ebnf
Import ::= ‘import’ ImportExpr {‘,’ ImportExpr}
ImportExpr ::= StableId ‘.’ (id | ‘_’ | ImportSelectors)
ImportSelectors ::= ‘{’ {ImportSelector ‘,’}
@@ -874,7 +874,7 @@ which are made available without qualification. A member $m$ of $p$ is
_importable_ if it is not [object-private](07-classes-and-objects.html#modifiers).
The most general form of an import expression is a list of _import selectors_
-```
+```scala
{ $x_1$ => $y_1 , \ldots , x_n$ => $y_n$, _ }
```
@@ -925,7 +925,7 @@ sequence of import clauses
###### Example
Consider the object definition:
-```
+```scala
object M {
def z = 0, one = 1
def add(x: Int, y: Int): Int = x + y
@@ -934,12 +934,12 @@ object M {
Then the block
-```
+```scala
{ import M.{one, z => zero, _}; add(zero, one) }
```
is equivalent to the block
-```
+```scala
{ M.add(M.z, M.one) }
```
diff --git a/07-classes-and-objects.md b/07-classes-and-objects.md
index d16be19586..4ad637f517 100644
--- a/07-classes-and-objects.md
+++ b/07-classes-and-objects.md
@@ -6,7 +6,7 @@ chapter: 5
# Classes and Objects
-```
+```ebnf
TmplDef ::= [`case'] `class' ClassDef
| [`case'] `object' ObjectDef
| `trait' TraitDef
@@ -18,7 +18,7 @@ are both defined in terms of _templates_.
## Templates
-```
+```ebnf
ClassTemplate ::= [EarlyDefs] ClassParents [TemplateBody]
TraitTemplate ::= [EarlyDefs] TraitParents [TemplateBody]
ClassParents ::= Constr {`with' AnnotType}
@@ -96,7 +96,7 @@ without introducing an alias name for it.
###### Example
Consider the following class definitions:
-```
+```scala
class Base extends Object {}
trait Mixin extends Base {}
object O extends Mixin {}
@@ -104,7 +104,7 @@ object O extends Mixin {}
In this case, the definition of `O` is expanded to:
-```
+```scala
object O extends Base with Mixin {}
```
@@ -141,14 +141,14 @@ it. But templates inheriting the `scala.DelayedInit` trait
can override the hook by re-implementing the `delayedInit`
method, which is defined as follows:
-```
+```scala
def delayedInit(body: => Unit)
```
### Constructor Invocations
-```
+```ebnf
Constr ::= AnnotType {`(' [Exprs] `)'}
```
@@ -199,7 +199,7 @@ $\mathcal{L}(C) = C, \mathcal{L}(C_n) \; \vec{+} \; \ldots \; \vec{+} \; \mathca
Here $\vec{+}$ denotes concatenation where elements of the right operand
replace identical elements of the left operand:
-```
+```scala
\[
\begin{array}{lcll}
\{a, A\} \;\vec{+}\; B &=& a, (A \;\vec{+}\; B) &{\bf if} \; a \not\in B \\
@@ -212,7 +212,7 @@ replace identical elements of the left operand:
###### Example
Consider the following class definitions.
-```
+```scala
abstract class AbsIterator extends AnyRef { ... }
trait RichIterator extends AbsIterator { ... }
class StringIterator extends AbsIterator { ... }
@@ -221,7 +221,7 @@ class Iter extends StringIterator with RichIterator { ... }
Then the linearization of class `Iter` is
-```
+```scala
{ Iter, RichIterator, StringIterator, AbsIterator, AnyRef, Any }
```
@@ -233,7 +233,7 @@ a linearization of a class always contains the linearization of its direct super
For instance, the linearization of `StringIterator` is
-```
+```scala
{ StringIterator, AbsIterator, AnyRef, Any }
```
@@ -241,7 +241,7 @@ which is a suffix of the linearization of its subclass `Iter`.
The same is not true for the linearization of mixins.
For instance, the linearization of `RichIterator` is
-```
+```scala
{ RichIterator, AbsIterator, AnyRef, Any }
```
@@ -312,7 +312,7 @@ defined or inherited) with the same name which both define default arguments.
###### Example
Consider the trait definitions:
-```
+```scala
trait A { def f: Int }
trait B extends A { def f: Int = 1 ; def g: Int = 2 ; def h: Int = 3 }
trait C extends A { override def f: Int = 4 ; def g: Int }
@@ -357,7 +357,7 @@ $M'$:
A stable member can only be overridden by a stable member.
For example, this is not allowed:
-```
+```scala
class X { val stable = 1}
class Y extends X { override var stable = 1 } // error
```
@@ -378,11 +378,11 @@ it is possible to add new defaults (if the corresponding parameter in the
superclass does not have a default) or to override the defaults of the
superclass (otherwise).
-### Example:
+### Example
Consider the definitions:
-```
+```scala
trait Root { type T <: Root }
trait A extends Root { type T <: A }
trait B extends Root { type T <: B }
@@ -396,7 +396,7 @@ which fails to subsume the binding `type T <: A` of `T`
in type `A`. The problem can be solved by adding an overriding
definition of type `T` in class `C`:
-```
+```scala
class C extends A with B { type T <: C }
```
@@ -418,7 +418,7 @@ necessary to make subtyping decidable [@kennedy-pierce:decidable]).
### Early Definitions
-```
+```ebnf
EarlyDefs ::= `{' [EarlyDef {semi EarlyDef}] `}' `with'
EarlyDef ::= {Annotation} {Modifier} PatVarDef
```
@@ -427,7 +427,7 @@ A template may start with an _early field definition_ clause,
which serves to define certain field values before the supertype
constructor is called. In a template
-```
+```scala
{ val $p_1$: $T_1$ = $e_1$
...
val $p_n$: $T_n$ = $e_n$
@@ -462,7 +462,7 @@ before the superclass constructor of the template is called.
Early definitions are particularly useful for
traits, which do not have normal constructor parameters. Example:
-```
+```scala
trait Greeting {
val name: String
val msg = "How are you, "+name
@@ -486,7 +486,7 @@ body, it would be initialized after the constructor of
## Modifiers
-```
+```ebnf
Modifier ::= LocalModifier
| AccessModifier
| `override'
@@ -634,7 +634,7 @@ and a later access will retry to evaluate its right hand side.
###### Example
The following code illustrates the use of qualified private:
-```
+```scala
package outerpkg.innerpkg
class Outer {
class Inner {
@@ -659,7 +659,7 @@ A useful idiom to prevent clients of a class from
constructing new instances of that class is to declare the class
`abstract` and `sealed`:
-```
+```scala
object m {
abstract sealed class C (x: Int) {
def nextC = new C(x + 1) {}
@@ -673,7 +673,7 @@ For instance, in the code above clients can create instances of class
object; it is not possible for clients to create objects of class
`m.C` directly. Indeed the following two lines are both in error:
-```
+```scala
new m.C(0) // **** error: C is abstract, so it cannot be instantiated.
new m.C(0) {} // **** error: illegal inheritance from sealed class.
```
@@ -684,7 +684,7 @@ constructor `private` ([example](#example-private-constructor)).
## Class Definitions
-```
+```ebnf
TmplDef ::= `class' ClassDef
ClassDef ::= id [TypeParamClause] {Annotation}
[AccessModifier] ClassParamClauses ClassTemplateOpt
@@ -699,7 +699,7 @@ ClassTemplateOpt ::= `extends' ClassTemplate | [[`extends'] TemplateBody]
The most general form of class definition is
-```
+```scala
class $c$[$\mathit{tps}\,$] $as$ $m$($\mathit{ps}_1$)$\ldots$($\mathit{ps}_n$) extends $t$ $\gap(n \geq 0)$.
```
@@ -760,10 +760,10 @@ which when applied to parameters conforming to types $\mathit{ps}$
initializes instances of type `$c$[$\mathit{tps}\,$]` by evaluating the template
$t$.
-### Example:
+### Example
The following example illustrates `val` and `var` parameters of a class `C`:
-```
+```scala
class C(x: Int, val y: String, var z: List[String])
val c = new C(1, "abc", List())
c.z = c.y :: c.z
@@ -771,7 +771,7 @@ c.z = c.y :: c.z
The following class can be created only from its companion module.
-```
+```scala
object Sensitive {
def makeSensitive(credentials: Certificate): Sensitive =
if (credentials == Admin) new Sensitive()
@@ -785,7 +785,7 @@ class Sensitive private () {
### Constructor Definitions
-```
+```ebnf
FunDef ::= `this' ParamClause ParamClauses
(`=' ConstrExpr | [nl] ConstrBlock)
ConstrExpr ::= SelfInvocation
@@ -838,7 +838,7 @@ primary constructor of the class).
###### Example
Consider the class definition
-```
+```scala
class LinkedList[A]() {
var head = _
var tail = null
@@ -855,7 +855,7 @@ third one constructs a list with a given head and tail.
## Case Classes
-```
+```ebnf
TmplDef ::= `case' `class' ClassDef
```
@@ -875,7 +875,7 @@ parameters $\mathit{tps}$ and value parameters $\mathit{ps}$ implicitly
generates an [extractor object](10-pattern-matching.html#extractor-patterns) which is
defined as follows:
-```
+```scala
object $c$ {
def apply[$\mathit{tps}\,$]($\mathit{ps}_1\,$)$\ldots$($\mathit{ps}_n$): $c$[$\mathit{tps}\,$] = new $c$[$\mathit{Ts}\,$]($\mathit{xs}_1\,$)$\ldots$($\mathit{xs}_n$)
def unapply[$\mathit{tps}\,$]($x$: $c$[$\mathit{tps}\,$]) =
@@ -900,7 +900,7 @@ If the case class definition contains an empty value parameter list, the
`unapply` method returns a `Boolean` instead of an `Option` type and
is defined as follows:
-```
+```scala
def unapply[$\mathit{tps}\,$]($x$: $c$[$\mathit{tps}\,$]) = x ne null
```
@@ -915,7 +915,7 @@ A method named `copy` is implicitly added to every case class unless the
class already has a member (directly defined or inherited) with that name, or the
class has a repeated parameter. The method is defined as follows:
-```
+```scala
def copy[$\mathit{tps}\,$]($\mathit{ps}'_1\,$)$\ldots$($\mathit{ps}'_n$): $c$[$\mathit{tps}\,$] = new $c$[$\mathit{Ts}\,$]($\mathit{xs}_1\,$)$\ldots$($\mathit{xs}_n$)
```
@@ -946,7 +946,7 @@ class different from `AnyRef`. In particular:
###### Example
Here is the definition of abstract syntax for lambda calculus:
-```
+```scala
class Expr
case class Var (x: String) extends Expr
case class Apply (f: Expr, e: Expr) extends Expr
@@ -957,7 +957,7 @@ This defines a class `Expr` with case classes
`Var`, `Apply` and `Lambda`. A call-by-value evaluator
for lambda expressions could then be written as follows.
-```
+```scala
type Env = String => Value
case class Value(e: Expr, env: Env)
@@ -976,7 +976,7 @@ def eval(e: Expr, env: Env): Value = e match {
It is possible to define further case classes that extend type
`Expr` in other parts of the program, for instance
-```
+```scala
case class Number(x: Int) extends Expr
```
@@ -988,7 +988,7 @@ directly extend `Expr` must be in the same source file as
### Traits
-```
+```ebnf
TmplDef ::= `trait' TraitDef
TraitDef ::= id [TypeParamClause] TraitTemplateOpt
TraitTemplateOpt ::= `extends' TraitTemplate | [[`extends'] TemplateBody]
@@ -1010,14 +1010,14 @@ it is not statically known at the time the trait is defined.
If $D$ is not a trait, then its actual supertype is simply its
least proper supertype (which is statically known).
-### Example:
+### Example
The following trait defines the property
of being comparable to objects of some type. It contains an abstract
method `<` and default implementations of the other
comparison operators `<=`, `>`, and
`>=`.
-```
+```scala
trait Comparable[T <: Comparable[T]] { self: T =>
def < (that: T): Boolean
def <=(that: T): Boolean = this < that || this == that
@@ -1035,7 +1035,7 @@ given key. Finally, there is a method `apply` which is like
`get`, except that it returns a given default value if the table
is undefined for the given key. This class is implemented as follows.
-```
+```scala
abstract class Table[A, B](defaultValue: B) {
def get(key: A): Option[B]
def set(key: A, value: B)
@@ -1048,7 +1048,7 @@ abstract class Table[A, B](defaultValue: B) {
Here is a concrete implementation of the `Table` class.
-```
+```scala
class ListTable[A, B](defaultValue: B) extends Table[A, B](defaultValue) {
private var elems: List[(A, B)]
def get(key: A) = elems.find(._1.==(key)).map(._2)
@@ -1059,7 +1059,7 @@ class ListTable[A, B](defaultValue: B) extends Table[A, B](defaultValue) {
Here is a trait that prevents concurrent access to the
`get` and `set` operations of its parent class:
-```
+```scala
trait SynchronizedTable[A, B] extends Table[A, B] {
abstract override def get(key: A): B =
synchronized { super.get(key) }
@@ -1080,7 +1080,7 @@ Finally, the following mixin composition creates a synchronized list
table with strings as keys and integers as values and with a default
value `0`:
-```
+```scala
object MyTable extends ListTable[String, Int](0) with SynchronizedTable
```
@@ -1093,7 +1093,7 @@ in `MyTable`.
## Object Definitions
-```
+```ebnf
ObjectDef ::= id ClassTemplate
```
@@ -1103,7 +1103,7 @@ most general form is
$m$ is the name of the object to be defined, and
$t$ is a [template](#templates) of the form
-```
+```scala
$sc$ with $mt_1$ with $\ldots$ with $mt_n$ { $\mathit{stats}$ }
```
@@ -1118,7 +1118,7 @@ The object definition defines a single object (or: _module_)
conforming to the template $t$. It is roughly equivalent to the
following definition of a lazy value:
-```
+```scala
lazy val $m$ = new $sc$ with $mt_1$ with $\ldots$ with $mt_n$ { this: $m.type$ => $\mathit{stats}$ }
```
@@ -1142,7 +1142,7 @@ Classes in Scala do not have static members; however, an equivalent
effect can be achieved by an accompanying object definition
E.g.
-```
+```scala
abstract class Point {
val x: Double
val y: Double
diff --git a/08-expressions.md b/08-expressions.md
index 1c72e4734e..db1bd182cd 100644
--- a/08-expressions.md
+++ b/08-expressions.md
@@ -6,7 +6,7 @@ chapter: 6
# Expressions
-```
+```ebnf
Expr ::= (Bindings | id | `_') `=>' Expr
| Expr1
Expr1 ::= `if' `(' Expr `)' {nl} Expr [[semi] `else' Expr]
@@ -66,14 +66,14 @@ type $T$ and let $t_1[\mathit{tps}_1] >: L_1 <: U_1 , \ldots , t_n[\mathit{tps}_
all the type variables created by skolemization of some part of $e$ which are free in $T$.
Then the _packed type_ of $e$ is
-```
+```scala
$T$ forSome { type $t_1[\mathit{tps}_1] >: L_1 <: U_1$; $\ldots$; type $t_n[\mathit{tps}_n] >: L_n <: U_n$ }.
```
## Literals
-```
+```ebnf
SimpleExpr ::= Literal
```
@@ -102,7 +102,7 @@ A reference to any other member of the "null" object causes a
## Designators
-```
+```ebnf
SimpleExpr ::= Path
| SimpleExpr `.' id
```
@@ -160,7 +160,7 @@ is thrown.
## This and Super
-```
+```ebnf
SimpleExpr ::= [id `.'] `this'
| [id '.'] `super' [ClassQualifier] `.' id
```
@@ -210,10 +210,10 @@ to the type or method of $x$ in the parent trait of $C$ whose simple
name is $T$. That member must be uniquely defined. If it is a method,
it must be concrete.
-### Example:
+### Example
Consider the following class definitions
-```
+```scala
class Root { def x = "Root" }
class A extends Root { override def x = "A" ; def superA = super.x }
trait B extends Root { override def x = "B" ; def superB = super.x }
@@ -229,7 +229,7 @@ The linearization of class `C` is `{C, B, Root}` and
the linearization of class `D` is `{D, B, A, Root}`.
Then we have:
-```
+```scala
(new A).superA == "Root",
(new C).superB = "Root", (new C).superC = "B",
(new D).superA == "Root", (new D).superB = "A", (new D).superD = "B",
@@ -241,7 +241,7 @@ depending on whether `B` is mixed in with class `Root` or `A`.
## Function Applications
-```
+```ebnf
SimpleExpr ::= SimpleExpr1 ArgumentExprs
ArgumentExprs ::= `(' [Exprs] `)'
| `(' [Exprs `,'] PostfixExpr `:' `_' `*' ')'
@@ -326,20 +326,20 @@ of the caller.
Assume the following function which computes the sum of a
variable number of arguments:
-```
+```scala
def sum(xs: Int*) = (0 /: xs) ((x, y) => x + y)
```
Then
-```
+```scala
sum(1, 2, 3, 4)
sum(List(1, 2, 3, 4): _*)
```
both yield `10` as result. On the other hand,
-```
+```scala
sum(List(1, 2, 3, 4))
```
@@ -369,7 +369,7 @@ If the function $f$
has the form `$p.m$[$\mathit{targs}$]` it is transformed into the
block
-```
+```scala
{ val q = $p$
q.$m$[$\mathit{targs}$]
}
@@ -379,7 +379,7 @@ If the function $f$ is itself an application expression the transformation
is applied recursively on $f$. The result of transforming $f$ is a block of
the form
-```
+```scala
{ val q = $p$
val $x_1$ = expr$_1$
$\ldots$
@@ -404,7 +404,7 @@ that the position of each name matches the position of its corresponding
parameter in the method type `($p_1:T_1 , \ldots , p_n:T_n$)$U$`.
The final result of the transformation is a block of the form
-```
+```scala
{ val q = $p$
val $x_1$ = expr$_1$
$\ldots$
@@ -422,7 +422,7 @@ The final result of the transformation is a block of the form
## Method Values
-```
+```ebnf
SimpleExpr ::= SimpleExpr1 `_'
```
@@ -455,7 +455,7 @@ because otherwise the underscore would be considered part of the name.
## Type Applications
-```
+```ebnf
SimpleExpr ::= SimpleExpr TypeArgs
```
@@ -482,7 +482,7 @@ and the expected result type.
## Tuples
-```
+```ebnf
SimpleExpr ::= `(' [Exprs] `)'
```
@@ -495,7 +495,7 @@ The empty tuple
## Instance Creation Expressions
-```
+```ebnf
SimpleExpr ::= `new' (ClassTemplate | TemplateBody)
```
@@ -510,7 +510,7 @@ $T$. The concrete self type is normally
$T$, except if the expression `new $c$` appears as the
right hand side of a value definition
-```
+```scala
val $x$: $S$ = new $c$
```
@@ -526,7 +526,7 @@ A general instance creation expression is of the form
`new $t$` for some [class template](07-classes-and-objects.html#templates) $t$.
Such an expression is equivalent to the block
-```
+```scala
{ class $a$ extends $t$; new $a$ }
```
@@ -541,19 +541,19 @@ types: If `{$D$}` is a class body, then
###### Example
Consider the following structural instance creation expression:
-```
+```scala
new { def getName() = "aaron" }
```
This is a shorthand for the general instance creation expression
-```
+```scala
new AnyRef{ def getName() = "aaron" }
```
The latter is in turn a shorthand for the block
-```
+```scala
{ class anon\$X extends AnyRef{ def getName() = "aaron" }; new anon\$X }
```
@@ -562,7 +562,7 @@ where `anon\$X` is some freshly created name.
## Blocks
-```
+```ebnf
BlockExpr ::= ‘{’ CaseClauses ‘}’
| ‘{’ Block ‘}’
Block ::= BlockStat {semi BlockStat} [ResultExpr]
@@ -609,14 +609,14 @@ $e$, which defines the result of the block.
###### Example
Assuming a class `Ref[T](x: T)`, the block
-```
+```scala
{ class C extends B {$\ldots$} ; new Ref(new C) }
```
has the type `Ref[_1] forSome { type _1 <: B }`.
The block
-```
+```scala
{ class C extends B {$\ldots$} ; new C }
```
@@ -627,7 +627,7 @@ the existentially quantified type
## Prefix, Infix, and Postfix Operations
-```
+```ebnf
PostfixExpr ::= InfixExpr [id [nl]]
InfixExpr ::= PrefixExpr
| InfixExpr id [nl] InfixExpr
@@ -668,7 +668,7 @@ The _precedence_ of an infix operator is determined by the operator's first
character. Characters are listed below in increasing order of
precedence, with characters on the same line having the same precedence.
-```
+```scala
(all letters)
|
^
@@ -742,7 +742,7 @@ operation `$l$ += $r$`, where $l$, $r$ are expressions.
This operation can be re-interpreted as an operation which corresponds
to the assignment
-```
+```scala
$l$ = $l$ + $r$
```
@@ -762,7 +762,7 @@ The re-interpretation occurs if the following two conditions are fulfilled.
## Typed Expressions
-```
+```ebnf
Expr1 ::= PostfixExpr `:' CompoundType
```
@@ -773,7 +773,7 @@ the expression is the value of $e$ converted to type $T$.
###### Example
Here are examples of well-typed and ill-typed expressions.
-```
+```scala
1: Int // legal, of type Int
1: Long // legal, of type Long
// 1: string // ***** illegal
@@ -782,7 +782,7 @@ Here are examples of well-typed and ill-typed expressions.
## Annotated Expressions
-```
+```ebnf
Expr1 ::= PostfixExpr `:' Annotation {Annotation}
```
@@ -793,7 +793,7 @@ expression $e$.
## Assignments
-```
+```ebnf
Expr1 ::= [SimpleExpr `.'] id `=' Expr
| SimpleExpr1 ArgumentExprs `=' Expr
```
@@ -825,11 +825,11 @@ Here are some assignment expressions and their equivalent expansions.
`x.f(i, j) = e` x.f.update(i, j, e)
-------------------------- ---------------------
-### Example:
+### Example
Here is the usual imperative code for matrix multiplication.
-```
+```scala
def matmul(xss: Array[Array[Double]], yss: Array[Array[Double]]) = {
val zss: Array[Array[Double]] = new Array(xss.length, yss(0).length)
var i = 0
@@ -854,7 +854,7 @@ def matmul(xss: Array[Array[Double]], yss: Array[Array[Double]]) = {
Desugaring the array accesses and assignments yields the following
expanded version:
-```
+```scala
def matmul(xss: Array[Array[Double]], yss: Array[Array[Double]]) = {
val zss: Array[Array[Double]] = new Array(xss.length, yss.apply(0).length)
var i = 0
@@ -879,7 +879,7 @@ def matmul(xss: Array[Array[Double]], yss: Array[Array[Double]]) = {
## Conditional Expressions
-```
+```ebnf
Expr1 ::= `if' `(' Expr `)' {nl} Expr [[semi] `else' Expr]
```
@@ -905,7 +905,7 @@ evaluated as if it was `if ($e_1$) $e_2$ else ()`.
## While Loop Expressions
-```
+```ebnf
Expr1 ::= `while' `(' Expr ')' {nl} Expr
```
@@ -913,7 +913,7 @@ The while loop expression `while ($e_1$) $e_2$` is typed and
evaluated as if it was an application of `whileLoop ($e_1$) ($e_2$)` where
the hypothetical function `whileLoop` is defined as follows.
-```
+```scala
def whileLoop(cond: => Boolean)(body: => Unit): Unit =
if (cond) { body ; whileLoop(cond)(body) } else {}
```
@@ -921,7 +921,7 @@ def whileLoop(cond: => Boolean)(body: => Unit): Unit =
## Do Loop Expressions
-```
+```ebnf
Expr1 ::= `do' Expr [semi] `while' `(' Expr ')'
```
@@ -932,7 +932,7 @@ A semicolon preceding the `while` symbol of a do loop expression is ignored.
## For Comprehensions and For Loops
-```
+```ebnf
Expr1 ::= `for' (`(' Enumerators `)' | `{' Enumerators `}')
{nl} [`yield'] Expr
Enumerators ::= Generator {semi Generator}
@@ -961,7 +961,7 @@ The translation scheme is as follows. In a first step, every
generator `$p$ <- $e$`, where $p$ is not [irrefutable](10-pattern-matching.html#patterns)
for the type of $e$ is replaced by
-```
+```scala
$p$ <- $e$.withFilter { case $p$ => true; case _ => false }
```
@@ -1022,7 +1022,7 @@ comprehensions have been eliminated.
The following code produces all pairs of numbers between $1$ and $n-1$
whose sums are prime.
-```
+```scala
for { i <- 1 until n
j <- 1 until i
if isPrime(i+j)
@@ -1031,7 +1031,7 @@ for { i <- 1 until n
The for comprehension is translated to:
-```
+```scala
(1 until n)
.flatMap {
case i => (1 until i)
@@ -1046,7 +1046,7 @@ For instance, here is a function to compute the transpose of a given matrix:
<!-- see test/files/run/t0421.scala -->
-```
+```scala
def transpose[A](xss: Array[Array[A]]) = {
for (i <- Array.range(0, xss(0).length)) yield
for (xs <- xss) yield xs(i)
@@ -1055,7 +1055,7 @@ def transpose[A](xss: Array[Array[A]]) = {
Here is a function to compute the scalar product of two vectors:
-```
+```scala
def scalprod(xs: Array[Double], ys: Array[Double]) = {
var acc = 0.0
for ((x, y) <- xs zip ys) acc = acc + x * y
@@ -1066,7 +1066,7 @@ def scalprod(xs: Array[Double], ys: Array[Double]) = {
Finally, here is a function to compute the product of two matrices.
Compare with the [imperative version](#example-imperative-matrix-multiplication).
-```
+```scala
def matmul(xss: Array[Array[Double]], yss: Array[Array[Double]]) = {
val ysst = transpose(yss)
for (xs <- xss) yield
@@ -1082,7 +1082,7 @@ The code above makes use of the fact that `map`, `flatMap`,
## Return Expressions
-```
+```ebnf
Expr1 ::= `return' [Expr]
```
@@ -1120,7 +1120,7 @@ and will propagate up the call stack.
## Throw Expressions
-```
+```ebnf
Expr1 ::= `throw' Expr
```
@@ -1138,7 +1138,7 @@ is `scala.Nothing`.
## Try Expressions
-```
+```ebnf
Expr1 ::= `try' `{' Block `}' [`catch' `{' CaseClauses `}']
[`finally' Expr]
```
@@ -1147,7 +1147,7 @@ A try expression is of the form `try { $b$ } catch $h$`
where the handler $h$ is a
[pattern matching anonymous function](#pattern-matching-anonymous-functions)
-```
+```scala
{ case $p_1$ => $b_1$ $\ldots$ case $p_n$ => $b_n$ }
```
@@ -1193,7 +1193,7 @@ for `try { try { $b$ } catch $e_1$ } finally $e_2$`.
## Anonymous Functions
-```
+```ebnf
Expr ::= (Bindings | [`implicit'] id | `_') `=>' Expr
ResultExpr ::= (Bindings | ([`implicit'] id | `_') `:' CompoundType) `=>' Block
Bindings ::= `(' Binding {`,' Binding} `)'
@@ -1221,7 +1221,7 @@ type which does not refer to any of the formal parameters $x_i$.
The anonymous function is evaluated as the instance creation expression
-```
+```scala
new scala.Function$n$[$T_1 , \ldots , T_n$, $T$] {
def apply($x_1$: $T_1 , \ldots , x_n$: $T_n$): $T$ = $e$
}
@@ -1247,7 +1247,7 @@ anonymous functions always have to be given explicitly.
###### Example
Examples of anonymous functions:
-```
+```scala
x => x // The identity function
f => g => x => f(g(x)) // Curried function composition
@@ -1266,7 +1266,7 @@ _ => 5 // The function that ignores its argument
### Placeholder Syntax for Anonymous Functions
-```
+```ebnf
SimpleExpr1 ::= `_'
```
@@ -1323,7 +1323,7 @@ include at least the expressions of the following forms:
## Statements
-```
+```ebnf
BlockStat ::= Import
| {Annotation} [‘implicit’ | ‘lazy’] Def
| {Annotation} {LocalModifier} TmplDef
@@ -1380,7 +1380,7 @@ is applied to pick a unique member.
###### Type Instantiation
An expression $e$ of polymorphic type
-```
+```scala
[$a_1$ >: $L_1$ <: $U_1 , \ldots , a_n$ >: $L_n$ <: $U_n$]$T$
```
@@ -1557,7 +1557,7 @@ alternatives in $\mathscr{B}$.
###### Example
Consider the following definitions:
-```
+```scala
class A extends B {}
def f(x: B, y: B) = $\ldots$
def f(x: A, y: B) = $\ldots$
@@ -1569,7 +1569,7 @@ Then the application `f(b, b)` refers to the first
definition of $f$ whereas the application `f(a, a)`
refers to the second. Assume now we add a third overloaded definition
-```
+```scala
def f(x: B, y: A) = $\ldots$
```
@@ -1670,14 +1670,14 @@ any one of them.
###### Example
Consider the two methods:
-```
+```scala
def cons[A](x: A, xs: List[A]): List[A] = x :: xs
def nil[B]: List[B] = Nil
```
and the definition
-```
+```scala
val xs = cons(1, nil)
```
@@ -1693,7 +1693,7 @@ has type `Int` whereas the second argument `nil` is
itself polymorphic. One tries to type-check `nil` with an
expected type `List[a]`. This leads to the constraint system
-```
+```scala
List[b?] <: List[a]
```
@@ -1702,14 +1702,14 @@ that it is a variable in the constraint system.
Because class `List` is covariant, the optimal
solution of this constraint is
-```
+```scala
b = scala.Nothing
```
In a second step, one solves the following constraint system for
the type parameter `a` of `cons`:
-```
+```scala
Int <: a?
List[scala.Nothing] <: List[a?]
List[a?] <: $\mathit{undefined}$
@@ -1717,7 +1717,7 @@ List[a?] <: $\mathit{undefined}$
The optimal solution of this constraint system is
-```
+```scala
a = Int
```
@@ -1728,7 +1728,7 @@ so `Int` is the type inferred for `a`.
Consider now the definition
-```
+```scala
val ys = cons("abc", xs)
```
@@ -1746,7 +1746,7 @@ the second strategy is tried; `xs` is now typed with expected type
In a second step, one solves the following constraint system for
the type parameter `a` of `cons`:
-```
+```scala
String <: a?
List[Int] <: List[a?]
List[a?] <: $\mathit{undefined}$
@@ -1754,7 +1754,7 @@ List[a?] <: $\mathit{undefined}$
The optimal solution of this constraint system is
-```
+```scala
a = scala.Any
```
@@ -1774,7 +1774,7 @@ corresponding fresh name $x_i$. Second, one creates a fresh name $y_i$
for every argument type $T_i$ of the method ($i = 1 , \ldots ,
n$). The result of eta-conversion is then:
-```
+```scala
{ val $x_1$ = $e_1$;
$\ldots$
val $x_m$ = $e_m$;
@@ -1787,7 +1787,7 @@ n$). The result of eta-conversion is then:
The standard Scala library defines a trait `scala.Dynamic` which defines a member
\@invokeDynamic@ as follows:
-```
+```scala
package scala
trait Dynamic {
def applyDynamic (name: String, args: Any*): Any
@@ -1798,14 +1798,14 @@ trait Dynamic {
Assume a selection of the form $e.x$ where the type of $e$ conforms to `scala.Dynamic`.
Further assuming the selection is not followed by any function arguments, such an expression can be rewitten under the conditions given [here](#implicit-conversions) to:
-```
+```scala
$e$.applyDynamic("$x$")
```
If the selection is followed by some arguments, e.g. $e.x(\mathit{args})$, then that expression
is rewritten to
-```
+```scala
$e$.applyDynamic("$x$", $\mathit{args}$)
```
diff --git a/09-implicit-parameters-and-views.md b/09-implicit-parameters-and-views.md
index 8cd54897c9..3e821ec9fa 100644
--- a/09-implicit-parameters-and-views.md
+++ b/09-implicit-parameters-and-views.md
@@ -8,7 +8,7 @@ chapter: 7
## The Implicit Modifier
-```
+```ebnf
LocalModifier ::= ‘implicit’
ParamClauses ::= {ParamClause} [nl] ‘(’ ‘implicit’ Params ‘)’
```
@@ -19,12 +19,12 @@ and can be used as implicit conversions called [views](#views).
The `implicit` modifier is illegal for all
type members, as well as for [top-level objects](11-top-level-definitions.html#packagings).
-### Example:
+### Example
The following code defines an abstract class of monoids and
two concrete implementations, `StringMonoid` and
`IntMonoid`. The two implementations are marked implicit.
-```
+```scala
abstract class Monoid[A] extends SemiGroup[A] {
def unit: A
def add(x: A, y: A): A
@@ -101,7 +101,7 @@ Assuming the classes from the [`Monoid` example](#example-monoid), here is a
method which computes the sum of a list of elements using the
monoid's `add` and `unit` operations.
-```
+```scala
def sum[A](xs: List[A])(implicit m: Monoid[A]): A =
if (xs.isEmpty) m.unit
else m.add(xs.head, sum(xs.tail))
@@ -126,7 +126,7 @@ is the following method from module `scala.List`, which injects
lists into the `scala.Ordered` class, provided the element
type of the list is also convertible to this type.
-```
+```scala
implicit def list2ordered[A](x: List[A])
(implicit elem2ordered: A => Ordered[A]): Ordered[List[A]] =
...
@@ -134,14 +134,14 @@ implicit def list2ordered[A](x: List[A])
Assume in addition a method
-```
+```scala
implicit def int2ordered(x: Int): Ordered[Int]
```
that injects integers into the `Ordered` class. We can now
define a `sort` method over ordered lists:
-```
+```scala
def sort[A](xs: List[A])(implicit a2ordered: A => Ordered[A]) = ...
```
@@ -149,13 +149,13 @@ We can apply `sort` to a list of lists of integers
`yss: List[List[Int]]`
as follows:
-```
+```scala
sort(yss)
```
The call above will be completed by passing two nested implicit arguments:
-```
+```scala
sort(yss)(xs: List[Int] => list2ordered[Int](xs)(int2ordered)) .
```
@@ -164,7 +164,7 @@ raises the possibility of an infinite recursion. For instance, one
might try to define the following method, which injects _every_ type into the
`Ordered` class:
-```
+```scala
implicit def magic[A](x: A)(implicit a2ordered: A => Ordered[A]): Ordered[A] =
a2ordered(x)
```
@@ -174,7 +174,7 @@ Now, if one tried to apply
another injection into the `Ordered` class, one would obtain an infinite
expansion:
-```
+```scala
sort(arg)(x => magic(x)(x => magic(x)(x => ... )))
```
@@ -218,7 +218,7 @@ When typing `sort(xs)` for some list `xs` of type `List[List[List[Int]]]`,
the sequence of types for
which implicit arguments are searched is
-```
+```scala
List[List[Int]] => Ordered[List[List[Int]]],
List[Int] => Ordered[List[Int]]
Int => Ordered[Int]
@@ -233,14 +233,14 @@ Hence, the code typechecks.
Let `ys` be a list of some type which cannot be converted
to `Ordered`. For instance:
-```
+```scala
val ys = List(new IllegalArgumentException, new ClassCastException, new Error)
```
Assume that the definition of `magic` above is in scope. Then the sequence
of types for which implicit arguments are searched is
-```
+```scala
Throwable => Ordered[Throwable],
Throwable => Ordered[Throwable],
...
@@ -290,10 +290,10 @@ As for implicit parameters, overloading resolution is applied
if there are several possible candidates (of either the call-by-value
or the call-by-name category).
-### Example:
+### Example
Class `scala.Ordered[A]` contains a method
-```
+```scala
def <= [B >: A](that: B)(implicit b2ordered: B => Ordered[B]): Boolean .
```
@@ -302,13 +302,13 @@ and assume that the `list2ordered` and `int2ordered`
methods defined [here](#implicit-parameters) are in scope.
Then the operation
-```
+```scala
xs <= ys
```
is legal, and is expanded to:
-```
+```scala
list2ordered(xs)(int2ordered).<=
(ys)
(xs => list2ordered(xs)(int2ordered))
@@ -322,7 +322,7 @@ method.
## Context Bounds and View Bounds
-```
+```ebnf
TypeParam ::= (id | ‘_’) [TypeParamClause] [‘>:’ Type] [‘<:’ Type]
{‘<%’ Type} {‘:’ Type}
```
@@ -342,13 +342,13 @@ A method or class containing type parameters with view or context bounds is trea
equivalent to a method with implicit parameters. Consider first the case of a
single parameter with view and/or context bounds such as:
-```
+```scala
def $f$[$A$ <% $T_1$ ... <% $T_m$ : $U_1$ : $U_n$]($\mathit{ps}$): $R$ = ...
```
Then the method definition above is expanded to
-```
+```scala
def $f$[$A$]($\mathit{ps}$)(implicit $v_1$: $A$ => $T_1$, ..., $v_m$: $A$ => $T_m$,
$w_1$: $U_1$[$A$], ..., $w_n$: $U_n$[$A$]): $R$ = ...
```
@@ -369,7 +369,7 @@ additional implicit parameters.
The `<=` method from the [`Ordered` example](#example-ordered) can be declared
more concisely as follows:
-```
+```scala
def <= [B >: A <% Ordered[B]](that: B): Boolean
```
@@ -382,7 +382,7 @@ standard library contains a hierarchy of four manifest classes,
with `OptManifest`
at the top. Their signatures follow the outline below.
-```
+```scala
trait OptManifest[+T]
object NoManifest extends OptManifest[Nothing]
trait ClassManifest[T] extends OptManifest[T]
diff --git a/10-pattern-matching.md b/10-pattern-matching.md
index cb20a81823..19182c757b 100644
--- a/10-pattern-matching.md
+++ b/10-pattern-matching.md
@@ -8,7 +8,7 @@ chapter: 8
## Patterns
-```
+```ebnf
Pattern ::= Pattern1 { ‘|’ Pattern1 }
Pattern1 ::= varid ‘:’ TypePat
| ‘_’ ‘:’ TypePat
@@ -55,7 +55,7 @@ patterns.
### Variable Patterns
-```
+```ebnf
SimplePattern ::= `_'
| varid
```
@@ -69,7 +69,7 @@ which is treated as if it was a fresh variable on each occurrence.
### Typed Patterns
-```
+```ebnf
Pattern1 ::= varid `:' TypePat
| `_' `:' TypePat
```
@@ -83,7 +83,7 @@ that value.
### Pattern Binders
-```
+```ebnf
Pattern2 ::= varid `@' Pattern3
```
@@ -95,7 +95,7 @@ and it binds the variable name to that value.
### Literal Patterns
-```
+```ebnf
SimplePattern ::= Literal
```
@@ -105,7 +105,7 @@ expected type of the pattern.
### Stable Identifier Patterns
-```
+```ebnf
SimplePattern ::= StableId
```
@@ -122,7 +122,7 @@ backquotes; then it is treated as a stable identifier pattern.
###### Example
Consider the following function definition:
-```
+```scala
def f(x: Int, y: Int) = x match {
case y => ...
}
@@ -132,7 +132,7 @@ Here, `y` is a variable pattern, which matches any value.
If we wanted to turn the pattern into a stable identifier pattern, this
can be achieved as follows:
-```
+```scala
def f(x: Int, y: Int) = x match {
case `y` => ...
}
@@ -144,7 +144,7 @@ argument of `f` are equal.
### Constructor Patterns
-```
+```ebnf
SimplePattern ::= StableId `(' [Patterns] `)
```
@@ -170,7 +170,7 @@ repeated parameter. This is further discussed [here](#pattern-sequences).
### Tuple Patterns
-```
+```ebnf
SimplePattern ::= `(' [Patterns] `)'
```
@@ -181,7 +181,7 @@ where $n \geq 2$. The empty tuple
### Extractor Patterns
-```
+```ebnf
SimplePattern ::= StableId `(' [Patterns] `)'
```
@@ -221,7 +221,7 @@ This case is further discussed [below](#pattern-sequences).
The `Predef` object contains a definition of an
extractor object `Pair`:
-```
+```scala
object Pair {
def apply[A, B](x: A, y: B) = Tuple2(x, y)
def unapply[A, B](x: Tuple2[A, B]): Option[Tuple2[A, B]] = Some(x)
@@ -232,7 +232,7 @@ This means that the name `Pair` can be used in place of `Tuple2` for tuple
formation as well as for deconstruction of tuples in patterns.
Hence, the following is possible:
-```
+```scala
val x = (1, 2)
val y = x match {
case Pair(i, s) => Pair(s + i, i * i)
@@ -241,7 +241,7 @@ val y = x match {
### Pattern Sequences
-```
+```ebnf
SimplePattern ::= StableId `(' [Patterns `,'] [varid `@'] `_' `*' `)'
```
@@ -262,7 +262,7 @@ p_n$.
### Infix Operation Patterns
-```
+```ebnf
Pattern3 ::= SimplePattern {id [nl] SimplePattern}
```
@@ -277,7 +277,7 @@ shorthand for the constructor or extractor pattern $\mathit{op}(p, q_1
### Pattern Alternatives
-```
+```ebnf
Pattern ::= Pattern1 { `|' Pattern1 }
```
@@ -320,7 +320,7 @@ A pattern $p$ is _irrefutable_ for a type $T$, if one of the following applies:
## Type Patterns
-```
+```ebnf
TypePat ::= Type
```
@@ -448,7 +448,7 @@ are inferred in the same way as for the typed pattern
###### Example
Consider the program fragment:
-```
+```scala
val x: Any
x match {
case y: List[a] => ...
@@ -464,7 +464,7 @@ bounds. The scope of `a` is right-hand side of its case clause.
On the other hand, if `x` is declared as
-```
+```scala
val x: List[List[String]],
```
@@ -477,7 +477,7 @@ this generates the constraint
###### Example
Consider the program fragment:
-```
+```scala
val x: Any
x match {
case y: List[String] => ...
@@ -499,7 +499,7 @@ compiler will flag this potential loss of type-safety with an
###### Example
Consider the program fragment
-```
+```scala
class Term[A]
class Number(val n: Int) extends Term[Int]
def f[B](t: Term[B]): B = t match {
@@ -522,7 +522,7 @@ function's declared result type, `Number`.
## Pattern Matching Expressions
-```
+```ebnf
Expr ::= PostfixExpr `match' `{' CaseClauses `}'
CaseClauses ::= CaseClause {CaseClause}
CaseClause ::= `case' Pattern [Guard] `=>' Block
@@ -530,7 +530,7 @@ function's declared result type, `Number`.
A pattern matching expression
-```
+```scala
e match { case $p_1$ => $b_1$ $\ldots$ case $p_n$ => $b_n$ }
```
@@ -597,11 +597,11 @@ the compilation of pattern matching can emit warnings which diagnose
that a given set of patterns is not exhaustive, i.e. that there is a
possibility of a `MatchError` being raised at run-time.
-### Example:
+### Example
Consider the following definitions of arithmetic terms:
-```
+```scala
abstract class Term[T]
case class Lit(x: Int) extends Term[Int]
case class Succ(t: Term[Int]) extends Term[Int]
@@ -617,7 +617,7 @@ type of the expression it representes (either `Int` or `Boolean`).
A type-safe evaluator for such terms can be written as follows.
-```
+```scala
def eval[T](t: Term[T]): T = t match {
case Lit(n) => n
case Succ(u) => eval(u) + 1
@@ -640,13 +640,13 @@ conforms to its expected type, `T`.
## Pattern Matching Anonymous Functions
-```
+```ebnf
BlockExpr ::= `{' CaseClauses `}'
```
An anonymous function can be defined by a sequence of cases
-```
+```scala
{ case $p_1$ => $b_1$ $\ldots$ case $p_n$ => $b_n$ }
```
@@ -660,7 +660,7 @@ $R$ may be undetermined.
If the expected type is `scala.Function$k$[$S_1 , \ldots , S_k$, $R$]`,
the expression is taken to be equivalent to the anonymous function:
-```
+```scala
($x_1: S_1 , \ldots , x_k: S_k$) => ($x_1 , \ldots , x_k$) match {
case $p_1$ => $b_1$ $\ldots$ case $p_n$ => $b_n$
}
@@ -671,7 +671,7 @@ As was shown [here](08-expressions.html#anonymous-functions), this anonymous fun
equivalent to the following instance creation expression, where
$T$ is the weak least upper bound of the types of all $b_i$.
-```
+```scala
new scala.Function$k$[$S_1 , \ldots , S_k$, $T$] {
def apply($x_1: S_1 , \ldots , x_k: S_k$): $T$ = ($x_1 , \ldots , x_k$) match {
case $p_1$ => $b_1$ $\ldots$ case $p_n$ => $b_n$
@@ -682,7 +682,7 @@ new scala.Function$k$[$S_1 , \ldots , S_k$, $T$] {
If the expected type is `scala.PartialFunction[$S$, $R$]`,
the expression is taken to be equivalent to the following instance creation expression:
-```
+```scala
new scala.PartialFunction[$S$, $T$] {
def apply($x$: $S$): $T$ = x match {
case $p_1$ => $b_1$ $\ldots$ case $p_n$ => $b_n$
@@ -704,7 +704,7 @@ Here is a method which uses a fold-left operation
`/:` to compute the scalar product of
two vectors:
-```
+```scala
def scalarProduct(xs: Array[Double], ys: Array[Double]) =
(0.0 /: (xs zip ys)) {
case (a, (b, c)) => a + b * c
@@ -714,7 +714,7 @@ def scalarProduct(xs: Array[Double], ys: Array[Double]) =
The case clauses in this code are equivalent to the following
anonymous function:
-```
+```scala
(x, y) => (x, y) match {
case (a, (b, c)) => a + b * c
}
diff --git a/11-top-level-definitions.md b/11-top-level-definitions.md
index 2c65e35898..cfb2c98adb 100644
--- a/11-top-level-definitions.md
+++ b/11-top-level-definitions.md
@@ -8,7 +8,7 @@ chapter: 9
## Compilation Units
-```
+```ebnf
CompilationUnit ::= {‘package’ QualId semi} TopStatSeq
TopStatSeq ::= TopStat {semi TopStat}
TopStat ::= {Annotation} {Modifier} TmplDef
@@ -25,7 +25,7 @@ package clause.
A compilation unit
-```
+```scala
package $p_1$;
$\ldots$
package $p_n$;
@@ -36,7 +36,7 @@ starting with one or more package
clauses is equivalent to a compilation unit consisting of the
packaging
-```
+```scala
package $p_1$ { $\ldots$
package $p_n$ {
$\mathit{stats}$
@@ -55,7 +55,7 @@ The exception to the implicit import of `scala.Predef` can be useful to hide, e.
## Packagings
-```
+```ebnf
Packaging ::= ‘package’ QualId [nl] ‘{’ TopStatSeq ‘}’
```
@@ -74,7 +74,7 @@ Inside the packaging, all members of package $p$ are visible under their
simple names. However this rule does not extend to members of enclosing
packages of $p$ that are designated by a prefix of the path $p$.
-```
+```scala
package org.net.prj {
...
}
@@ -97,7 +97,7 @@ are visible to each other without qualification.
## Package Objects
-```
+```ebnf
PackageObject ::= ‘package’ ‘object’ ObjectDef
```
@@ -116,7 +116,7 @@ future version of Scala.
## Package References
-```
+```ebnf
QualId ::= id {‘.’ id}
```
@@ -131,7 +131,7 @@ outermost root package which contains all top-level packages.
###### Example
Consider the following program:
-```
+```scala
package b {
class B
}
@@ -168,7 +168,7 @@ which executes the initializaton code of the object $m$.
The following example will create a hello world program by defining
a method `main` in module `test.HelloWorld`.
-```
+```scala
package test
object HelloWorld {
def main(args: Array[String]) { println("Hello World") }
@@ -177,13 +177,13 @@ object HelloWorld {
This program can be started by the command
-```
+```scala
scala test.HelloWorld
```
In a Java environment, the command
-```
+```scala
java test.HelloWorld
```
@@ -192,7 +192,7 @@ would work as well.
`HelloWorld` can also be defined without a `main` method
by inheriting from `App` instead:
-```
+```scala
package test
object HelloWorld extends App {
println("Hello World")
diff --git a/12-xml-expressions-and-patterns.md b/12-xml-expressions-and-patterns.md
index 735349cb90..7aab3380d4 100644
--- a/12-xml-expressions-and-patterns.md
+++ b/12-xml-expressions-and-patterns.md
@@ -18,7 +18,7 @@ XML expressions are expressions generated by the following production, where the
opening bracket `<` of the first element must be in a position to start the lexical
[XML mode](03-lexical-syntax.html#xml-mode).
-```
+```ebnf
XmlExpr ::= XmlContent {Element}
```
@@ -33,7 +33,7 @@ standard. Only the productions for attribute values and character data are chang
Scala does not support declarations, CDATA sections or processing instructions.
Entity references are not resolved at runtime.
-```
+```ebnf
Element ::= EmptyElemTag
| STag Content ETag
@@ -67,7 +67,7 @@ and consecutive occurrences of whitespace are replaced by a single space
character `\u0020`. This behavior can be changed to preserve all whitespace
with a compiler option.
-```
+```ebnf
Attribute ::= Name Eq AttValue
AttValue ::= ‘"’ {CharQ | CharRef} ‘"’
@@ -88,7 +88,7 @@ within XML text as generated by CharData, it must be doubled.
Thus, `{{` represents the XML text `{` and does not introduce an embedded Scala expression.
<!-- {% endraw %} -->
-```
+```ebnf
BaseChar, Char, Comment, CombiningChar, Ideographic, NameChar, S, Reference
::= $\mbox{\rm\em “as in W3C XML”}$
@@ -109,7 +109,7 @@ XML patterns are patterns generated by the following production, where
the opening bracket `<` of the element patterns must be in a position
to start the lexical [XML mode](03-lexical-syntax.html#xml-mode).
-```
+```ebnf
XmlPattern ::= ElementPattern
```
@@ -128,7 +128,7 @@ and consecutive occurrences of whitespace are replaced by a single space
character `\u0020`. This behavior can be changed to preserve all whitespace
with a compiler option.
-```
+```ebnf
ElemPattern ::= EmptyElemTagP
| STagP ContentP ETagP
diff --git a/13-user-defined-annotations.md b/13-user-defined-annotations.md
index 621b55928d..a9f3e0f1de 100644
--- a/13-user-defined-annotations.md
+++ b/13-user-defined-annotations.md
@@ -6,7 +6,7 @@ chapter: 11
# User-Defined Annotations
-```
+```ebnf
Annotation ::= ‘@’ SimpleType {ArgumentExprs}
ConstrAnnotation ::= ‘@’ SimpleType ArgumentExprs
```
@@ -26,7 +26,7 @@ does not matter.
Examples:
-```
+```scala
@deprecated("Use D", "1.0") class C { ... } // Class annotation
@transient @volatile var m: Int // Variable annotation
String @local // Type annotation
diff --git a/14-the-scala-standard-library.md b/14-the-scala-standard-library.md
index db68edd32f..d0d06c25b2 100644
--- a/14-the-scala-standard-library.md
+++ b/14-the-scala-standard-library.md
@@ -40,7 +40,7 @@ class for objects).
The signatures of these root classes are described by the following
definitions.
-```
+```scala
package scala
/** The universal root class */
abstract class Any {
@@ -87,12 +87,11 @@ class AnyRef extends Any {
def synchronized[T](body: => T): T // execute `body` in while locking `this`.
}
-```
-
+```scala
The type test `$x$.isInstanceOf[$T$]` is equivalent to a typed
pattern match
-```
+```scala
$x$ match {
case _: $T'$ => true
case _ => false
@@ -131,7 +130,7 @@ Subrange types, as well as `Int` and `Long` are called _integer types_, whereas
Numeric value types are ranked in the following partial order:
-```
+```scala
Byte - Short
\
Int - Long - Float - Double
@@ -215,7 +214,7 @@ type. If this is true, it will perform the `==` operation which
is appropriate for that type. That is, the `equals` method of a
numeric value type can be thought of being defined as follows:
-```
+```scala
def equals(other: Any): Boolean = other match {
case that: Byte => this == that
case that: Short => this == that
@@ -235,11 +234,11 @@ for type `Int` and for all subrange types.
The `toString` method displays its receiver as an integer or
floating point number.
-### Example:
+### Example
This is the signature of the numeric value type `Int`:
-```
+```scala
package scala
abstract sealed class Int extends AnyVal {
def == (that: Double): Boolean // double equality
@@ -292,7 +291,7 @@ Class `Boolean` has only two values: `true` and
`false`. It implements operations as given in the following
class definition.
-```
+```scala
package scala
abstract sealed class Boolean extends AnyVal {
def && (p: => Boolean): Boolean = // boolean and
@@ -347,7 +346,7 @@ class of the underlying host system (and may be identified with
it). For Scala clients the class is taken to support in each case a
method
-```
+```scala
def + (that: Any): String
```
@@ -359,7 +358,7 @@ right operand.
Scala defines tuple classes `Tuple$n$` for $n = 2 , \ldots , 22$.
These are defined as follows.
-```
+```scala
package scala
case class Tuple$n$[+T_1, ..., +T_n](_1: T_1, ..., _$n$: T_$n$) {
def toString = "(" ++ _1 ++ "," ++ $\ldots$ ++ "," ++ _$n$ ++ ")"
@@ -375,7 +374,7 @@ as an alias for `Tuple3`.
Scala defines function classes `Function$n$` for $n = 1 , \ldots , 22$.
These are defined as follows.
-```
+```scala
package scala
trait Function$n$[-T_1, ..., -T_$n$, +R] {
def apply(x_1: T_1, ..., x_$n$: T_$n$): R
@@ -386,7 +385,7 @@ trait Function$n$[-T_1, ..., -T_$n$, +R] {
The `PartialFunction` subclass of `Function1` represents functions that (indirectly) specify their domain.
Use the `isDefined` method to query whether the partial function is defined for a given input (i.e., whether the input is part of the function's domain).
-```
+```scala
class PartialFunction[-A, +B] extends Function1[A, B] {
def isDefinedAt(x: A): Boolean
}
@@ -401,7 +400,7 @@ All operations on arrays desugar to the corresponding operations of the
underlying platform. Therefore, the following class definition is given for
informational purposes only:
-```
+```scala
final class Array[T](_length: Int)
extends java.io.Serializable with java.lang.Cloneable {
def length: Int = $\ldots$
@@ -463,7 +462,7 @@ However, it is possible to cast an expression of type
`Array[String]` to `Array[Object]`, and this
cast will succeed without raising a `ClassCastException`. Example:
-```
+```scala
val xs = new Array[String](2)
// val ys: Array[Object] = xs // **** error: incompatible types
val ys: Array[Object] = xs.asInstanceOf[Array[Object]] // OK
@@ -478,7 +477,7 @@ following implementation of method `mkArray`, which creates
an array of an arbitrary type $T$, given a sequence of $T$`s which
defines its elements:
-```
+```scala
import reflect.ClassTag
def mkArray[T : ClassTag](elems: Seq[T]): Array[T] = {
val result = new Array[T](elems.length)
@@ -505,7 +504,7 @@ instantiation of single- and multi-dimensional arrays, an extractor method
[`unapplySeq`](10-pattern-matching.html#extractor-patterns) which enables pattern matching
over arrays and additional utility methods:
-```
+```scala
package scala
object Array {
/** copies array elements from `src` to `dest`. */
@@ -558,7 +557,7 @@ object Array {
## Class Node
-```
+```scala
package scala.xml
trait Node {
@@ -637,7 +636,7 @@ for Scala programs. It is always implicitly imported, so that all its
defined members are available without qualification. Its definition
for the JVM environment conforms to the following signature:
-```
+```scala
package scala
object Predef {
@@ -714,8 +713,7 @@ object Predef {
```
-```
-
+```scala
// tupling ---------------------------------------------------------
type Pair[+A, +B] = Tuple2[A, B]
diff --git a/15-syntax-summary.md b/15-syntax-summary.md
index ac24e1e14a..3eecc26eb4 100644
--- a/15-syntax-summary.md
+++ b/15-syntax-summary.md
@@ -10,14 +10,14 @@ The following descriptions of Scala tokens uses literal characters `‘c’` whe
_Unicode escapes_ are used to represent the Unicode character with the given hexadecimal code:
-```
+```ebnf
UnicodeEscape ::= ‘\‘ ‘u‘ {‘u‘} hexDigit hexDigit hexDigit hexDigit
hexDigit ::= ‘0’ | … | ‘9’ | ‘A’ | … | ‘F’ | ‘a’ | … | ‘f’
```
The lexical syntax of Scala is given by the following grammar in EBNF form:
-```
+```ebnf
whiteSpace ::= ‘\u0020’ | ‘\u0009’ | ‘\u000D’ | ‘\u000A’
upper ::= ‘A’ | … | ‘Z’ | ‘\$’ | ‘_’ // and Unicode category Lu
lower ::= ‘a’ | … | ‘z’ // and Unicode category Ll
@@ -75,7 +75,7 @@ semi ::= ‘;’ | nl {nl}
The context-free syntax of Scala is given by the following EBNF
grammar.
-```
+```ebnf
Literal ::= [‘-’] integerLiteral
| [‘-’] floatingPointLiteral
| booleanLiteral
diff --git a/_includes/numbering.css b/_includes/numbering.css
index e8404652dc..86b946354d 100644
--- a/_includes/numbering.css
+++ b/_includes/numbering.css
@@ -41,12 +41,12 @@ h3:before {
margin-right: 1em;
}
-h3[id*='example:'] {
+h3[id*='example'] {
/* must increment here */
counter-increment: example;
display: inline;
}
-h3[id*='example:']:before {
+h3[id*='example']:before {
/* and must reset again here */
counter-reset: chapter {{ page.chapter }};
diff --git a/_layouts/default.yml b/_layouts/default.yml
index cb9f8623be..814bc511a9 100644
--- a/_layouts/default.yml
+++ b/_layouts/default.yml
@@ -21,7 +21,7 @@
<script type="text/javascript">
// clear content of H3 nodes that start with "Example:"
// the content is only there to determine ID of the H3 element (redcarpet doesn't let us set css id)
- $( document ).ready(function(){ $("h3[id*='example:']").text("") })
+ $( document ).ready(function(){ $("h3[id*='example']").text("") })
</script>
<link rel="stylesheet" type="text/css" href="resources/style.css">