From 57c9f704170cd4d3adf49623c9f1b7a7a9670925 Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Mon, 10 Nov 2014 19:24:00 -0700 Subject: A huge re-organization of the Scala file --- scala.html.markdown | 358 ++++++++++++++++++++++++++++------------------------ 1 file changed, 193 insertions(+), 165 deletions(-) diff --git a/scala.html.markdown b/scala.html.markdown index 5a0cc0ff..a55e1f0e 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -4,6 +4,7 @@ filename: learnscala.scala contributors: - ["George Petrov", "http://github.com/petrovg"] - ["Dominic Bou-Samra", "http://dbousamra.github.com"] + - ["Geoff Liu", "http://geoffliu.me"] filename: learn.scala --- @@ -20,16 +21,16 @@ Scala - the scalable language scala> - This is the so called REPL. You can run commands in the REPL. Let's do just - that: + This is the so called REPL (Read-Eval-Print Loop). You may type any valid + Scala expression into it, and the result will be printed. We will explain what + Scala files look like further into this tutorial, but for now, let's start + with some basics. */ -println(10) // prints the integer 10 -println("Boo!") // printlns the string Boo! - - -// Some basics +################################################# +## 1. Basics +################################################# // Printing, and forcing a new line on the next print println("Hello world!") @@ -37,15 +38,15 @@ println("Hello world!") print("Hello world") // Declaring values is done using either var or val -// val declarations are immutable, whereas var's are mutable. Immutability is +// val declarations are immutable, whereas var's are mutable. Immutability is // a good thing. val x = 10 // x is now 10 x = 20 // error: reassignment to val -var x = 10 +var x = 10 x = 20 // x is now 20 // Single line comments start with two forward slashes -/* +/* Multi line comments look like this. */ @@ -82,149 +83,83 @@ true == false // false */ -// Everything is an object, including a function. Type these in the REPL: - -7 // results in res30: Int = 7 (res30 is just a generated var name for the result) - -// The next line gives you a function that takes an Int and returns it squared -(x:Int) => x * x - -// You can assign this function to an identifier, like this: -val sq = (x:Int) => x * x - -/* The above says this - - sq: Int => Int = - - Which means that this time we gave an explicit name to the value - sq is a - function that take an Int and returns Int. - - sq can be executed as follows: -*/ - -sq(10) // Gives you this: res33: Int = 100. - -// The colon explicitly defines the type of a value, in this case a function -// taking an Int and returning an Int. -val add10: Int => Int = _ + 10 - -// Scala allows methods and functions to return, or take as parameters, other -// functions or methods. - -List(1, 2, 3) map add10 // List(11, 12, 13) - add10 is applied to each element - -// Anonymous functions can be used instead of named functions: -List(1, 2, 3) map (x => x + 10) - -// And the underscore symbol, can be used if there is just one argument to the -// anonymous function. It gets bound as the variable -List(1, 2, 3) map (_ + 10) - -// If the anonymous block AND the function you are applying both take one -// argument, you can even omit the underscore -List("Dom", "Bob", "Natalia") foreach println - - - -// Data structures - -val a = Array(1, 2, 3, 5, 8, 13) -a(0) -a(3) -a(21) // Throws an exception - -val m = Map("fork" -> "tenedor", "spoon" -> "cuchara", "knife" -> "cuchillo") -m("fork") -m("spoon") -m("bottle") // Throws an exception - -val safeM = m.withDefaultValue("no lo se") -safeM("bottle") - -val s = Set(1, 3, 7) -s(0) -s(1) - -/* Look up the documentation of map here - - * http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Map - * and make sure you can read it - */ - - -// Tuples - -(1, 2) - -(4, 3, 2) - -(1, 2, "three") - -(a, 2, "three") - -// Why have this? -val divideInts = (x:Int, y:Int) => (x / y, x % y) - -divideInts(10,3) // The function divideInts gives you the result and the remainder - -// To access the elements of a tuple, use _._n where n is the 1-based index of -// the element -val d = divideInts(10,3) - -d._1 - -d._2 - +// Strings +"Scala strings are surrounded by double quotes" // +'a' // A Scala Char +'Single quote strings don't exist' // Error +"Strings have the usual Java methods defined on them".length +"They also have some extra Scala methods.".reverse -// Combinators +// Seealso: scala.collection.immutable.StringOps -s.map(sq) +println("ABCDEF".length) +println("ABCDEF".substring(2, 6)) +println("ABCDEF".replace("C", "3")) -val sSquared = s. map(sq) +// String interpolation +val n = 45 +println(s"We have $n apples") // => "We have 45 apples" -sSquared.filter(_ < 10) +// Expressions inside interpolated strings are also possible +val a = Array(11, 9, 6) +println(s"My second daughter is ${a(0) - a(2)} years old.") // => "My second daughter is 5 years old." +println(s"We have double the amount of ${n / 2.0} in apples.") // => "We have double the amount of 22.5 in apples." +println(s"Power of 2: ${math.pow(2, 2)}") // => "Power of 2: 4" -sSquared.reduce (_+_) +// Formatting with interpolated strings (note the prefixed f) +println(f"Power of 5: ${math.pow(5, 2)}%1.0f") // "Power of 5: 25" +println(f"Square root of 122: ${math.sqrt(122)}%1.4f") // "Square root of 122" -// The filter function takes a predicate (a function from A -> Boolean) and -// selects all elements which satisfy the predicate -List(1, 2, 3) filter (_ > 2) // List(3) -List( - Person(name = "Dom", age = 23), - Person(name = "Bob", age = 30) -).filter(_.age > 25) // List(Person("Bob", 30)) +// Ignoring special characters. +println(raw"New line feed: \n. Carriage return: \r.") // => "New line feed: \n. Carriage return: \r." +// Some characters need to be 'escaped', e.g. a double quote inside a string: +val a = "They stood outside the \"Rose and Crown\"" // => "They stood outside the "Rose and Crown"" -// Scala a foreach method defined on certain collections that takes a type -// returning Unit (a void method) -aListOfNumbers foreach (x => println(x)) -aListOfNumbers foreach println +// Triple double-quotes let strings span multiple rows and contain quotes +val html = """
+

Press belo', Joe

+ | +
""" +################################################# +## 2. Functions +################################################# +// The next line gives you a function that takes an Int and returns it squared +(x:Int) => x * x -// For comprehensions +// You can assign this function to an identifier, like this: +val sq = (x:Int) => x * x -for { n <- s } yield sq(n) +/* The above says this -val nSquared2 = for { n <- s } yield sq(n) + sq: Int => Int = -for { n <- nSquared2 if n < 10 } yield n + Which means that this time we gave an explicit name to the value - sq is a + function that take an Int and returns Int. -for { n <- s; nSquared = n * n if nSquared < 10} yield nSquared + sq can be executed as follows: +*/ -/* NB Those were not for loops. The semantics of a for loop is 'repeat', whereas - a for-comprehension defines a relationship between two sets of data. */ +sq(10) // Gives you this: res33: Int = 100. +// The colon explicitly defines the type of a value, in this case a function +// taking an Int and returning an Int. +val add10: Int => Int = _ + 10 -// Loops and iteration +################################################# +## 3. Flow Control +################################################# 1 to 5 val r = 1 to 5 r.foreach( println ) -r foreach println +r foreach println // NB: Scala is quite lenient when it comes to dots and brackets - study the // rules separately. This helps write DSLs and APIs that read like English @@ -243,7 +178,7 @@ i // Show the value of i. Note that while is a loop in the classical sense - // A do while loop do { - println("x is still less than 10"); + println("x is still less than 10"); x += 1 } while (x < 10) @@ -257,7 +192,6 @@ def showNumbersInRange(a:Int, b:Int):Unit = { } - // Conditionals val x = 10 @@ -274,10 +208,76 @@ var i = 0 while (i < 10) { println("i " + i); i+=1 } +################################################# +## 4. Data Structures +################################################# -// Object oriented features +val a = Array(1, 2, 3, 5, 8, 13) +a(0) +a(3) +a(21) // Throws an exception + +val m = Map("fork" -> "tenedor", "spoon" -> "cuchara", "knife" -> "cuchillo") +m("fork") +m("spoon") +m("bottle") // Throws an exception + +val safeM = m.withDefaultValue("no lo se") +safeM("bottle") + +val s = Set(1, 3, 7) +s(0) +s(1) + +/* Look up the documentation of map here - + * http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Map + * and make sure you can read it + */ + + +// Tuples + +(1, 2) + +(4, 3, 2) + +(1, 2, "three") + +(a, 2, "three") + +// Why have this? +val divideInts = (x:Int, y:Int) => (x / y, x % y) + +divideInts(10,3) // The function divideInts gives you the result and the remainder + +// To access the elements of a tuple, use _._n where n is the 1-based index of +// the element +val d = divideInts(10,3) + +d._1 + +d._2 + + +################################################# +## 5. Object Oriented Programming +################################################# + +/* + Aside: Everything we've done so far in this tutorial has been simple + expressions (values, functions, etc). These expressions are fine to type into + the command-line interpreter for quick tests, but they cannot exist by + themselves in a Scala file. For example, you cannot have just "val x = 5" in + a Scala file. Instead, the only top-level constructs allowed in Scala are: + + - objects + - classes + - case classes + - traits + + And now we will explain what these are. +*/ -// Classname is Dog class Dog { //A method called bark, returning a String def bark: String = { @@ -289,8 +289,6 @@ class Dog { // Classes can contain nearly any other construct, including other classes, // functions, methods, objects, case classes, traits etc. - - // Case classes case class Person(name:String, phoneNumber:String) @@ -298,8 +296,12 @@ case class Person(name:String, phoneNumber:String) Person("George", "1234") == Person("Kate", "1236") +// Objects and traits coming soon! + -// Pattern matching +################################################# +## 6. Pattern Matching +################################################# val me = Person("George", "1234") @@ -338,49 +340,75 @@ matcher("52917") // => "No match on '52917'" matcher("52752-16432-22178-47917") // => "Serial key: 52752, 16432, 22178, 47917" -// Strings +################################################# +## 7. Functional Programming +################################################# -"Scala strings are surrounded by double quotes" // -'a' // A Scala Char -'Single quote strings don't exist' // Error -"Strings have the usual Java methods defined on them".length -"They also have some extra Scala methods.".reverse +// Scala allows methods and functions to return, or take as parameters, other +// functions or methods. -// Seealso: scala.collection.immutable.StringOps +List(1, 2, 3) map add10 // List(11, 12, 13) - add10 is applied to each element -println("ABCDEF".length) -println("ABCDEF".substring(2, 6)) -println("ABCDEF".replace("C", "3")) +// Anonymous functions can be used instead of named functions: +List(1, 2, 3) map (x => x + 10) -// String interpolation -val n = 45 -println(s"We have $n apples") // => "We have 45 apples" +// And the underscore symbol, can be used if there is just one argument to the +// anonymous function. It gets bound as the variable +List(1, 2, 3) map (_ + 10) -// Expressions inside interpolated strings are also possible -val a = Array(11, 9, 6) -println(s"My second daughter is ${a(0) - a(2)} years old.") // => "My second daughter is 5 years old." -println(s"We have double the amount of ${n / 2.0} in apples.") // => "We have double the amount of 22.5 in apples." -println(s"Power of 2: ${math.pow(2, 2)}") // => "Power of 2: 4" +// If the anonymous block AND the function you are applying both take one +// argument, you can even omit the underscore +List("Dom", "Bob", "Natalia") foreach println -// Formatting with interpolated strings (note the prefixed f) -println(f"Power of 5: ${math.pow(5, 2)}%1.0f") // "Power of 5: 25" -println(f"Square root of 122: ${math.sqrt(122)}%1.4f") // "Square root of 122" -// Ignoring special characters. -println(raw"New line feed: \n. Carriage return: \r.") // => "New line feed: \n. Carriage return: \r." +// Combinators -// Some characters need to be 'escaped', e.g. a double quote inside a string: -val a = "They stood outside the \"Rose and Crown\"" // => "They stood outside the "Rose and Crown"" +s.map(sq) -// Triple double-quotes let strings span multiple rows and contain quotes -val html = """
-

Press belo', Joe

- | -
""" +val sSquared = s. map(sq) + +sSquared.filter(_ < 10) + +sSquared.reduce (_+_) + +// The filter function takes a predicate (a function from A -> Boolean) and +// selects all elements which satisfy the predicate +List(1, 2, 3) filter (_ > 2) // List(3) +List( + Person(name = "Dom", age = 23), + Person(name = "Bob", age = 30) +).filter(_.age > 25) // List(Person("Bob", 30)) + + +// Scala a foreach method defined on certain collections that takes a type +// returning Unit (a void method) +aListOfNumbers foreach (x => println(x)) +aListOfNumbers foreach println + +// For comprehensions + +for { n <- s } yield sq(n) + +val nSquared2 = for { n <- s } yield sq(n) + +for { n <- nSquared2 if n < 10 } yield n + +for { n <- s; nSquared = n * n if nSquared < 10} yield nSquared + +/* NB Those were not for loops. The semantics of a for loop is 'repeat', whereas + a for-comprehension defines a relationship between two sets of data. */ + + +################################################# +## 8. Implicits +################################################# +Coming soon! -// Application structure and organization +################################################# +## 9. Misc +################################################# // Importing things import scala.collection.immutable.List -- cgit v1.2.3 From 761f150b4bb0374e71aa16a2323a96a89603aaf7 Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Mon, 10 Nov 2014 19:38:48 -0700 Subject: Clean up of section 1 --- scala.html.markdown | 73 +++++++++++++++++++++++++++++++---------------------- 1 file changed, 43 insertions(+), 30 deletions(-) diff --git a/scala.html.markdown b/scala.html.markdown index a55e1f0e..a0983bdb 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -32,23 +32,36 @@ Scala - the scalable language ## 1. Basics ################################################# +// Single line comments start with two forward slashes + +/* + Multi line comments, as you can already see from above, look like this. +*/ + // Printing, and forcing a new line on the next print println("Hello world!") +println(10) + // Printing, without forcing a new line on next print print("Hello world") -// Declaring values is done using either var or val +// Declaring values is done using either var or val. // val declarations are immutable, whereas var's are mutable. Immutability is // a good thing. val x = 10 // x is now 10 x = 20 // error: reassignment to val -var x = 10 -x = 20 // x is now 20 +var y = 10 +y = 20 // y is now 20 -// Single line comments start with two forward slashes /* -Multi line comments look like this. + Scala is a statically typed language, yet note that in the above declarations, we did not specify + a type. This is due to a language feature called type inference. In most cases, Scala compiler can + guess what the type of a variable is, so you don't have to type it every time. We can explicitly + declare the type of a variable like so: */ +val z: Int = 10 +val a: Double = 1.0 +val b: Double = 10 // Notice automatic conversion from Int to Double, result is 10.0, not 10 // Boolean values true @@ -65,9 +78,11 @@ true == false // false 2 - 1 // 1 5 * 3 // 15 6 / 2 // 3 +6 / 4 // 1 +6.0 / 4 // 1.5 -// Evaluating a command in the REPL gives you the type and value of the result +// Evaluating an expression in the REPL gives you the type and value of the result 1 + 7 @@ -79,48 +94,46 @@ true == false // false This means the result of evaluating 1 + 7 is an object of type Int with a value of 8 - 1+7 will give you the same result + Note that "res29" is a sequentially generated variable name to store the results of the + expressions you typed, your output may differ. */ - -// Strings - -"Scala strings are surrounded by double quotes" // +"Scala strings are surrounded by double quotes" 'a' // A Scala Char 'Single quote strings don't exist' // Error -"Strings have the usual Java methods defined on them".length -"They also have some extra Scala methods.".reverse -// Seealso: scala.collection.immutable.StringOps +// Strings have the usual Java methods defined on them +"hello world".length +"ABCDEF".substring(2, 6) +"ABCDEF".replace("C", "3") -println("ABCDEF".length) -println("ABCDEF".substring(2, 6)) -println("ABCDEF".replace("C", "3")) +// They also have some extra Scala methods. See also: scala.collection.immutable.StringOps +"hello world".take(5) -// String interpolation +// String interpolation: notice the prefix "s" val n = 45 -println(s"We have $n apples") // => "We have 45 apples" +s"We have $n apples" // => "We have 45 apples" // Expressions inside interpolated strings are also possible val a = Array(11, 9, 6) -println(s"My second daughter is ${a(0) - a(2)} years old.") // => "My second daughter is 5 years old." -println(s"We have double the amount of ${n / 2.0} in apples.") // => "We have double the amount of 22.5 in apples." -println(s"Power of 2: ${math.pow(2, 2)}") // => "Power of 2: 4" +s"My second daughter is ${a(0) - a(2)} years old." // => "My second daughter is 5 years old." +s"We have double the amount of ${n / 2.0} in apples." // => "We have double the amount of 22.5 in apples." +s"Power of 2: ${math.pow(2, 2)}" // => "Power of 2: 4" -// Formatting with interpolated strings (note the prefixed f) -println(f"Power of 5: ${math.pow(5, 2)}%1.0f") // "Power of 5: 25" -println(f"Square root of 122: ${math.sqrt(122)}%1.4f") // "Square root of 122" +// Formatting with interpolated strings with the prefix "f" +f"Power of 5: ${math.pow(5, 2)}%1.0f" // "Power of 5: 25" +f"Square root of 122: ${math.sqrt(122)}%1.4f" // "Square root of 122" -// Ignoring special characters. -println(raw"New line feed: \n. Carriage return: \r.") // => "New line feed: \n. Carriage return: \r." +// Raw strings, ignoring special characters. +raw"New line feed: \n. Carriage return: \r." // => "New line feed: \n. Carriage return: \r." -// Some characters need to be 'escaped', e.g. a double quote inside a string: -val a = "They stood outside the \"Rose and Crown\"" // => "They stood outside the "Rose and Crown"" +// Some characters need to be "escaped", e.g. a double quote inside a string: +"They stood outside the \"Rose and Crown\"" // => "They stood outside the "Rose and Crown"" // Triple double-quotes let strings span multiple rows and contain quotes val html = """

Press belo', Joe

- | +
""" -- cgit v1.2.3 From 45bc0f19a0e52d5ccc58db555cb3823c1a00e973 Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Mon, 10 Nov 2014 19:46:26 -0700 Subject: Minor fix --- scala.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scala.html.markdown b/scala.html.markdown index a0983bdb..6311dba4 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -122,7 +122,7 @@ s"Power of 2: ${math.pow(2, 2)}" // => "Power of 2: 4" // Formatting with interpolated strings with the prefix "f" f"Power of 5: ${math.pow(5, 2)}%1.0f" // "Power of 5: 25" -f"Square root of 122: ${math.sqrt(122)}%1.4f" // "Square root of 122" +f"Square root of 122: ${math.sqrt(122)}%1.4f" // "Square root of 122: 11.0454" // Raw strings, ignoring special characters. raw"New line feed: \n. Carriage return: \r." // => "New line feed: \n. Carriage return: \r." -- cgit v1.2.3 From e784f52d33475b0cba059a0c07ad01b0e63578a9 Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Mon, 10 Nov 2014 19:58:14 -0700 Subject: Minor consistency edit --- scala.html.markdown | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/scala.html.markdown b/scala.html.markdown index 6311dba4..c8932c86 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -104,11 +104,12 @@ true == false // false // Strings have the usual Java methods defined on them "hello world".length -"ABCDEF".substring(2, 6) -"ABCDEF".replace("C", "3") +"hello world".substring(2, 6) +"hello world".replace("C", "3") // They also have some extra Scala methods. See also: scala.collection.immutable.StringOps "hello world".take(5) +"hello world".drop(5) // String interpolation: notice the prefix "s" val n = 45 -- cgit v1.2.3 From 29bc9a14495a433536a5aaeb1278e56708a81bb7 Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Wed, 12 Nov 2014 00:36:19 -0800 Subject: Use the right comment style for Scala... oops --- scala.html.markdown | 54 ++++++++++++++++++++++++++--------------------------- 1 file changed, 27 insertions(+), 27 deletions(-) diff --git a/scala.html.markdown b/scala.html.markdown index 6964b9a0..dc039f0c 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -28,9 +28,9 @@ Scala - the scalable language */ -################################################# -## 1. Basics -################################################# +///////////////////////////////////////////////// +// 1. Basics +///////////////////////////////////////////////// // Single line comments start with two forward slashes @@ -138,9 +138,9 @@ val html = """
""" -################################################# -## 2. Functions -################################################# +///////////////////////////////////////////////// +// 2. Functions +///////////////////////////////////////////////// // The next line gives you a function that takes an Int and returns it squared (x:Int) => x * x @@ -165,9 +165,9 @@ sq(10) // Gives you this: res33: Int = 100. val add10: Int => Int = _ + 10 -################################################# -## 3. Flow Control -################################################# +///////////////////////////////////////////////// +// 3. Flow Control +///////////////////////////////////////////////// 1 to 5 val r = 1 to 5 @@ -220,9 +220,9 @@ println(if (x == 10) "yeah" else "nope") val text = if (x == 10) "yeah" else "nope" -################################################# -## 4. Data Structures -################################################# +///////////////////////////////////////////////// +// 4. Data Structures +///////////////////////////////////////////////// val a = Array(1, 2, 3, 5, 8, 13) a(0) @@ -271,9 +271,9 @@ d._1 d._2 -################################################# -## 5. Object Oriented Programming -################################################# +///////////////////////////////////////////////// +// 5. Object Oriented Programming +///////////////////////////////////////////////// /* Aside: Everything we've done so far in this tutorial has been simple @@ -317,9 +317,9 @@ Person("George", "1234") == Person("Kate", "1236") // Objects and traits coming soon! -################################################# -## 6. Pattern Matching -################################################# +///////////////////////////////////////////////// +// 6. Pattern Matching +///////////////////////////////////////////////// val me = Person("George", "1234") @@ -358,9 +358,9 @@ matcher("52917") // => "No match on '52917'" matcher("52752-16432-22178-47917") // => "Serial key: 52752, 16432, 22178, 47917" -################################################# -## 7. Functional Programming -################################################# +///////////////////////////////////////////////// +// 7. Functional Programming +///////////////////////////////////////////////// // Scala allows methods and functions to return, or take as parameters, other // functions or methods. @@ -419,16 +419,16 @@ for { n <- s; nSquared = n * n if nSquared < 10} yield nSquared a for-comprehension defines a relationship between two sets of data. */ -################################################# -## 8. Implicits -################################################# +///////////////////////////////////////////////// +// 8. Implicits +///////////////////////////////////////////////// Coming soon! -################################################# -## 9. Misc -################################################# +///////////////////////////////////////////////// +// 9. Misc +///////////////////////////////////////////////// // Importing things import scala.collection.immutable.List -- cgit v1.2.3