From 34e52cac395346285c21c2a0191dac0284508c56 Mon Sep 17 00:00:00 2001 From: kiroco12 <48894338+kiroco12@users.noreply.github.com> Date: Tue, 7 Jan 2020 10:15:55 +0100 Subject: [PATCH 1/2] Updated to Scala 2.13.1 --- .travis.yml | 2 +- build.sbt | 2 +- project/ProjectPlugin.scala | 6 +- project/build.properties | 2 +- project/plugins.sbt | 2 +- src/main/scala/stdlib/Asserts.scala | 8 +- src/main/scala/stdlib/ByNameParameter.scala | 18 +- src/main/scala/stdlib/CaseClasses.scala | 22 +-- src/main/scala/stdlib/Classes.scala | 6 +- src/main/scala/stdlib/EmptyValues.scala | 26 +-- src/main/scala/stdlib/Enumerations.scala | 10 +- src/main/scala/stdlib/Extractors.scala | 42 ++--- src/main/scala/stdlib/ForExpressions.scala | 16 +- src/main/scala/stdlib/Formatting.scala | 10 +- .../scala/stdlib/HigherOrderFunctions.scala | 38 ++-- src/main/scala/stdlib/Implicits.scala | 12 +- .../InfixPrefixandPostfixOperators.scala | 10 +- src/main/scala/stdlib/InfixTypes.scala | 4 +- src/main/scala/stdlib/Iterables.scala | 30 +-- src/main/scala/stdlib/Lists.scala | 38 ++-- src/main/scala/stdlib/LiteralBooleans.scala | 2 +- src/main/scala/stdlib/LiteralNumbers.scala | 10 +- src/main/scala/stdlib/LiteralStrings.scala | 12 +- src/main/scala/stdlib/Maps.scala | 68 +++---- .../stdlib/NamedandDefaultArguments.scala | 28 +-- src/main/scala/stdlib/Objects.scala | 16 +- src/main/scala/stdlib/Options.scala | 20 +- src/main/scala/stdlib/ParentClasses.scala | 6 +- src/main/scala/stdlib/PartialFunctions.scala | 26 +-- .../stdlib/PartiallyAppliedFunctions.scala | 15 +- src/main/scala/stdlib/PatternMatching.scala | 104 +++++------ src/main/scala/stdlib/Ranges.scala | 12 +- .../scala/stdlib/RepeatedParameters.scala | 8 +- .../scala/stdlib/SequencesandArrays.scala | 18 +- src/main/scala/stdlib/Sets.scala | 40 ++-- src/main/scala/stdlib/Traits.scala | 20 +- src/main/scala/stdlib/Traversables.scala | 172 +++++++++--------- src/main/scala/stdlib/Tuples.scala | 8 +- src/main/scala/stdlib/TypeSignatures.scala | 8 +- src/main/scala/stdlib/TypeVariance.scala | 14 +- .../scala/stdlib/UniformAccessPrinciple.scala | 2 +- src/test/scala/stdlib/MapsSpec.scala | 9 - src/test/scala/stdlib/SetsSpec.scala | 9 - src/test/scala/stdlib/TraversablesSpec.scala | 10 +- version.sbt | 2 +- 45 files changed, 447 insertions(+), 496 deletions(-) diff --git a/.travis.yml b/.travis.yml index 251cd379..7ec1f31d 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,7 +1,7 @@ dist: xenial language: scala scala: -- 2.12.10 +- 2.13.1 jdk: - openjdk8 script: diff --git a/build.sbt b/build.sbt index a6260b9a..431ed469 100644 --- a/build.sbt +++ b/build.sbt @@ -1,4 +1,4 @@ -val scalaExercisesV = "0.5.0-SNAPSHOT" +val scalaExercisesV = "0.6.0-SNAPSHOT" def dep(artifactId: String) = "org.scala-exercises" %% artifactId % scalaExercisesV excludeAll (ExclusionRule("io.monix")) diff --git a/project/ProjectPlugin.scala b/project/ProjectPlugin.scala index a97cc3b3..634591f5 100644 --- a/project/ProjectPlugin.scala +++ b/project/ProjectPlugin.scala @@ -16,11 +16,11 @@ object ProjectPlugin extends AutoPlugin { object autoImport { lazy val V = new { - val scala212: String = "2.12.10" + val scala213: String = "2.13.1" val shapeless: String = "2.3.3" val scalatest: String = "3.1.0" val scalatestplusScheck: String = "3.1.0.0-RC2" - val scalacheck: String = "1.14.2" + val scalacheck: String = "1.14.3" val scalacheckShapeless: String = "1.2.3" } } @@ -40,7 +40,7 @@ object ProjectPlugin extends AutoPlugin { organizationEmail = "hello@47deg.com" ), orgLicenseSetting := ApacheLicense, - scalaVersion := V.scala212, + scalaVersion := V.scala213, scalaOrganization := "org.scala-lang", resolvers ++= Seq( Resolver.mavenLocal, diff --git a/project/build.properties b/project/build.properties index 1fc4b809..eb9d0270 100644 --- a/project/build.properties +++ b/project/build.properties @@ -1 +1 @@ -sbt.version=1.2.8 \ No newline at end of file +sbt.version=1.3.5 \ No newline at end of file diff --git a/project/plugins.sbt b/project/plugins.sbt index b149c55d..109ce8f7 100644 --- a/project/plugins.sbt +++ b/project/plugins.sbt @@ -2,5 +2,5 @@ resolvers ++= Seq( Resolver.sonatypeRepo("snapshots") ) -addSbtPlugin("org.scala-exercises" % "sbt-exercise" % "0.5.0-SNAPSHOT") +addSbtPlugin("org.scala-exercises" % "sbt-exercise" % "0.6.0-SNAPSHOT") addSbtPlugin("com.47deg" % "sbt-org-policies" % "0.12.0-M3") diff --git a/src/main/scala/stdlib/Asserts.scala b/src/main/scala/stdlib/Asserts.scala index 918716ae..92f6f715 100644 --- a/src/main/scala/stdlib/Asserts.scala +++ b/src/main/scala/stdlib/Asserts.scala @@ -45,13 +45,12 @@ object Asserts extends AnyFlatSpec with Matchers with org.scalaexercises.definit * * Come on, your turn: true and false values can be compared with should matchers: */ - def scalaTestAsserts(res0: Boolean) { + def scalaTestAsserts(res0: Boolean) = true should be(res0) - } /** Booleans in asserts can test equality: */ - def booleanAsserts(res0: Int) { + def booleanAsserts(res0: Int) = { val v1 = 4 v1 shouldEqual res0 @@ -60,8 +59,7 @@ object Asserts extends AnyFlatSpec with Matchers with org.scalaexercises.definit /** Sometimes we expect you to fill in the values: */ - def valuesAsserts(res0: Int) { + def valuesAsserts(res0: Int) = assert(res0 == 1 + 1) - } } diff --git a/src/main/scala/stdlib/ByNameParameter.scala b/src/main/scala/stdlib/ByNameParameter.scala index b007d441..8a7c7226 100644 --- a/src/main/scala/stdlib/ByNameParameter.scala +++ b/src/main/scala/stdlib/ByNameParameter.scala @@ -18,16 +18,16 @@ object ByNameParameter /** `() => Int` is a Function type that takes a `Unit` type. `Unit` is known as `void` to a Java programmer. The function returns an `Int`. You can place this as a method parameter so that you can you use it as a block, but still it doesn't look quite right: */ - def takesUnitByNameParameter(res0: Either[Throwable, Int]) { - def calc(x: () ⇒ Int): Either[Throwable, Int] = { + def takesUnitByNameParameter(res0: Either[Throwable, Int]) = { + def calc(x: () => Int): Either[Throwable, Int] = { try { Right(x()) //An explicit call of the x function } catch { - case b: Throwable ⇒ Left(b) + case b: Throwable => Left(b) } } - val y = calc { () ⇒ //Having explicitly declaring that Unit is a parameter with () + val y = calc { () => //Having explicitly declaring that Unit is a parameter with () 14 + 15 } @@ -36,13 +36,13 @@ object ByNameParameter /** A by-name parameter does the same thing as the previous koan but there is no need to explicitly handle `Unit` or `()`. This is used extensively in Scala to create blocks: */ - def byNameParameter(res0: Either[Throwable, Int]) { - def calc(x: ⇒ Int): Either[Throwable, Int] = { + def byNameParameter(res0: Either[Throwable, Int]) = { + def calc(x: => Int): Either[Throwable, Int] = { //x is a call by name parameter try { Right(x) } catch { - case b: Throwable ⇒ Left(b) + case b: Throwable => Left(b) } } @@ -58,9 +58,9 @@ object ByNameParameter /** By name parameters can also be used with `object` and `apply` to make interesting block-like calls: */ - def withApplyByNameParameter(res0: String) { + def withApplyByNameParameter(res0: String) = { object PigLatinizer { - def apply(x: ⇒ String) = x.tail + x.head + "ay" + def apply(x: => String) = x.tail + x.head + "ay" } val result = PigLatinizer { diff --git a/src/main/scala/stdlib/CaseClasses.scala b/src/main/scala/stdlib/CaseClasses.scala index fad8523b..aefdfd65 100644 --- a/src/main/scala/stdlib/CaseClasses.scala +++ b/src/main/scala/stdlib/CaseClasses.scala @@ -60,7 +60,7 @@ object CaseClasses extends AnyFlatSpec with Matchers with org.scalaexercises.def * * {{{ * object TermTest extends Application { - * def printTerm(term: Term) { + * def printTerm(term: Term) = { * term match { * case Var(n) => * print(n) @@ -94,7 +94,7 @@ object CaseClasses extends AnyFlatSpec with Matchers with org.scalaexercises.def * * Case classes have an automatic equals method that works: */ - def caseClassesSupportEquality(res0: Boolean, res1: Boolean, res2: Boolean, res3: Boolean) { + def caseClassesSupportEquality(res0: Boolean, res1: Boolean, res2: Boolean, res3: Boolean) = { case class Person(first: String, last: String) val p1 = new Person("Fred", "Jones") @@ -110,7 +110,7 @@ object CaseClasses extends AnyFlatSpec with Matchers with org.scalaexercises.def /** Case classes have an automatic hashcode method that works: */ - def hashcodeMethodCaseClasses(res0: Boolean, res1: Boolean) { + def hashcodeMethodCaseClasses(res0: Boolean, res1: Boolean) = { case class Person(first: String, last: String) val p1 = new Person("Fred", "Jones") @@ -123,7 +123,7 @@ object CaseClasses extends AnyFlatSpec with Matchers with org.scalaexercises.def /** Case classes can be created in a convenient way: */ - def creationCaseClasses(res0: Boolean, res1: Boolean, res2: Boolean) { + def creationCaseClasses(res0: Boolean, res1: Boolean, res2: Boolean) = { case class Dog(name: String, breed: String) val d1 = Dog("Scooby", "Doberman") @@ -137,7 +137,7 @@ object CaseClasses extends AnyFlatSpec with Matchers with org.scalaexercises.def /** Case classes have a convenient toString method defined: */ - def toStringMethodCaseClasses(res0: String) { + def toStringMethodCaseClasses(res0: String) = { case class Dog(name: String, breed: String) val d1 = Dog("Scooby", "Doberman") d1.toString should be(res0) @@ -145,7 +145,7 @@ object CaseClasses extends AnyFlatSpec with Matchers with org.scalaexercises.def /** Case classes have automatic properties: */ - def propertiesCaseClasses(res0: String, res1: String) { + def propertiesCaseClasses(res0: String, res1: String) = { case class Dog(name: String, breed: String) val d1 = Dog("Scooby", "Doberman") @@ -155,7 +155,7 @@ object CaseClasses extends AnyFlatSpec with Matchers with org.scalaexercises.def /** Case classes can have mutable properties: */ - def mutablePropertiesCaseClasses(res0: String, res1: String, res2: String, res3: String) { + def mutablePropertiesCaseClasses(res0: String, res1: String, res2: String, res3: String) = { case class Dog(var name: String, breed: String) // you can rename a dog, but change its breed? nah! val d1 = Dog("Scooby", "Doberman") @@ -170,7 +170,7 @@ object CaseClasses extends AnyFlatSpec with Matchers with org.scalaexercises.def /** There are safer alternatives for altering case classes: */ - def alteringCaseClasses(res0: String, res1: String, res2: String, res3: String) { + def alteringCaseClasses(res0: String, res1: String, res2: String, res3: String) = { case class Dog(name: String, breed: String) // Doberman val d1 = Dog("Scooby", "Doberman") @@ -199,7 +199,7 @@ object CaseClasses extends AnyFlatSpec with Matchers with org.scalaexercises.def res9: String, res10: Int, res11: String, - res12: Boolean) { + res12: Boolean) = { case class Person(first: String, last: String, age: Int = 0, ssn: String = "") val p1 = Person("Fred", "Jones", 23, "111-22-3333") val p2 = Person("Samantha", "Jones") // note missing age and ssn @@ -226,7 +226,7 @@ object CaseClasses extends AnyFlatSpec with Matchers with org.scalaexercises.def /** Case classes can be disassembled to their constituent parts as a tuple: */ - def asTupleCaseClasses(res0: String, res1: String, res2: Int, res3: String) { + def asTupleCaseClasses(res0: String, res1: String, res2: Int, res3: String) = { case class Person(first: String, last: String, age: Int = 0, ssn: String = "") val p1 = Person("Fred", "Jones", 23, "111-22-3333") @@ -240,7 +240,7 @@ object CaseClasses extends AnyFlatSpec with Matchers with org.scalaexercises.def /** Case classes are `Serializable`: */ - def serializableCaseClasses(res0: Boolean, res1: Boolean) { + def serializableCaseClasses(res0: Boolean, res1: Boolean) = { case class PersonCC(firstName: String, lastName: String) val indy = PersonCC("Indiana", "Jones") diff --git a/src/main/scala/stdlib/Classes.scala b/src/main/scala/stdlib/Classes.scala index 7e59520b..09e92063 100644 --- a/src/main/scala/stdlib/Classes.scala +++ b/src/main/scala/stdlib/Classes.scala @@ -17,7 +17,7 @@ object Classes extends AnyFlatSpec with Matchers with org.scalaexercises.definit * Here is a class definition which defines a class Point: * * {{{ - * class Point(x: Int, y: Int) { + * class Point(x: Int, y: Int) = { * override def toString(): String = "(" + x + ", " + y + ")" * } * }}} @@ -29,7 +29,7 @@ object Classes extends AnyFlatSpec with Matchers with org.scalaexercises.definit * * {{{ * object Classes { - * def main(args: Array[String]) { + * def main(args: Array[String]) = { * val pt = new Point(1, 2) * println(pt) * } @@ -41,7 +41,7 @@ object Classes extends AnyFlatSpec with Matchers with org.scalaexercises.definit * This also demonstrates the use of value parameters in `ClassWithValParameter(val name: String)`, which automatically creates an internal property `val name: String` in the class: * */ - def classWithValParameterClasses(res0: String) { + def classWithValParameterClasses(res0: String) = { class ClassWithValParameter(val name: String) val aClass = new ClassWithValParameter("Gandalf") aClass.name should be(res0) diff --git a/src/main/scala/stdlib/EmptyValues.scala b/src/main/scala/stdlib/EmptyValues.scala index f5141877..412daf12 100644 --- a/src/main/scala/stdlib/EmptyValues.scala +++ b/src/main/scala/stdlib/EmptyValues.scala @@ -36,45 +36,39 @@ object EmptyValues extends AnyFlatSpec with Matchers with org.scalaexercises.def * * An empty list can be represented by another nothing value: `Nil` */ - def emptyValuesEmptyValues(res0: Boolean) { + def emptyValuesEmptyValues(res0: Boolean) = List() === Nil shouldBe res0 - } /** [[http://www.scala-lang.org/api/current/index.html#scala.None None]] is the counterpart to [[http://www.scala-lang.org/api/current/index.html#scala.Some Some]], used when you're using Scala's [[http://www.scala-lang.org/api/current/index.html#scala.Option Option]] class to help avoid `null` references. * * `None` equals `None`: */ - def avoidingNullEmptyValues(res0: Boolean) { + def avoidingNullEmptyValues(res0: Boolean) = None === None shouldBe res0 - } /** `None` should be identical to `None`: */ - def identicalNoneEmptyValues(res0: Boolean) { + def identicalNoneEmptyValues(res0: Boolean) = None eq None shouldBe res0 - } /** `None` can be converted to a String: */ - def noneToStringEmptyValues(res0: String) { + def noneToStringEmptyValues(res0: String) = assert(None.toString === res0) - } /** `None` can be converted to an empty list: */ - def noneToListEmptyValues(res0: Boolean) { + def noneToListEmptyValues(res0: Boolean) = None.toList === Nil shouldBe res0 - } /** `None` is considered empty: */ - def noneAsEmptyEmptyValues(res0: Boolean) { + def noneAsEmptyEmptyValues(res0: Boolean) = assert(None.isEmpty === res0) - } /** `None` can be cast to `Any`, `AnyRef` or `AnyVal`: */ - def noneToAnyEmptyValues(res0: Boolean, res1: Boolean, res2: Boolean) { + def noneToAnyEmptyValues(res0: Boolean, res1: Boolean, res2: Boolean) = { None.asInstanceOf[Any] === None shouldBe res0 None.asInstanceOf[AnyRef] === None shouldBe res1 None.asInstanceOf[AnyVal] === None shouldBe res2 @@ -82,7 +76,7 @@ object EmptyValues extends AnyFlatSpec with Matchers with org.scalaexercises.def /** `None` can be used with `Option` instead of null references: */ - def noneWithOptionEmptyValues(res0: Boolean, res1: Option[String]) { + def noneWithOptionEmptyValues(res0: Boolean, res1: Option[String]) = { val optional: Option[String] = None assert(optional.isEmpty === res0) assert(optional === res1) @@ -90,7 +84,7 @@ object EmptyValues extends AnyFlatSpec with Matchers with org.scalaexercises.def /** `Some` is the opposite of `None` for `Option` types: */ - def someAgainstNoneEmptyValues(res0: Boolean, res1: Boolean) { + def someAgainstNoneEmptyValues(res0: Boolean, res1: Boolean) = { val optional: Option[String] = Some("Some Value") assert((optional == None) === res0, "Some(value) should not equal None") assert(optional.isEmpty === res1, "Some(value) should not be empty") @@ -98,7 +92,7 @@ object EmptyValues extends AnyFlatSpec with Matchers with org.scalaexercises.def /** `Option.getOrElse` can be used to provide a default in the case of `None`: */ - def getOrElseEmptyValues(res0: String, res1: String) { + def getOrElseEmptyValues(res0: String, res1: String) = { val optional: Option[String] = Some("Some Value") val optional2: Option[String] = None assert(optional.getOrElse("No Value") === res0, "Should return the value in the option") diff --git a/src/main/scala/stdlib/Enumerations.scala b/src/main/scala/stdlib/Enumerations.scala index e73e6b10..b2b86d6f 100644 --- a/src/main/scala/stdlib/Enumerations.scala +++ b/src/main/scala/stdlib/Enumerations.scala @@ -24,7 +24,7 @@ object Enumerations extends AnyFlatSpec with Matchers with org.scalaexercises.de res2: String, res3: String, res4: Boolean, - res5: Boolean) { + res5: Boolean) = { object Planets extends Enumeration { val Mercury = Value val Venus = Value @@ -55,7 +55,7 @@ object Enumerations extends AnyFlatSpec with Matchers with org.scalaexercises.de res2: String, res3: String, res4: Boolean, - res5: Boolean) { + res5: Boolean) = { object GreekPlanets extends Enumeration { val Mercury = Value(1, "Hermes") @@ -88,7 +88,7 @@ object Enumerations extends AnyFlatSpec with Matchers with org.scalaexercises.de res2: String, res3: String, res4: Boolean, - res5: Boolean) { + res5: Boolean) = { object Planets extends Enumeration { val Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune, Pluto = Value } @@ -111,7 +111,7 @@ object Enumerations extends AnyFlatSpec with Matchers with org.scalaexercises.de res2: String, res3: String, res4: Boolean, - res5: Boolean) { + res5: Boolean) = { object GreekPlanets extends Enumeration { val Mercury = Value("Hermes") @@ -137,7 +137,7 @@ object Enumerations extends AnyFlatSpec with Matchers with org.scalaexercises.de /** You can extend the `Enumeration` by extending the `Value` class. */ - def extendingValueEnumerations(res0: Double, res1: Double) { + def extendingValueEnumerations(res0: Double, res1: Double) = { object Planets extends Enumeration { val G = 6.67300E-11 diff --git a/src/main/scala/stdlib/Extractors.scala b/src/main/scala/stdlib/Extractors.scala index 607b821a..06097450 100644 --- a/src/main/scala/stdlib/Extractors.scala +++ b/src/main/scala/stdlib/Extractors.scala @@ -54,13 +54,13 @@ object Extractors extends AnyFlatSpec with Matchers with org.scalaexercises.defi * When you create a case class, it automatically can be used with pattern matching since it has an extractor: * */ - def extractorsExtractors(res0: String) { + def extractorsExtractors(res0: String) = { case class Employee(firstName: String, lastName: String) val rob = new Employee("Robin", "Williams") val result = rob match { - case Employee("Robin", _) ⇒ "Where's Batman?" - case _ ⇒ "No Batman Joke For You" + case Employee("Robin", _) => "Where's Batman?" + case _ => "No Batman Joke For You" } result should be(res0) @@ -68,7 +68,7 @@ object Extractors extends AnyFlatSpec with Matchers with org.scalaexercises.defi /** What's an extractor? In Scala it's a method in any `object` called `unapply`, and that method is used to disassemble the object given by returning a tuple wrapped in an option. Extractors can be used to assign values: */ - def calledUnapplyExtractors(res0: String, res1: String, res2: Int, res3: Int) { + def calledUnapplyExtractors(res0: String, res1: String, res2: Int, res3: Int) = { class Car(val make: String, val model: String, val year: Short, val topSpeed: Short) object ChopShop { @@ -85,7 +85,7 @@ object Extractors extends AnyFlatSpec with Matchers with org.scalaexercises.defi /** An extractor can also be used in pattern matching: */ - def patternMatchingExtractors(res0: String, res1: String) { + def patternMatchingExtractors(res0: String, res1: String) = { class Car(val make: String, val model: String, val year: Short, val topSpeed: Short) object ChopShop { @@ -93,8 +93,8 @@ object Extractors extends AnyFlatSpec with Matchers with org.scalaexercises.defi } val x = new Car("Chevy", "Camaro", 1978, 120) match { - case ChopShop(s, t, u, v) ⇒ (s, t) - case _ ⇒ ("Ford", "Edsel") + case ChopShop(s, t, u, v) => (s, t) + case _ => ("Ford", "Edsel") } x._1 should be(res0) @@ -103,7 +103,7 @@ object Extractors extends AnyFlatSpec with Matchers with org.scalaexercises.defi /** Since we aren't really using `u` and `v` in the previous pattern matching, they can be replaced with `_`: */ - def withWildcardExtractors(res0: String, res1: String) { + def withWildcardExtractors(res0: String, res1: String) = { class Car(val make: String, val model: String, val year: Short, val topSpeed: Short) object ChopShop { @@ -111,8 +111,8 @@ object Extractors extends AnyFlatSpec with Matchers with org.scalaexercises.defi } val x = new Car("Chevy", "Camaro", 1978, 120) match { - case ChopShop(s, t, _, _) ⇒ (s, t) - case _ ⇒ ("Ford", "Edsel") + case ChopShop(s, t, _, _) => (s, t) + case _ => ("Ford", "Edsel") } x._1 should be(res0) @@ -121,7 +121,7 @@ object Extractors extends AnyFlatSpec with Matchers with org.scalaexercises.defi /** As long as the method signatures aren't the same, you can have as many unapply methods as you want: */ - def multipleUnapplyExtractors(res0: String) { + def multipleUnapplyExtractors(res0: String) = { class Car(val make: String, val model: String, val year: Short, val topSpeed: Short) class Employee(val firstName: String, val middleName: Option[String], val lastName: String) @@ -132,8 +132,8 @@ object Extractors extends AnyFlatSpec with Matchers with org.scalaexercises.defi } val result = new Employee("Kurt", None, "Vonnegut") match { - case Tokenizer(c, d) ⇒ "c: %s, d: %s".format(c, d) - case _ ⇒ "Not found" + case Tokenizer(c, d) => "c: %s, d: %s".format(c, d) + case _ => "Not found" } result should be(res0) @@ -141,7 +141,7 @@ object Extractors extends AnyFlatSpec with Matchers with org.scalaexercises.defi /** An extractor can be any stable object, including instantiated classes with an unapply method: */ - def anyObjectExtractors(res0: String) { + def anyObjectExtractors(res0: String) = { class Car(val make: String, val model: String, val year: Short, val topSpeed: Short) { def unapply(x: Car) = Some((x.make, x.model)) } @@ -149,8 +149,8 @@ object Extractors extends AnyFlatSpec with Matchers with org.scalaexercises.defi val camaro = new Car("Chevy", "Camaro", 1978, 122) val result = camaro match { - case camaro(make, model) ⇒ "make: %s, model: %s".format(make, model) - case _ ⇒ "unknown" + case camaro(make, model) => "make: %s, model: %s".format(make, model) + case _ => "unknown" } result should be(res0) @@ -158,7 +158,7 @@ object Extractors extends AnyFlatSpec with Matchers with org.scalaexercises.defi /** A custom extractor is typically created in the companion object of the class. In this exercise, we use it as an assignment: */ - def asAssignmentExtractors(res0: String, res1: Option[String], res2: String) { + def asAssignmentExtractors(res0: String, res1: Option[String], res2: String) = { class Employee( val firstName: String, val middleName: Option[String], @@ -183,7 +183,7 @@ object Extractors extends AnyFlatSpec with Matchers with org.scalaexercises.defi /** In this exercise we use `unapply` for pattern matching employee objects: */ - def unapplyForPatternMatchingExtractors(res0: String) { + def unapplyForPatternMatchingExtractors(res0: String) = { class Employee( val firstName: String, val middleName: Option[String], @@ -200,11 +200,11 @@ object Extractors extends AnyFlatSpec with Matchers with org.scalaexercises.defi val singri = new Employee("Singri", None, "Keerthi") val result = singri match { - case Employee("Singri", None, x) ⇒ + case Employee("Singri", None, x) => "Yay, Singri %s! with no middle name!".format(x) - case Employee("Singri", Some(x), _) ⇒ + case Employee("Singri", Some(x), _) => "Yay, Singri with a middle name of %s".format(x) - case _ ⇒ "I don't care, going on break" + case _ => "I don't care, going on break" } result should be(res0) diff --git a/src/main/scala/stdlib/ForExpressions.scala b/src/main/scala/stdlib/ForExpressions.scala index 440124a1..40e22f8e 100644 --- a/src/main/scala/stdlib/ForExpressions.scala +++ b/src/main/scala/stdlib/ForExpressions.scala @@ -19,31 +19,31 @@ object ForExpressions /** `for` expressions can nest, with later generators varying more rapidly than earlier ones: */ - def canBeNestedForExpressions(res0: Int, res1: Int) { + def canBeNestedForExpressions(res0: Int, res1: Int) = { val xValues = 1 to 4 val yValues = 1 to 2 val coordinates = for { - x ← xValues - y ← yValues + x <- xValues + y <- yValues } yield (x, y) - coordinates(4) should be(res0, res1) + coordinates(4) should be((res0, res1)) } /** Using `for` we can make more readable code: */ - def readableCodeForExpressions(res0: List[Int]) { + def readableCodeForExpressions(res0: List[Int]) = { val nums = List(List(1), List(2), List(3), List(4), List(5)) val result = for { - numList ← nums - num ← numList + numList <- nums + num <- numList if (num % 2 == 0) } yield (num) result should be(res0) // Which is the same as - nums.flatMap(numList ⇒ numList).filter(_ % 2 == 0) should be(result) + nums.flatMap(numList => numList).filter(_ % 2 == 0) should be(result) // or the same as nums.flatten.filter(_ % 2 == 0) should be(result) diff --git a/src/main/scala/stdlib/Formatting.scala b/src/main/scala/stdlib/Formatting.scala index a6d35b4f..ae92664f 100644 --- a/src/main/scala/stdlib/Formatting.scala +++ b/src/main/scala/stdlib/Formatting.scala @@ -16,14 +16,14 @@ object Formatting extends AnyFlatSpec with Matchers with org.scalaexercises.defi /** String can be placed in format: */ - def placedInFormatFormatting(res0: String) { + def placedInFormatFormatting(res0: String) = { val s = "Hello World" "Application %s".format(s) should be(res0) } /** Character Literals can be a single character: */ - def characterFormatting(res0: String, res1: String) { + def characterFormatting(res0: String, res1: String) = { val a = 'a' val b = 'B' @@ -36,7 +36,7 @@ object Formatting extends AnyFlatSpec with Matchers with org.scalaexercises.defi /** Character Literals can be an escape sequence, including hexidecimal: */ - def escapeSequenceFormatting(res0: String, res1: String, res2: String) { + def escapeSequenceFormatting(res0: String, res1: String, res2: String) = { val c = '\u0061' //unicode for a val e = '\"' val f = '\\' @@ -48,14 +48,14 @@ object Formatting extends AnyFlatSpec with Matchers with org.scalaexercises.defi /** Formatting can also include numbers: */ - def includingNumbersFormatting(res0: String) { + def includingNumbersFormatting(res0: String) = { val j = 190 "%d bottles of beer on the wall" format j - 100 should be(res0) } /** Formatting can be used for any number of items, like a string and a number: */ - def anyNumberOfItemsFormatting(res0: String) { + def anyNumberOfItemsFormatting(res0: String) = { val j = 190 val k = "vodka" diff --git a/src/main/scala/stdlib/HigherOrderFunctions.scala b/src/main/scala/stdlib/HigherOrderFunctions.scala index 13763800..41cd5710 100644 --- a/src/main/scala/stdlib/HigherOrderFunctions.scala +++ b/src/main/scala/stdlib/HigherOrderFunctions.scala @@ -27,12 +27,12 @@ object HigherOrderFunctions res2: Int, res3: Int, res4: Int, - res5: Int) { - def lambda = { x: Int ⇒ + res5: Int) = { + def lambda = { x: Int => x + 1 } - def lambda2 = (x: Int) ⇒ x + 2 - val lambda3 = (x: Int) ⇒ x + 3 + def lambda2 = (x: Int) => x + 2 + val lambda3 = (x: Int) => x + 3 val lambda4 = new Function1[Int, Int] { def apply(v1: Int): Int = v1 - 1 @@ -58,8 +58,8 @@ object HigherOrderFunctions /** An anonymous function can also take on a different look by taking out the brackets: */ - def differentLookHigherOrderFunctions(res0: Int) { - def lambda = (x: Int) ⇒ x + 1 + def differentLookHigherOrderFunctions(res0: Int) = { + def lambda = (x: Int) => x + 1 def result = lambda(5) result should be(res0) } @@ -72,10 +72,10 @@ object HigherOrderFunctions * * A closure is a function which maintains a reference to one or more variables outside of the function scope (it "closes over" the variables). Scala will detect that you are using variables outside of scope and create an object instance to hold the shared variables. */ - def meetClosureHigherOrderFunctions(res0: Int, res1: Int) { + def meetClosureHigherOrderFunctions(res0: Int, res1: Int) = { var incrementer = 1 - def closure = { x: Int ⇒ + def closure = { x: Int => x + incrementer } @@ -93,11 +93,11 @@ object HigherOrderFunctions * * We can take that closure and throw it into a Higher Order Function and it will still hold the environment: */ - def holdEnvironmentHigherOrderFunctions(res0: Int, res1: Int) { - def summation(x: Int, y: Int ⇒ Int) = y(x) + def holdEnvironmentHigherOrderFunctions(res0: Int, res1: Int) = { + def summation(x: Int, y: Int => Int) = y(x) var incrementer = 3 - def closure = (x: Int) ⇒ x + incrementer + def closure = (x: Int) => x + incrementer val result = summation(10, closure) result should be(res0) @@ -109,7 +109,7 @@ object HigherOrderFunctions /** Higher Order Function returning another function: */ - def returningFunctionHigherOrderFunctions(res0: Boolean, res1: Int, res2: Int) { + def returningFunctionHigherOrderFunctions(res0: Boolean, res1: Int, res2: Int) = { def addWithoutSyntaxSugar(x: Int): Function1[Int, Int] = { new Function1[Int, Int]() { def apply(y: Int): Int = x + y @@ -125,8 +125,8 @@ object HigherOrderFunctions /** Function returning another function using an anonymous function: */ - def returningAnonymousFunctionHigherOrderFunctions(res0: Boolean, res1: Int, res2: Int) { - def addWithSyntaxSugar(x: Int) = (y: Int) ⇒ x + y + def returningAnonymousFunctionHigherOrderFunctions(res0: Boolean, res1: Int, res2: Int) = { + def addWithSyntaxSugar(x: Int) = (y: Int) => x + y addWithSyntaxSugar(1).isInstanceOf[Function1[Int, Int]] should be(res0) addWithSyntaxSugar(2)(3) should be(res1) @@ -137,8 +137,8 @@ object HigherOrderFunctions /** `isInstanceOf` is the same as `instanceof` in java, but in this case the parameter types can be *blanked out* using existential types with a single underline, since parameter types are unknown at runtime. */ - def isInstanceOfMethodHigherOrderFunctions(res0: Boolean) { - def addWithSyntaxSugar(x: Int) = (y: Int) ⇒ x + y + def isInstanceOfMethodHigherOrderFunctions(res0: Boolean) = { + def addWithSyntaxSugar(x: Int) = (y: Int) => x + y addWithSyntaxSugar(1).isInstanceOf[Function1[_, _]] should be(res0) } @@ -151,17 +151,17 @@ object HigherOrderFunctions res0: List[String], res1: List[String], res2: List[String], - res3: List[Int]) { + res3: List[Int]) = { def makeUpper(xs: List[String]) = xs map { _.toUpperCase } - def makeWhatEverYouLike(xs: List[String], sideEffect: String ⇒ String) = + def makeWhatEverYouLike(xs: List[String], sideEffect: String => String) = xs map sideEffect makeUpper(List("abc", "xyz", "123")) should be(res0) - makeWhatEverYouLike(List("ABC", "XYZ", "123"), { x ⇒ + makeWhatEverYouLike(List("ABC", "XYZ", "123"), { x => x.toLowerCase }) should be(res1) diff --git a/src/main/scala/stdlib/Implicits.scala b/src/main/scala/stdlib/Implicits.scala index 2a267efd..f16b19e0 100644 --- a/src/main/scala/stdlib/Implicits.scala +++ b/src/main/scala/stdlib/Implicits.scala @@ -57,7 +57,7 @@ object Implicits extends AnyFlatSpec with Matchers with org.scalaexercises.defin * * Creating a method `isOdd` for `Int`, which doesn't exist: */ - def implicitsParametersImplicits(res0: Boolean, res1: Boolean) { + def implicitsParametersImplicits(res0: Boolean, res1: Boolean) = { class KoanIntWrapper(val original: Int) { def isOdd = original % 2 != 0 } @@ -71,7 +71,7 @@ object Implicits extends AnyFlatSpec with Matchers with org.scalaexercises.defin /** Implicits rules can be imported into your scope with an import: */ - def importedImplicits(res0: Boolean, res1: Boolean) { + def importedImplicits(res0: Boolean, res1: Boolean) = { object MyPredef { class KoanIntWrapper(val original: Int) { @@ -97,7 +97,7 @@ object Implicits extends AnyFlatSpec with Matchers with org.scalaexercises.defin res1: Boolean, res2: Boolean, res3: Boolean, - res4: Boolean) { + res4: Boolean) = { import java.math.BigInteger implicit def Int2BigIntegerConvert(value: Int): BigInteger = new BigInteger(value.toString) @@ -116,7 +116,7 @@ object Implicits extends AnyFlatSpec with Matchers with org.scalaexercises.defin /** Implicits can be used to declare a value to be provided as a default as long as an implicit value is set with in the scope. These are called Implicit Function Parameters: */ - def asDefaultImplicits(res0: BigDecimal) { + def asDefaultImplicits(res0: BigDecimal) = { def howMuchCanIMake_?(hours: Int)(implicit dollarsPerHour: BigDecimal) = dollarsPerHour * hours @@ -127,7 +127,7 @@ object Implicits extends AnyFlatSpec with Matchers with org.scalaexercises.defin /** Implicit Function Parameters can contain a list of implicits: */ - def listOfImplicitsImplicits(res0: String) { + def listOfImplicitsImplicits(res0: String) = { def howMuchCanIMake_?(hours: Int)(implicit amount: BigDecimal, currencyName: String) = (amount * hours).toString() + " " + currencyName @@ -139,7 +139,7 @@ object Implicits extends AnyFlatSpec with Matchers with org.scalaexercises.defin /** Default arguments, though, are preferred to Implicit Function Parameters: */ - def defaultArgumentsImplicits(res0: String, res1: String) { + def defaultArgumentsImplicits(res0: String, res1: String) = { def howMuchCanIMake_?(hours: Int, amount: BigDecimal = 34, currencyName: String = "Dollars") = (amount * hours).toString() + " " + currencyName diff --git a/src/main/scala/stdlib/InfixPrefixandPostfixOperators.scala b/src/main/scala/stdlib/InfixPrefixandPostfixOperators.scala index f350116f..35e2dac6 100644 --- a/src/main/scala/stdlib/InfixPrefixandPostfixOperators.scala +++ b/src/main/scala/stdlib/InfixPrefixandPostfixOperators.scala @@ -20,7 +20,7 @@ object InfixPrefixandPostfixOperators /** Any method which takes a single parameter can be used as an infix operator: `a.m(b)` can also be written as `a m b`. */ - def singleParameterInfixPrefixandPostfixOperators(res0: Int, res1: Int) { + def singleParameterInfixPrefixandPostfixOperators(res0: Int, res1: Int) = { val g: Int = 3 (g + 4) should be(res0) // + is an infix operator g.+(4) should be(res1) // same result but not using the infix operator @@ -28,7 +28,7 @@ object InfixPrefixandPostfixOperators /** Infix operators do NOT work if an object has a method that takes two parameters: */ - def notWithTwoInfixPrefixandPostfixOperators(res0: Int, res1: Int) { + def notWithTwoInfixPrefixandPostfixOperators(res0: Int, res1: Int) = { val g: String = "Check out the big brains on Brad!" g indexOf 'o' should be(res0) //indexOf(Char) can be used as an infix operator @@ -47,7 +47,7 @@ object InfixPrefixandPostfixOperators * - `foo bar baz bam` means `(foo.bar(baz)).bam` * - `foo bar baz bam bim` means `(foo.bar(baz)).bam(bim)`. */ - def postfixOperatorInfixPrefixandPostfixOperators(res0: String) { + def postfixOperatorInfixPrefixandPostfixOperators(res0: String) = { val g: Int = 31 (g toHexString) should be(res0) //toHexString takes no params therefore can be called as a postfix operator. //Hint: The answer is "1f" @@ -55,14 +55,14 @@ object InfixPrefixandPostfixOperators /** Prefix operators work if an object has a method name that starts with `unary_` : */ - def startsWithUnaryInfixPrefixandPostfixOperators(res0: Int) { + def startsWithUnaryInfixPrefixandPostfixOperators(res0: Int) = { val g: Int = 31 (-g) should be(res0) } /** Here's how to create a prefix operator for our own class. The only identifiers that can be used as prefix operators are `+`, `-`, `!`, and `~`: */ - def ourOwnOperatorInfixPrefixandPostfixOperators(res0: String, res1: String) { + def ourOwnOperatorInfixPrefixandPostfixOperators(res0: String, res1: String) = { class Stereo { def unary_+ = "on" diff --git a/src/main/scala/stdlib/InfixTypes.scala b/src/main/scala/stdlib/InfixTypes.scala index 5dae5fca..738be532 100644 --- a/src/main/scala/stdlib/InfixTypes.scala +++ b/src/main/scala/stdlib/InfixTypes.scala @@ -22,7 +22,7 @@ object InfixTypes extends AnyFlatSpec with Matchers with org.scalaexercises.defi * * We can make a type infix, meaning that the type can be displayed in complement between two types in order to make a readable declaration: */ - def infixTypeInfixTypes(res0: String) { + def infixTypeInfixTypes(res0: String) = { case class Person(name: String) class Loves[A, B](val a: A, val b: B) @@ -38,7 +38,7 @@ object InfixTypes extends AnyFlatSpec with Matchers with org.scalaexercises.defi /** Of course we can make this a bit more elegant by creating an infix operator method to use with our infix type: */ - def infixOperatorInfixTypes(res0: String) { + def infixOperatorInfixTypes(res0: String) = { case class Person(name: String) { def loves(person: Person) = new Loves(this, person) } diff --git a/src/main/scala/stdlib/Iterables.scala b/src/main/scala/stdlib/Iterables.scala index 3c2c9481..1d97cb4d 100644 --- a/src/main/scala/stdlib/Iterables.scala +++ b/src/main/scala/stdlib/Iterables.scala @@ -28,7 +28,7 @@ object Iterables extends AnyFlatSpec with Matchers with org.scalaexercises.defin * Some common iterables are `Set`, `List`, `Vector`, `Stacks` and `Stream`. Iterator has two important methods: `hasNext`, which answers whether the iterator has another element available, and `next` which returns the next element in the iterator. * */ - def collectionIterablesIterables(res0: Int) { + def collectionIterablesIterables(res0: Int) = { val list = List(3, 5, 9, 11, 15, 19, 21) val it = list.iterator if (it.hasNext) { @@ -47,7 +47,7 @@ object Iterables extends AnyFlatSpec with Matchers with org.scalaexercises.defin res5: Int, res6: Int, res7: Int, - res8: Int) { + res8: Int) = { val list = List(3, 5, 9, 11, 15, 19, 21, 24, 32) val it = list grouped 3 it.next() should be(List(res0, res1, res2)) @@ -66,7 +66,7 @@ object Iterables extends AnyFlatSpec with Matchers with org.scalaexercises.defin res5: Int, res6: Int, res7: Int, - res8: Int) { + res8: Int) = { val list = List(3, 5, 9, 11, 15, 19, 21, 24, 32) val it = list sliding 3 it.next() should be(List(res0, res1, res2)) @@ -85,7 +85,7 @@ object Iterables extends AnyFlatSpec with Matchers with org.scalaexercises.defin res5: Int, res6: Int, res7: Int, - res8: Int) { + res8: Int) = { val list = List(3, 5, 9, 11, 15, 19, 21, 24, 32) val it = list sliding (3, 3) it.next() should be(List(res0, res1, res2)) @@ -95,14 +95,14 @@ object Iterables extends AnyFlatSpec with Matchers with org.scalaexercises.defin /** `takeRight` is the opposite of 'take' in `Traversable`. It retrieves the last elements of an `Iterable`: */ - def takeRightIterables(res0: Int, res1: Int, res2: Int) { + def takeRightIterables(res0: Int, res1: Int, res2: Int) = { val list = List(3, 5, 9, 11, 15, 19, 21, 24, 32) (list takeRight 3) should be(List(res0, res1, res2)) } /** `dropRight` will drop a specified number of elements from the right: */ - def dropRightIterables(res0: Int, res1: Int, res2: Int, res3: Int, res4: Int, res5: Int) { + def dropRightIterables(res0: Int, res1: Int, res2: Int, res3: Int, res4: Int, res5: Int) = { val list = List(3, 5, 9, 11, 15, 19, 21, 24, 32) (list dropRight 3) should be(List(res0, res1, res2, res3, res4, res5)) } @@ -111,7 +111,7 @@ object Iterables extends AnyFlatSpec with Matchers with org.scalaexercises.defin * * e.g. `Iterable(x1, x2, x3) zip Iterable(y1, y2, y3)` will return `((x1, y1), (x2, y2), (x3, y3))`: */ - def zipIterables(res0: Int, res1: String, res2: Int, res3: String, res4: Int, res5: String) { + def zipIterables(res0: Int, res1: String, res2: Int, res3: String, res4: Int, res5: String) = { val xs = List(3, 5, 9) val ys = List("Bob", "Ann", "Stella") (xs zip ys) should be(List((res0, res1), (res2, res3), (res4, res5))) @@ -122,7 +122,7 @@ object Iterables extends AnyFlatSpec with Matchers with org.scalaexercises.defin * e.g. `Iterable(x1, x2, x3) zip Iterable(y1, y2)` will return `((x1, y1), (x2, y2))`: * */ - def sameSizeZipIterables(res0: Int, res1: String, res2: Int, res3: String) { + def sameSizeZipIterables(res0: Int, res1: String, res2: Int, res3: String) = { val xs = List(3, 5, 9) val ys = List("Bob", "Ann") (xs zip ys) should be(List((res0, res1), (res2, res3))) @@ -142,7 +142,7 @@ object Iterables extends AnyFlatSpec with Matchers with org.scalaexercises.defin res6: String, res7: Int, res8: String, - res9: String) { + res9: String) = { val xs = List(3, 5, 9) val ys = List("Bob", "Ann") (xs zipAll (ys, -1, "?")) should be(List((res0, res1), (res2, res3), (res4, "?"))) @@ -155,29 +155,29 @@ object Iterables extends AnyFlatSpec with Matchers with org.scalaexercises.defin /** `zipWithIndex` will zip an `Iterable` with its integer index: */ - def zipWithIndexIterables(res0: String, res1: String, res2: Int, res3: String) { + def zipWithIndexIterables(res0: String, res1: String, res2: Int, res3: String) = { val xs = List("Manny", "Moe", "Jack") xs.zipWithIndex should be(List((res0, 0), (res1, res2), (res3, 2))) } /** `sameElements` will return true if the two `Iterables` produce the same elements in the same order: */ - def sameElementsIterables(res0: Boolean, res1: Boolean, res2: Boolean, res3: Boolean) { + def sameElementsIterables(res0: Boolean, res1: Boolean, res2: Boolean, res3: Boolean) = { val xs = List("Manny", "Moe", "Jack") val ys = List("Manny", "Moe", "Jack") - (xs sameElements ys) should be(res0) + xs.iterator.sameElements(ys) should be(res0) val xt = List("Manny", "Moe", "Jack") val yt = List("Manny", "Jack", "Moe") - (xt sameElements yt) should be(res1) + xt.iterator.sameElements(yt) should be(res1) val xs1 = Set(3, 2, 1, 4, 5, 6, 7) val ys1 = Set(7, 2, 1, 4, 5, 6, 3) - (xs1 sameElements ys1) should be(res2) + xs1.iterator.sameElements(ys1) should be(res2) val xt1 = Set(1, 2, 3) val yt1 = Set(3, 2, 1) - (xt1 sameElements yt1) should be(res3) // Caution - see below! + xt1.iterator.sameElements(yt1) should be(res3) // Caution - see below! /** Note that very small Sets (containing up to 4 elements) are implemented differently to larger Sets; as a result, their iterators produce the elements in the order that they were originally added. This causes the surprising (and arguably incorrect) behaviour in the final example above. */ } diff --git a/src/main/scala/stdlib/Lists.scala b/src/main/scala/stdlib/Lists.scala index 0bb95d8d..4fab9c11 100644 --- a/src/main/scala/stdlib/Lists.scala +++ b/src/main/scala/stdlib/Lists.scala @@ -18,7 +18,7 @@ object Lists extends AnyFlatSpec with Matchers with org.scalaexercises.definitio * * `eq` tests identity (same object): */ - def similarToArraysLists(res0: Boolean) { + def similarToArraysLists(res0: Boolean) = { val a = List(1, 2, 3) val b = List(1, 2, 3) (a eq b) should be(res0) @@ -26,7 +26,7 @@ object Lists extends AnyFlatSpec with Matchers with org.scalaexercises.definitio /** `==` tests equality (same content): */ - def sameContentLists(res0: Boolean) { + def sameContentLists(res0: Boolean) = { val a = List(1, 2, 3) val b = List(1, 2, 3) (a == b) should be(res0) @@ -40,7 +40,7 @@ object Lists extends AnyFlatSpec with Matchers with org.scalaexercises.definitio res2: Boolean, res3: Boolean, res4: Boolean, - res5: Boolean) { + res5: Boolean) = { val a: List[String] = Nil val b: List[Int] = Nil @@ -56,14 +56,14 @@ object Lists extends AnyFlatSpec with Matchers with org.scalaexercises.definitio /** Lists can be easily created: */ - def easilyCreatedLists(res0: Int, res1: Int, res2: Int) { + def easilyCreatedLists(res0: Int, res1: Int, res2: Int) = { val a = List(1, 2, 3) a should equal(List(res0, res1, res2)) } /** Lists can be accessed via `head`, `headOption` and `tail`. Accessing a list via `head` is unsafe and may result in a `IndexOutOfBoundsException`. */ - def headAndTailLists(res0: Int, res1: Int, res2: Int) { + def headAndTailLists(res0: Int, res1: Int, res2: Int) = { val a = List(1, 2, 3) a.headOption should equal(Some(res0)) a.tail should equal(List(res1, res2)) @@ -71,7 +71,7 @@ object Lists extends AnyFlatSpec with Matchers with org.scalaexercises.definitio /** Lists can be accessed by position: */ - def byPositionLists(res0: Int, res1: Int, res2: Int) { + def byPositionLists(res0: Int, res1: Int, res2: Int) = { val a = List(1, 3, 5, 7, 9) a(0) should equal(res0) a(2) should equal(res1) @@ -84,9 +84,9 @@ object Lists extends AnyFlatSpec with Matchers with org.scalaexercises.definitio /** Lists are immutable: */ - def areImmutableLists(res0: Int, res1: Int, res2: Int, res3: Int) { + def areImmutableLists(res0: Int, res1: Int, res2: Int, res3: Int) = { val a = List(1, 3, 5, 7, 9) - val b = a.filterNot(v ⇒ v == 5) // remove where value is 5 + val b = a.filterNot(v => v == 5) // remove where value is 5 a should equal(List(1, 3, 5, 7, 9)) b should equal(List(res0, res1, res2, res3)) @@ -94,7 +94,7 @@ object Lists extends AnyFlatSpec with Matchers with org.scalaexercises.definitio /** Lists have many useful utility methods: */ - def usefulMethodsLists(res0: Int, res1: List[Int], res2: List[Int], res3: List[Int]) { + def usefulMethodsLists(res0: Int, res1: List[Int], res2: List[Int], res3: List[Int]) = { val a = List(1, 3, 5, 7, 9) // get the length of the list @@ -104,19 +104,19 @@ object Lists extends AnyFlatSpec with Matchers with org.scalaexercises.definitio a.reverse should equal(res1) // map a function to double the numbers over the list - a.map { v ⇒ + a.map { v => v * 2 } should equal(res2) // filter any values divisible by 3 in the list - a.filter { v ⇒ + a.filter { v => v % 3 == 0 } should equal(res3) } /** Functions over lists can use _ as shorthand: */ - def wildcardAsShorthandLists(res0: Int, res1: Int, res2: Int, res3: Int) { + def wildcardAsShorthandLists(res0: Int, res1: Int, res2: Int, res3: Int) = { val a = List(1, 2, 3) a.map { @@ -130,7 +130,7 @@ object Lists extends AnyFlatSpec with Matchers with org.scalaexercises.definitio /** Functions over lists can use `()` instead of `{}`: */ - def functionsOverListsLists(res0: Int, res1: Int, res2: Int, res3: Int, res4: Int) { + def functionsOverListsLists(res0: Int, res1: Int, res2: Int, res3: Int, res4: Int) = { val a = List(1, 2, 3) a.map(_ * 2) should equal(List(res0, res1, res2)) a.filter(_ % 2 != 0) should equal(List(res3, res4)) @@ -138,7 +138,7 @@ object Lists extends AnyFlatSpec with Matchers with org.scalaexercises.definitio /** Lists can be reduced with a mathematical operation: */ - def reducingListsLists(res0: Int, res1: Int) { + def reducingListsLists(res0: Int, res1: Int) = { val a = List(1, 3, 5, 7) a.reduceLeft(_ + _) should equal(res0) a.reduceLeft(_ * _) should equal(res1) @@ -146,7 +146,7 @@ object Lists extends AnyFlatSpec with Matchers with org.scalaexercises.definitio /** `foldLeft` is like `reduce`, but with an explicit starting value: */ - def foldLeftLists(res0: Int, res1: Int, res2: Int, res3: Int) { + def foldLeftLists(res0: Int, res1: Int, res2: Int, res3: Int) = { val a = List(1, 3, 5, 7) // NOTE: foldLeft uses a form called currying that we will explore later a.foldLeft(0)(_ + _) should equal(res0) @@ -157,14 +157,14 @@ object Lists extends AnyFlatSpec with Matchers with org.scalaexercises.definitio /** You can create a list from a range: */ - def fromRangeLists(res0: List[Int]) { + def fromRangeLists(res0: List[Int]) = { val a = (1 to 5).toList a should be(res0) } /** You can prepend elements to a List to get a new List: */ - def addElementsLists(res0: List[Int]) { + def addElementsLists(res0: List[Int]) = { val a = List(1, 3, 5, 7) 0 :: a should be(res0) @@ -172,7 +172,7 @@ object Lists extends AnyFlatSpec with Matchers with org.scalaexercises.definitio /** Lists can be concatened and Nil is an empty List: */ - def concatenateLists(res0: List[Int], res1: List[Int]) { + def concatenateLists(res0: List[Int], res1: List[Int]) = { val head = List(1, 3) val tail = List(5, 7) @@ -188,7 +188,7 @@ object Lists extends AnyFlatSpec with Matchers with org.scalaexercises.definitio res2: Int, res3: List[Int], res4: List[Int], - res5: List[Int]) { + res5: List[Int]) = { val d = Nil val c = 3 :: d val b = 2 :: c diff --git a/src/main/scala/stdlib/LiteralBooleans.scala b/src/main/scala/stdlib/LiteralBooleans.scala index 185d92bf..80eca359 100644 --- a/src/main/scala/stdlib/LiteralBooleans.scala +++ b/src/main/scala/stdlib/LiteralBooleans.scala @@ -25,7 +25,7 @@ object LiteralBooleans res2: Boolean, res3: Boolean, res4: Boolean, - res5: Boolean) { + res5: Boolean) = { val a = true val b = false val c = 1 > 2 diff --git a/src/main/scala/stdlib/LiteralNumbers.scala b/src/main/scala/stdlib/LiteralNumbers.scala index adec9efc..947bfd46 100644 --- a/src/main/scala/stdlib/LiteralNumbers.scala +++ b/src/main/scala/stdlib/LiteralNumbers.scala @@ -26,7 +26,7 @@ object LiteralNumbers res3: Int, res4: Int, res5: Int, - res6: Int) { + res6: Int) = { val a = 2 val b = 31 val c = 0x30F @@ -43,7 +43,7 @@ object LiteralNumbers h should be(res6) //Hint: 30F = 783 } - /** Long literals are 64-bit. They are specified by appending an `L` or `l` at the end of the declaration: + /** Long literals are 64-bit. They are specified by appending an `L` at the end of the declaration: */ def longLiteralsLiteralNumbers( res0: Long, @@ -52,12 +52,12 @@ object LiteralNumbers res3: Long, res4: Long, res5: Long, - res6: Long) { + res6: Long) = { val a = 2L val b = 31L val c = 0x30FL val e = 0L - val f = -2l + val f = -2L val g = -31L val h = -0x30FL @@ -83,7 +83,7 @@ object LiteralNumbers res5: Double, res6: Double, res7: Double, - res8: Double) { + res8: Double) = { val a = 3.0 val b = 3.00 val c = 2.73 diff --git a/src/main/scala/stdlib/LiteralStrings.scala b/src/main/scala/stdlib/LiteralStrings.scala index 6dcb3aaf..0ef8da53 100644 --- a/src/main/scala/stdlib/LiteralStrings.scala +++ b/src/main/scala/stdlib/LiteralStrings.scala @@ -19,7 +19,7 @@ object LiteralStrings /** Character literals are quoted with single quotes: */ - def characterLiteralsLiteralStrings(res0: String, res1: String) { + def characterLiteralsLiteralStrings(res0: String, res1: String) = { val a = 'a' val b = 'B' @@ -29,7 +29,7 @@ object LiteralStrings /** Character literals can use hexadecimal Unicode: */ - def characterLiteralsUnicodeLiteralStrings(res0: String) { + def characterLiteralsUnicodeLiteralStrings(res0: String) = { val c = '\u0061' //unicode for a c.toString should be(res0) @@ -37,7 +37,7 @@ object LiteralStrings /** Character literals can use escape sequences: */ - def escapeSequenceLiteralStrings(res0: String, res1: String) { + def escapeSequenceLiteralStrings(res0: String, res1: String) = { val e = '\"' val f = '\\' @@ -47,7 +47,7 @@ object LiteralStrings /** One-line String literals are surrounded by quotation marks: */ - def oneLineLiteralStrings(res0: String) { + def oneLineLiteralStrings(res0: String) = { val a = "To be or not to be" a should be(res0) } @@ -56,7 +56,7 @@ object LiteralStrings * * Multiline String literals are surrounded by three quotation marks. */ - def multilineLiteralStrings(res0: Int) { + def multilineLiteralStrings(res0: Int) = { val a = """An apple a day keeps the doctor away""" @@ -69,7 +69,7 @@ object LiteralStrings * Multiline String literals can use | to specify the starting position * of subsequent lines, then use stripMargin to remove the surplus indentation. */ - def stripMarginLiteralStrings(res0: String) { + def stripMarginLiteralStrings(res0: String) = { val a = """An apple a day keeps | the doctor away""" diff --git a/src/main/scala/stdlib/Maps.scala b/src/main/scala/stdlib/Maps.scala index 7f54f396..7b66270a 100644 --- a/src/main/scala/stdlib/Maps.scala +++ b/src/main/scala/stdlib/Maps.scala @@ -26,31 +26,31 @@ object Maps extends AnyFlatSpec with Matchers with org.scalaexercises.definition * * Maps can be created easily: */ - def keyAndValueMaps(res0: Int) { + def keyAndValueMaps(res0: Int) = { val myMap = - Map("MI" → "Michigan", "OH" → "Ohio", "WI" → "Wisconsin", "IA" → "Iowa") + Map("MI" -> "Michigan", "OH" -> "Ohio", "WI" -> "Wisconsin", "IA" -> "Iowa") myMap.size should be(res0) } /** Maps do not contain multiple identical pairs: */ - def distinctPairingsMaps(res0: Int) { - val myMap = Map("MI" → "Michigan", "OH" → "Ohio", "WI" → "Wisconsin", "MI" → "Michigan") + def distinctPairingsMaps(res0: Int) = { + val myMap = Map("MI" -> "Michigan", "OH" -> "Ohio", "WI" -> "Wisconsin", "MI" -> "Michigan") myMap.size should be(res0) } /** Maps can be added to easily: */ - def easilyAddedMaps(res0: Boolean) { - val myMap = Map("MI" → "Michigan", "OH" → "Ohio", "WI" → "Wisconsin", "MI" → "Michigan") - val aNewMap = myMap + ("IL" → "Illinois") + def easilyAddedMaps(res0: Boolean) = { + val myMap = Map("MI" -> "Michigan", "OH" -> "Ohio", "WI" -> "Wisconsin", "MI" -> "Michigan") + val aNewMap = myMap + ("IL" -> "Illinois") aNewMap.contains("IL") should be(res0) } /** Map values can be iterated: */ - def canBeIteratedMaps(res0: Int, res1: String, res2: String) { - val myMap = Map("MI" → "Michigan", "OH" → "Ohio", "WI" → "Wisconsin", "MI" → "Michigan") + def canBeIteratedMaps(res0: Int, res1: String, res2: String) = { + val myMap = Map("MI" -> "Michigan", "OH" -> "Ohio", "WI" -> "Wisconsin", "MI" -> "Michigan") val mapValues = myMap.values mapValues.size should be(res0) @@ -63,17 +63,17 @@ object Maps extends AnyFlatSpec with Matchers with org.scalaexercises.definition /** Maps may be accessed: */ - def mayBeAccessedMaps(res0: String, res1: String) { + def mayBeAccessedMaps(res0: String, res1: String) = { val myMap = - Map("MI" → "Michigan", "OH" → "Ohio", "WI" → "Wisconsin", "IA" → "Iowa") + Map("MI" -> "Michigan", "OH" -> "Ohio", "WI" -> "Wisconsin", "IA" -> "Iowa") myMap("MI") should be(res0) myMap("IA") should be(res1) } /** Maps insertion with duplicate key updates previous entry with subsequent value: */ - def duplicatedKeyInsertionMaps(res0: Int, res1: String) { - val myMap = Map("MI" → "Michigan", "OH" → "Ohio", "WI" → "Wisconsin", "MI" → "Meechigan") + def duplicatedKeyInsertionMaps(res0: Int, res1: String) = { + val myMap = Map("MI" -> "Michigan", "OH" -> "Ohio", "WI" -> "Wisconsin", "MI" -> "Meechigan") val mapValues = myMap.values mapValues.size should be(res0) myMap("MI") should be(res1) @@ -82,8 +82,8 @@ object Maps extends AnyFlatSpec with Matchers with org.scalaexercises.definition /** Map keys may be of mixed type: */ - def mixedTypeKeysMaps(res0: String, res1: String) { - val myMap = Map("Ann Arbor" → "MI", 49931 → "MI") + def mixedTypeKeysMaps(res0: String, res1: String) = { + val myMap = Map("Ann Arbor" -> "MI", 49931 -> "MI") myMap("Ann Arbor") should be(res0) myMap(49931) should be(res1) } @@ -91,23 +91,23 @@ object Maps extends AnyFlatSpec with Matchers with org.scalaexercises.definition /** If a nonexistent map key is requested using `myMap(missingKey)`, a `NoSuchElementException` will be thrown. * Default values may be provided using either `getOrElse` or `withDefaultValue` for the entire map: */ - def defaultValuesMayBeProvidedMaps(res0: String, res1: String) { + def defaultValuesMayBeProvidedMaps(res0: String, res1: String) = { val myMap = - Map("MI" → "Michigan", "OH" → "Ohio", "WI" → "Wisconsin", "IA" → "Iowa") + Map("MI" -> "Michigan", "OH" -> "Ohio", "WI" -> "Wisconsin", "IA" -> "Iowa") intercept[NoSuchElementException] { myMap("TX") } myMap.getOrElse("TX", "missing data") should be(res0) - val myMap2 = Map("MI" → "Michigan", "OH" → "Ohio", "WI" → "Wisconsin", "IA" → "Iowa") withDefaultValue "missing data" + val myMap2 = Map("MI" -> "Michigan", "OH" -> "Ohio", "WI" -> "Wisconsin", "IA" -> "Iowa") withDefaultValue "missing data" myMap2("TX") should be(res1) } /** Map elements can be removed easily: */ - def easilyRemovedMaps(res0: Boolean, res1: Boolean) { + def easilyRemovedMaps(res0: Boolean, res1: Boolean) = { val myMap = - Map("MI" → "Michigan", "OH" → "Ohio", "WI" → "Wisconsin", "IA" → "Iowa") + Map("MI" -> "Michigan", "OH" -> "Ohio", "WI" -> "Wisconsin", "IA" -> "Iowa") val aNewMap = myMap - "MI" aNewMap.contains("MI") should be(res0) myMap.contains("MI") should be(res1) @@ -115,9 +115,9 @@ object Maps extends AnyFlatSpec with Matchers with org.scalaexercises.definition /** Map elements can be removed in multiple: */ - def removedInMultipleMaps(res0: Boolean, res1: Boolean, res2: Boolean, res3: Int, res4: Int) { + def removedInMultipleMaps(res0: Boolean, res1: Boolean, res2: Boolean, res3: Int, res4: Int) = { val myMap = - Map("MI" → "Michigan", "OH" → "Ohio", "WI" → "Wisconsin", "IA" → "Iowa") + Map("MI" -> "Michigan", "OH" -> "Ohio", "WI" -> "Wisconsin", "IA" -> "Iowa") val aNewMap = myMap -- List("MI", "OH") aNewMap.contains("MI") should be(res0) @@ -128,25 +128,11 @@ object Maps extends AnyFlatSpec with Matchers with org.scalaexercises.definition myMap.size should be(res4) } - /** Map elements can be removed with a tuple: - */ - def removedWithTupleMaps(res0: Boolean, res1: Boolean, res2: Boolean, res3: Int, res4: Int) { - val myMap = - Map("MI" → "Michigan", "OH" → "Ohio", "WI" → "Wisconsin", "IA" → "Iowa") - val aNewMap = myMap - ("MI", "WI") // Notice: single '-' operator for tuples - - aNewMap.contains("MI") should be(res0) - myMap.contains("MI") should be(res1) - aNewMap.contains("OH") should be(res2) - aNewMap.size should be(res3) - myMap.size should be(res4) - } - /** Attempted removal of nonexistent elements from a map is handled gracefully: */ - def attemptedRemovalMaps(res0: Boolean) { + def attemptedRemovalMaps(res0: Boolean) = { val myMap = - Map("MI" → "Michigan", "OH" → "Ohio", "WI" → "Wisconsin", "IA" → "Iowa") + Map("MI" -> "Michigan", "OH" -> "Ohio", "WI" -> "Wisconsin", "IA" -> "Iowa") val aNewMap = myMap - "MN" aNewMap.equals(myMap) should be(res0) @@ -154,11 +140,11 @@ object Maps extends AnyFlatSpec with Matchers with org.scalaexercises.definition /** Map equivalency is independent of order: */ - def orderIndependentMaps(res0: Boolean) { + def orderIndependentMaps(res0: Boolean) = { val myMap1 = - Map("MI" → "Michigan", "OH" → "Ohio", "WI" → "Wisconsin", "IA" → "Iowa") + Map("MI" -> "Michigan", "OH" -> "Ohio", "WI" -> "Wisconsin", "IA" -> "Iowa") val myMap2 = - Map("WI" → "Wisconsin", "MI" → "Michigan", "IA" → "Iowa", "OH" → "Ohio") + Map("WI" -> "Wisconsin", "MI" -> "Michigan", "IA" -> "Iowa", "OH" -> "Ohio") myMap1.equals(myMap2) should be(res0) } diff --git a/src/main/scala/stdlib/NamedandDefaultArguments.scala b/src/main/scala/stdlib/NamedandDefaultArguments.scala index c28cdf99..12197820 100644 --- a/src/main/scala/stdlib/NamedandDefaultArguments.scala +++ b/src/main/scala/stdlib/NamedandDefaultArguments.scala @@ -42,7 +42,7 @@ object NamedandDefaultArguments * Given classes below: * * {{{ - * class WithoutClassParameters() { + * class WithoutClassParameters() = { * def addColors(red: Int, green: Int, blue: Int) = { * (red, green, blue) * } @@ -52,7 +52,7 @@ object NamedandDefaultArguments * } * } * - * class WithClassParameters(val defaultRed: Int, val defaultGreen: Int, val defaultBlue: Int) { + * class WithClassParameters(val defaultRed: Int, val defaultGreen: Int, val defaultBlue: Int) = { * def addColors(red: Int, green: Int, blue: Int) = { * (red + defaultRed, green + defaultGreen, blue + defaultBlue) * } @@ -76,56 +76,56 @@ object NamedandDefaultArguments * * Can specify arguments in any order if you use their names: */ - def classWithoutParametersNamedandDefaultArguments(res0: Int, res1: Int, res2: Int) { + def classWithoutParametersNamedandDefaultArguments(res0: Int, res1: Int, res2: Int) = { val me = new WithoutClassParameters() // what happens if you change the order of these parameters (nothing) val myColor = me.addColors(green = 0, red = 255, blue = 0) // for koan, remove the values in the should equal - myColor should equal(res0, res1, res2) + myColor should equal((res0, res1, res2)) } /** Can default arguments if you leave them off: */ - def defaultArgumentsNamedandDefaultArguments(res0: Int, res1: Int, res2: Int) { + def defaultArgumentsNamedandDefaultArguments(res0: Int, res1: Int, res2: Int) = { val me = new WithoutClassParameters() val myColor = me.addColorsWithDefaults(green = 255) - myColor should equal(res0, res1, res2) + myColor should equal((res0, res1, res2)) } /** Can access class parameters and specify arguments in any order if you use their names: */ - def anyOrderNamedandDefaultArguments(res0: Int, res1: Int, res2: Int) { + def anyOrderNamedandDefaultArguments(res0: Int, res1: Int, res2: Int) = { val me = new WithClassParameters(40, 50, 60) val myColor = me.addColors(green = 50, red = 60, blue = 40) - myColor should equal(res0, res1, res2) + myColor should equal((res0, res1, res2)) } /** Can access class parameters and default arguments if you leave them off: */ - def accessClassParametersNamedandDefaultArguments(res0: Int, res1: Int, res2: Int) { + def accessClassParametersNamedandDefaultArguments(res0: Int, res1: Int, res2: Int) = { val me = new WithClassParameters(10, 20, 30) val myColor = me.addColorsWithDefaults(green = 70) - myColor should equal(res0, res1, res2) + myColor should equal((res0, res1, res2)) } /** Can default class parameters and have default arguments too: */ - def defaultClassArgumentsNamedandDefaultArguments(res0: Int, res1: Int, res2: Int) { + def defaultClassArgumentsNamedandDefaultArguments(res0: Int, res1: Int, res2: Int) = { val me = new WithClassParametersInClassDefinition() val myColor = me.addColorsWithDefaults(green = 70) - myColor should equal(res0, res1, res2) + myColor should equal((res0, res1, res2)) } /** Default parameters can be functions too: */ - def functionalDefaulParametersNamedandDefaultArguments(res0: Int, res1: Int) { - def reduce(a: Int, f: (Int, Int) ⇒ Int = _ + _): Int = f(a, a) + def functionalDefaulParametersNamedandDefaultArguments(res0: Int, res1: Int) = { + def reduce(a: Int, f: (Int, Int) => Int = _ + _): Int = f(a, a) reduce(5) should equal(res0) reduce(5, _ * _) should equal(res1) diff --git a/src/main/scala/stdlib/Objects.scala b/src/main/scala/stdlib/Objects.scala index 6efffbc2..4be834a3 100644 --- a/src/main/scala/stdlib/Objects.scala +++ b/src/main/scala/stdlib/Objects.scala @@ -16,7 +16,7 @@ object Objects extends AnyFlatSpec with Matchers with org.scalaexercises.definit /** An object is a singleton. One object, that's it. This object is a replacement of static in Java, and is called upon much in the same way: */ - def singletonObjects(res0: String, res1: String) { + def singletonObjects(res0: String, res1: String) = { object Greeting { def english = "Hi" @@ -30,7 +30,7 @@ object Objects extends AnyFlatSpec with Matchers with org.scalaexercises.definit /** Here is a proof that an object is a singleton, and not a static method in a class: */ - def notStaticMethodObjects(res0: Boolean, res1: Boolean) { + def notStaticMethodObjects(res0: Boolean, res1: Boolean) = { object Greeting { def english = "Hi" @@ -49,17 +49,17 @@ object Objects extends AnyFlatSpec with Matchers with org.scalaexercises.definit /** An object that has the same name as a class is called a companion object of the class, and it is often used to contain factory methods for the class that it complements: */ - def companionObjectObjects(res0: String) { + def companionObjectObjects(res0: String) = { class Movie(val name: String, val year: Short) object Movie { def academyAwardBestMoviesForYear(x: Short) = { //This is a match statement, more powerful than a Java switch statement! x match { - case 1930 ⇒ Some(new Movie("All Quiet On the Western Front", 1930)) - case 1931 ⇒ Some(new Movie("Cimarron", 1931)) - case 1932 ⇒ Some(new Movie("Grand Hotel", 1932)) - case _ ⇒ None + case 1930 => Some(new Movie("All Quiet On the Western Front", 1930)) + case 1931 => Some(new Movie("Cimarron", 1931)) + case 1932 => Some(new Movie("Grand Hotel", 1932)) + case _ => None } } } @@ -69,7 +69,7 @@ object Objects extends AnyFlatSpec with Matchers with org.scalaexercises.definit /** A companion object can also see private values and variables of the corresponding classes' instantiated objects: */ - def privateValuesObjects(res0: String, res1: String) { + def privateValuesObjects(res0: String, res1: String) = { class Person(val name: String, private val superheroName: String) //The superhero name is private! object Person { diff --git a/src/main/scala/stdlib/Options.scala b/src/main/scala/stdlib/Options.scala index dfc175c3..91b21a94 100644 --- a/src/main/scala/stdlib/Options.scala +++ b/src/main/scala/stdlib/Options.scala @@ -21,7 +21,7 @@ object Options extends AnyFlatSpec with Matchers with org.scalaexercises.definit * * `Option[A]` is a container for an optional value of type `A`. If the value of type `A` is present, the `Option[A]` is an instance of `Some[A]`, containing the present value of type `A.` If the value is absent, the `Option[A]` is the object `None`. */ - def conceptOptions(res0: Option[String], res1: Option[String]) { + def conceptOptions(res0: Option[String], res1: Option[String]) = { val someValue: Option[String] = Some("I am wrapped in something") someValue should be(res0) @@ -39,7 +39,7 @@ object Options extends AnyFlatSpec with Matchers with org.scalaexercises.definit * * Using `getOrElse`, we can extract the value if it exists, or return a provided default value. If we have a `Some(x)` we return `x`, and for `None` we return the default value. */ - def getOrElseOptions(res0: String, res1: String, res2: String) { + def getOrElseOptions(res0: String, res1: String, res2: String) = { val value1 = maybeItWillReturnSomething(true) val value2 = maybeItWillReturnSomething(false) @@ -53,7 +53,7 @@ object Options extends AnyFlatSpec with Matchers with org.scalaexercises.definit /** Checking whether option has value: */ - def isEmptyOptions(res0: Boolean, res1: Boolean) { + def isEmptyOptions(res0: Boolean, res1: Boolean) = { val value1 = maybeItWillReturnSomething(true) val value2 = maybeItWillReturnSomething(false) @@ -63,17 +63,17 @@ object Options extends AnyFlatSpec with Matchers with org.scalaexercises.definit /** Option can also be used with pattern matching: */ - def matchOptions(res0: Double, res1: Double) { + def matchOptions(res0: Double, res1: Double) = { val someValue: Option[Double] = Some(20.0) val value = someValue match { - case Some(v) ⇒ v - case None ⇒ 0.0 + case Some(v) => v + case None => 0.0 } value should be(res0) val noValue: Option[Double] = None val value1 = noValue match { - case Some(v) ⇒ v - case None ⇒ 0.0 + case Some(v) => v + case None => 0.0 } value1 should be(res1) } @@ -83,7 +83,7 @@ object Options extends AnyFlatSpec with Matchers with org.scalaexercises.definit * * One of these operations is `map`. This operation allows us to map the inner value to a different type while preserving the option: */ - def mapOptions(res0: Option[Double], res1: Option[Double]) { + def mapOptions(res0: Option[Double], res1: Option[Double]) = { val number: Option[Int] = Some(3) val noNumber: Option[Int] = None val result1 = number.map(_ * 1.5) @@ -97,7 +97,7 @@ object Options extends AnyFlatSpec with Matchers with org.scalaexercises.definit /** Another operation is `fold`. This operation will extract the value from the option, or provide a default if the value is `None` */ - def foldOptions(res0: Int, res1: Int) { + def foldOptions(res0: Int, res1: Int) = { val number: Option[Int] = Some(3) val noNumber: Option[Int] = None val result1 = number.fold(1)(_ * 3) diff --git a/src/main/scala/stdlib/ParentClasses.scala b/src/main/scala/stdlib/ParentClasses.scala index 976cbf9e..ebbf4a67 100644 --- a/src/main/scala/stdlib/ParentClasses.scala +++ b/src/main/scala/stdlib/ParentClasses.scala @@ -19,7 +19,7 @@ object ParentClasses extends AnyFlatSpec with Matchers with org.scalaexercises.d * Class hierarchy is linear, a class can only extend from one parent class: * */ - def allValuesAreObjectsParentClasses(res0: String, res1: String) { + def allValuesAreObjectsParentClasses(res0: String, res1: String) = { class Soldier(val firstName: String, val lastName: String) {} class Pilot(override val firstName: String, override val lastName: String, val squadron: Long) extends Soldier(firstName, lastName) @@ -30,7 +30,7 @@ object ParentClasses extends AnyFlatSpec with Matchers with org.scalaexercises.d /** A class that extends from another is polymorphic: */ - def polymorphicParentClasses(res0: String, res1: String) { + def polymorphicParentClasses(res0: String, res1: String) = { class Soldier(val firstName: String, val lastName: String) {} class Pilot(override val firstName: String, override val lastName: String, val squadron: Long) extends Soldier(firstName, lastName) @@ -53,7 +53,7 @@ object ParentClasses extends AnyFlatSpec with Matchers with org.scalaexercises.d * * A class can be placed inside an abstract class just like in Java: */ - def abstractClassParentClasses(res0: Int) { + def abstractClassParentClasses(res0: Int) = { abstract class Soldier(val firstName: String, val lastName: String) { class Catch(val number: Long) { diff --git a/src/main/scala/stdlib/PartialFunctions.scala b/src/main/scala/stdlib/PartialFunctions.scala index 491737ef..0c4cb4cb 100644 --- a/src/main/scala/stdlib/PartialFunctions.scala +++ b/src/main/scala/stdlib/PartialFunctions.scala @@ -19,7 +19,7 @@ object PartialFunctions /** A partial function is a `trait` that when implemented can be used as building blocks to determine a solution. The trait `PartialFunction` requires that the method `isDefinedAt` and `apply` be implemented: */ - def partialFunctionPartialFunctions(res0: Int, res1: Int) { + def partialFunctionPartialFunctions(res0: Int, res1: Int) = { val doubleEvens: PartialFunction[Int, Int] = new PartialFunction[Int, Int] { //States that this partial function will take on the task @@ -43,13 +43,13 @@ object PartialFunctions /** Case statements are a quick way to create partial functions. When you create a case statement, the `apply` and `isDefinedAt` methods are created automatically. */ - def caseStatementsPartialFunctions(res0: Int, res1: Int) { + def caseStatementsPartialFunctions(res0: Int, res1: Int) = { //These case statements are called case statements with guards val doubleEvens: PartialFunction[Int, Int] = { - case x if (x % 2) == 0 ⇒ x * 2 + case x if (x % 2) == 0 => x * 2 } val tripleOdds: PartialFunction[Int, Int] = { - case x if (x % 2) != 0 ⇒ x * 3 + case x if (x % 2) != 0 => x * 3 } val whatToDo = doubleEvens orElse tripleOdds //Here we chain the partial functions together @@ -59,16 +59,16 @@ object PartialFunctions /** The result of partial functions can have an `andThen` function added to the end of the chain: */ - def andThenPartialFunctions(res0: Int, res1: Int) { + def andThenPartialFunctions(res0: Int, res1: Int) = { //These are called case statements with guards val doubleEvens: PartialFunction[Int, Int] = { - case x if (x % 2) == 0 ⇒ x * 2 + case x if (x % 2) == 0 => x * 2 } val tripleOdds: PartialFunction[Int, Int] = { - case x if (x % 2) != 0 ⇒ x * 3 + case x if (x % 2) != 0 => x * 3 } - val addFive = (x: Int) ⇒ x + 5 + val addFive = (x: Int) => x + 5 val whatToDo = doubleEvens orElse tripleOdds andThen addFive //Here we chain the partial functions together whatToDo(3) should be(res0) whatToDo(4) should be(res1) @@ -76,19 +76,19 @@ object PartialFunctions /** `andThen` can be used to continue onto another chain of logic: */ - def chainOfLogicPartialFunctions(res0: String, res1: String) { + def chainOfLogicPartialFunctions(res0: String, res1: String) = { val doubleEvens: PartialFunction[Int, Int] = { - case x if (x % 2) == 0 ⇒ x * 2 + case x if (x % 2) == 0 => x * 2 } val tripleOdds: PartialFunction[Int, Int] = { - case x if (x % 2) != 0 ⇒ x * 3 + case x if (x % 2) != 0 => x * 3 } val printEven: PartialFunction[Int, String] = { - case x if (x % 2) == 0 ⇒ "Even" + case x if (x % 2) == 0 => "Even" } val printOdd: PartialFunction[Int, String] = { - case x if (x % 2) != 0 ⇒ "Odd" + case x if (x % 2) != 0 => "Odd" } val whatToDo = doubleEvens orElse tripleOdds andThen (printEven orElse printOdd) diff --git a/src/main/scala/stdlib/PartiallyAppliedFunctions.scala b/src/main/scala/stdlib/PartiallyAppliedFunctions.scala index 4a6af327..13886217 100644 --- a/src/main/scala/stdlib/PartiallyAppliedFunctions.scala +++ b/src/main/scala/stdlib/PartiallyAppliedFunctions.scala @@ -19,7 +19,7 @@ object PartiallyAppliedFunctions /** A partially applied function is a function that you do not apply any or all the arguments, creating another function. This partially applied function doesn't apply any arguments. */ - def partiallyAppliedPartiallyAppliedFunctions(res0: Int, res1: Int) { + def partiallyAppliedPartiallyAppliedFunctions(res0: Int, res1: Int) = { def sum(a: Int, b: Int, c: Int) = a + b + c val sum3 = sum _ sum3(1, 9, 7) should be(res0) @@ -28,7 +28,7 @@ object PartiallyAppliedFunctions /** Partially applied functions can replace any number of arguments: */ - def anyNumberArgumentsPartiallyAppliedFunctions(res0: Int, res1: Int) { + def anyNumberArgumentsPartiallyAppliedFunctions(res0: Int, res1: Int) = { def sum(a: Int, b: Int, c: Int) = a + b + c val sumC = sum(1, 10, _: Int) sumC(4) should be(res0) @@ -37,7 +37,12 @@ object PartiallyAppliedFunctions /** Currying is a technique to transform a function with multiple parameters into multiple functions which each take one parameter: */ - def curryingPartiallyAppliedFunctions(res0: Boolean, res1: Int, res2: Int, res3: Int, res4: Int) { + def curryingPartiallyAppliedFunctions( + res0: Boolean, + res1: Int, + res2: Int, + res3: Int, + res4: Int) = { def multiply(x: Int, y: Int) = x * y (multiply _).isInstanceOf[Function2[_, _, _]] should be(res0) val multiplyCurried = (multiply _).curried @@ -50,8 +55,8 @@ object PartiallyAppliedFunctions /** Currying allows you to create specialized versions of generalized functions: */ - def specializedVersionPartiallyAppliedFunctions(res0: List[Int], res1: List[Int]) { - def customFilter(f: Int ⇒ Boolean)(xs: List[Int]) = + def specializedVersionPartiallyAppliedFunctions(res0: List[Int], res1: List[Int]) = { + def customFilter(f: Int => Boolean)(xs: List[Int]) = xs filter f def onlyEven(x: Int) = x % 2 == 0 val xs = List(12, 11, 5, 20, 3, 13, 2) diff --git a/src/main/scala/stdlib/PatternMatching.scala b/src/main/scala/stdlib/PatternMatching.scala index 63159527..e7534d82 100644 --- a/src/main/scala/stdlib/PatternMatching.scala +++ b/src/main/scala/stdlib/PatternMatching.scala @@ -38,17 +38,17 @@ object PatternMatching * * Pattern matching returns something: */ - def patternMatchingMechanismPatternMatching(res0: Int) { + def patternMatchingMechanismPatternMatching(res0: Int) = { val stuff = "blue" val myStuff = stuff match { - case "red" ⇒ + case "red" => println("RED"); 1 - case "blue" ⇒ + case "blue" => println("BLUE"); 2 - case "green" ⇒ + case "green" => println("GREEN"); 3 - case _ ⇒ + case _ => println(stuff); 0 // case _ will trigger if all other cases fail. } @@ -57,27 +57,27 @@ object PatternMatching /** Pattern matching can return complex values: */ - def returnComplexPatternMatching(res0: Int, res1: Int, res2: Int) { + def returnComplexPatternMatching(res0: Int, res1: Int, res2: Int) = { val stuff = "blue" val myStuff = stuff match { - case "red" ⇒ (255, 0, 0) - case "green" ⇒ (0, 255, 0) - case "blue" ⇒ (0, 0, 255) - case _ ⇒ println(stuff); 0 + case "red" => (255, 0, 0) + case "green" => (0, 255, 0) + case "blue" => (0, 0, 255) + case _ => println(stuff); 0 } - myStuff should be(res0, res1, res2) + myStuff should be((res0, res1, res2)) } /** Pattern matching can match complex expressions: */ - def complexExpressionsPatternMatching(res0: String) { + def complexExpressionsPatternMatching(res0: String) = { def goldilocks(expr: Any) = expr match { - case ("porridge", "Papa") ⇒ "Papa eating porridge" - case ("porridge", "Mama") ⇒ "Mama eating porridge" - case ("porridge", "Baby") ⇒ "Baby eating porridge" - case _ ⇒ "what?" + case ("porridge", "Papa") => "Papa eating porridge" + case ("porridge", "Mama") => "Mama eating porridge" + case ("porridge", "Baby") => "Baby eating porridge" + case _ => "what?" } goldilocks(("porridge", "Mama")) should be(res0) @@ -85,12 +85,12 @@ object PatternMatching /** Pattern matching can wildcard parts of expressions: */ - def wildcardParsPatternMatching(res0: String, res1: String) { + def wildcardParsPatternMatching(res0: String, res1: String) = { def goldilocks(expr: Any) = expr match { - case ("porridge", _) ⇒ "eating" - case ("chair", "Mama") ⇒ "sitting" - case ("bed", "Baby") ⇒ "sleeping" - case _ ⇒ "what?" + case ("porridge", _) => "eating" + case ("chair", "Mama") => "sitting" + case ("bed", "Baby") => "sleeping" + case _ => "what?" } goldilocks(("porridge", "Papa")) should be(res0) @@ -99,13 +99,13 @@ object PatternMatching /** Pattern matching can substitute parts of expressions: */ - def substitutePartsPatternMatching(res0: String, res1: String) { - def goldilocks(expr: Any) = expr match { - case ("porridge", bear) ⇒ + def substitutePartsPatternMatching(res0: String, res1: String) = { + def goldilocks(expr: (String, String)) = expr match { + case ("porridge", bear) => bear + " said someone's been eating my porridge" - case ("chair", bear) ⇒ bear + " said someone's been sitting in my chair" - case ("bed", bear) ⇒ bear + " said someone's been sleeping in my bed" - case _ ⇒ "what?" + case ("chair", bear) => bear + " said someone's been sitting in my chair" + case ("bed", bear) => bear + " said someone's been sleeping in my bed" + case _ => "what?" } goldilocks(("porridge", "Papa")) should be(res0) @@ -117,7 +117,7 @@ object PatternMatching // * // * Pattern matching can be done on regular expression groups: // */ - // def regularExpressionsPatternMatching(res0: String, res1: String) { + // def regularExpressionsPatternMatching(res0: String, res1: String) = { // val EatingRegularExpression = """Eating Alert: bear=([^,]+),\s+source=(.+)""".r //.r turns a String to a regular expression // val SittingRegularExpression = // """Sitting Alert: bear=([^,]+),\s+source=(.+)""".r @@ -136,14 +136,14 @@ object PatternMatching /** A backquote can be used to refer to a stable variable in scope to create a case statement - this prevents "variable shadowing": */ - def createCaseStatementPatternMatching(res0: String, res1: String, res2: String, res3: String) { + def createCaseStatementPatternMatching(res0: String, res1: String, res2: String, res3: String) = { val foodItem = "porridge" - def goldilocks(expr: Any) = expr match { - case (`foodItem`, _) ⇒ "eating" - case ("chair", "Mama") ⇒ "sitting" - case ("bed", "Baby") ⇒ "sleeping" - case _ ⇒ "what?" + def goldilocks(expr: (String, String)) = expr match { + case (`foodItem`, _) => "eating" + case ("chair", "Mama") => "sitting" + case ("bed", "Baby") => "sleeping" + case _ => "what?" } goldilocks(("porridge", "Papa")) should be(res0) @@ -154,10 +154,10 @@ object PatternMatching /** A backquote can be used to refer to a method parameter as a stable variable to create a case statement: */ - def stableVariablePatternMatching(res0: Boolean, res1: Boolean, res2: Boolean) { + def stableVariablePatternMatching(res0: Boolean, res1: Boolean, res2: Boolean) = { def patternEquals(i: Int, j: Int) = j match { - case `i` ⇒ true - case _ ⇒ false + case `i` => true + case _ => false } patternEquals(3, 3) should be(res0) patternEquals(7, 9) should be(res1) @@ -166,10 +166,10 @@ object PatternMatching /** To pattern match against a `List`, the list can be split into parts, in this case the head `x` and the tail `xs`. Since the case doesn't terminate in `Nil`, `xs` is interpreted as the rest of the list: */ - def againstListsPatternMatching(res0: Int) { + def againstListsPatternMatching(res0: Int) = { val secondElement = List(1, 2, 3) match { - case x :: xs ⇒ xs.head - case _ ⇒ 0 + case x :: xs => xs.head + case _ => 0 } secondElement should be(res0) @@ -177,10 +177,10 @@ object PatternMatching /** To obtain the second element you can expand on the pattern. Where `x` is the first element, `y` is the second element, and `xs` is the rest: */ - def againstListsIIPatternMatching(res0: Int) { + def againstListsIIPatternMatching(res0: Int) = { val secondElement = List(1, 2, 3) match { - case x :: y :: xs ⇒ y - case _ ⇒ 0 + case x :: y :: xs => y + case _ => 0 } secondElement should be(res0) @@ -188,10 +188,10 @@ object PatternMatching /** Same koan as above, but we are pattern matching a list with only one item! */ - def againstListsIIIPatternMatching(res0: Int) { + def againstListsIIIPatternMatching(res0: Int) = { val secondElement = List(1) match { - case x :: y :: xs ⇒ y // only matches a list with two or more items - case _ ⇒ 0 + case x :: y :: xs => y // only matches a list with two or more items + case _ => 0 } secondElement should be(res0) @@ -199,10 +199,10 @@ object PatternMatching /** To pattern match against `List`, you can also establish a pattern match if you know the exact number of elements in a `List`: */ - def againstListsIVPatternMatching(res0: Int) { + def againstListsIVPatternMatching(res0: Int) = { val r = List(1, 2, 3) match { - case x :: y :: Nil ⇒ y // only matches a list with exactly two items - case _ ⇒ 0 + case x :: y :: Nil => y // only matches a list with exactly two items + case _ => 0 } r should be(res0) @@ -210,10 +210,10 @@ object PatternMatching /** If a pattern is exactly one element longer than a `List`, it extracts the final `Nil`: */ - def againstListsVPatternMatching(res0: Boolean) { + def againstListsVPatternMatching(res0: Boolean) = { val r = List(1, 2, 3) match { - case x :: y :: z :: tail ⇒ tail - case _ ⇒ 0 + case x :: y :: z :: tail => tail + case _ => 0 } r == Nil should be(res0) diff --git a/src/main/scala/stdlib/Ranges.scala b/src/main/scala/stdlib/Ranges.scala index f1c67a20..90aa4e8e 100644 --- a/src/main/scala/stdlib/Ranges.scala +++ b/src/main/scala/stdlib/Ranges.scala @@ -24,7 +24,7 @@ object Ranges extends AnyFlatSpec with Matchers with org.scalaexercises.definiti * * A range's upper bound is not inclusive: */ - def upperNotInclusiveRangeExercises(res0: Int, res1: Int, res2: Int) { + def upperNotInclusiveRangeExercises(res0: Int, res1: Int, res2: Int) = { val someNumbers = Range(0, 10) val second = someNumbers(1) val last = someNumbers.last @@ -36,7 +36,7 @@ object Ranges extends AnyFlatSpec with Matchers with org.scalaexercises.definiti /** Ranges can be specified using 'until': */ - def untilRangeExercises(res0: Boolean) { + def untilRangeExercises(res0: Boolean) = { val someNumbers = Range(0, 10) val otherRange = 0 until 10 @@ -45,7 +45,7 @@ object Ranges extends AnyFlatSpec with Matchers with org.scalaexercises.definiti /** Range can specify a step for an increment: */ - def incrementsRangeExercises(res0: Int, res1: Int, res2: Int) { + def incrementsRangeExercises(res0: Int, res1: Int, res2: Int) = { val someNumbers = Range(2, 10, 3) val second = someNumbers(1) val last = someNumbers.last @@ -57,7 +57,7 @@ object Ranges extends AnyFlatSpec with Matchers with org.scalaexercises.definiti /** A range does not include its upper bound, even in a step increment: */ - def upperInIncrementRangeExercises(res0: Boolean, res1: Boolean, res2: Boolean) { + def upperInIncrementRangeExercises(res0: Boolean, res1: Boolean, res2: Boolean) = { val someNumbers = Range(0, 34, 2) someNumbers.contains(33) should be(res0) someNumbers.contains(32) should be(res1) @@ -66,7 +66,7 @@ object Ranges extends AnyFlatSpec with Matchers with org.scalaexercises.definiti /** Range can specify to include its upper bound value: */ - def specifyUpperRangeExercises(res0: Boolean) { + def specifyUpperRangeExercises(res0: Boolean) = { val someNumbers = Range(0, 34).inclusive someNumbers.contains(34) should be(res0) @@ -74,7 +74,7 @@ object Ranges extends AnyFlatSpec with Matchers with org.scalaexercises.definiti /** Inclusive ranges can be specified using 'to': */ - def inclusiveWithToRangeExercises(res0: Boolean) { + def inclusiveWithToRangeExercises(res0: Boolean) = { val someNumbers = Range(0, 34).inclusive val otherRange = 0 to 34 diff --git a/src/main/scala/stdlib/RepeatedParameters.scala b/src/main/scala/stdlib/RepeatedParameters.scala index 1cb8d276..725ee694 100644 --- a/src/main/scala/stdlib/RepeatedParameters.scala +++ b/src/main/scala/stdlib/RepeatedParameters.scala @@ -30,21 +30,19 @@ object RepeatedParameters * Resolve: * */ - def theLastParameterRepeatedParameters(res0: String) { + def theLastParameterRepeatedParameters(res0: String) = repeatedParameterMethod(3, "egg", "a delicious sandwich", "protein", "high cholesterol") should be( res0) - } /** A repeated parameter can accept a collection as the last parameter but will be considered a single object: */ - def acceptCollectionRepeatedParameters(res0: String) { + def acceptCollectionRepeatedParameters(res0: String) = repeatedParameterMethod(3, "egg", List("a delicious sandwich", "protein", "high cholesterol")) should be( res0) - } /** A repeated parameter can accept a collection - if you want it expanded, add `:_*` */ - def expandCollectionRepeatedParameters(res0: String) { + def expandCollectionRepeatedParameters(res0: String) = { repeatedParameterMethod( 3, "egg", diff --git a/src/main/scala/stdlib/SequencesandArrays.scala b/src/main/scala/stdlib/SequencesandArrays.scala index d55f7533..7b59d235 100644 --- a/src/main/scala/stdlib/SequencesandArrays.scala +++ b/src/main/scala/stdlib/SequencesandArrays.scala @@ -21,7 +21,7 @@ object SequencesandArrays * * A list can be converted to an array: */ - def sequentialCollectionSequencesandArrays(res0: Int, res1: Int, res2: Int) { + def sequentialCollectionSequencesandArrays(res0: Int, res1: Int, res2: Int) = { val l = List(1, 2, 3) val a = l.toArray a should equal(Array(res0, res1, res2)) @@ -32,7 +32,7 @@ object SequencesandArrays * Any sequence can be converted to a list: * */ - def orderedElementsSequencesandArrays(res0: List[Int]) { + def orderedElementsSequencesandArrays(res0: List[Int]) = { val a = Array(1, 2, 3) val s = a.toSeq val l = s.toList @@ -41,21 +41,21 @@ object SequencesandArrays /** You can create a sequence from a `for` loop: */ - def fromForComprehensionSequencesandArrays(res0: List[Int]) { - val s = for (v ← 1 to 4) yield v + def fromForComprehensionSequencesandArrays(res0: List[Int]) = { + val s = for (v <- 1 to 4) yield v s.toList should be(res0) } /** You can create a sequence from a `for` loop with a filter: */ - def withConditionSequencesandArrays(res0: List[Int]) { - val s = for (v ← 1 to 10 if v % 3 == 0) yield v + def withConditionSequencesandArrays(res0: List[Int]) = { + val s = for (v <- 1 to 10 if v % 3 == 0) yield v s.toList should be(res0) } /** You can filter any sequence based on a predicate: */ - def filterPredicateSequencesandArrays(res0: String, res1: String) { + def filterPredicateSequencesandArrays(res0: String, res1: String) = { val s = Seq("hello", "to", "you") val filtered = s.filter(_.length > 2) filtered should be(Seq(res0, res1)) @@ -63,7 +63,7 @@ object SequencesandArrays /** You can also filter Arrays in the same way: */ - def filterArraySequencesandArrays(res0: String, res1: String) { + def filterArraySequencesandArrays(res0: String, res1: String) = { val a = Array("hello", "to", "you", "again") val filtered = a.filter(_.length > 3) filtered should be(Array(res0, res1)) @@ -71,7 +71,7 @@ object SequencesandArrays /** You can map values in a sequence through a function: */ - def mapValuesSequencesandArrays(res0: Seq[String]) { + def mapValuesSequencesandArrays(res0: Seq[String]) = { val s = Seq("hello", "world") val r = s map { _.reverse diff --git a/src/main/scala/stdlib/Sets.scala b/src/main/scala/stdlib/Sets.scala index 1eafbe31..172b5d35 100644 --- a/src/main/scala/stdlib/Sets.scala +++ b/src/main/scala/stdlib/Sets.scala @@ -23,21 +23,21 @@ object Sets extends AnyFlatSpec with Matchers with org.scalaexercises.definition * * Sets can be created easily: */ - def noDuplicatesSets(res0: Int) { + def noDuplicatesSets(res0: Int) = { val mySet = Set("Michigan", "Ohio", "Wisconsin", "Iowa") mySet.size should be(res0) } /** Sets contain distinct values: */ - def distinctValuesSets(res0: Int) { + def distinctValuesSets(res0: Int) = { val mySet = Set("Michigan", "Ohio", "Wisconsin", "Michigan") mySet.size should be(res0) } /** Sets can be added to easily: */ - def easilyAddedSets(res0: Boolean, res1: Boolean) { + def easilyAddedSets(res0: Boolean, res1: Boolean) = { val mySet = Set("Michigan", "Ohio", "Wisconsin", "Iowa") val aNewSet = mySet + "Illinois" @@ -47,7 +47,7 @@ object Sets extends AnyFlatSpec with Matchers with org.scalaexercises.definition /** Sets may be of mixed type: */ - def mixedTypeSets(res0: Boolean, res1: Boolean) { + def mixedTypeSets(res0: Boolean, res1: Boolean) = { val mySet = Set("Michigan", "Ohio", 12) mySet.contains(12) should be(res0) @@ -56,7 +56,7 @@ object Sets extends AnyFlatSpec with Matchers with org.scalaexercises.definition /** Sets can be checked for member existence: */ - def checkExistenceSets(res0: Boolean, res1: Boolean) { + def checkExistenceSets(res0: Boolean, res1: Boolean) = { val mySet = Set("Michigan", "Ohio", 12) mySet(12) should be(res0) @@ -65,7 +65,7 @@ object Sets extends AnyFlatSpec with Matchers with org.scalaexercises.definition /** Set elements can be removed easily: */ - def easilyRemovedSets(res0: Boolean, res1: Boolean) { + def easilyRemovedSets(res0: Boolean, res1: Boolean) = { val mySet = Set("Michigan", "Ohio", "Wisconsin", "Iowa") val aNewSet = mySet - "Michigan" @@ -75,7 +75,7 @@ object Sets extends AnyFlatSpec with Matchers with org.scalaexercises.definition /** Set elements can be removed in multiple: */ - def multipleRemovingSets(res0: Boolean, res1: Boolean, res2: Int) { + def multipleRemovingSets(res0: Boolean, res1: Boolean, res2: Int) = { val mySet = Set("Michigan", "Ohio", "Wisconsin", "Iowa") val aNewSet = mySet -- List("Michigan", "Ohio") @@ -84,20 +84,9 @@ object Sets extends AnyFlatSpec with Matchers with org.scalaexercises.definition aNewSet.size should be(res2) } - /** Set elements can be removed with a tuple: - */ - def tupleRemovingSets(res0: Boolean, res1: Boolean, res2: Int) { - val mySet = Set("Michigan", "Ohio", "Wisconsin", "Iowa") - val aNewSet = mySet - ("Michigan", "Ohio") // Notice: single '-' operator for tuples - - aNewSet.contains("Michigan") should be(res0) - aNewSet.contains("Wisconsin") should be(res1) - aNewSet.size should be(res2) - } - /** Attempted removal of nonexistent elements from a set is handled gracefully: */ - def nonexistentRemovalSets(res0: Boolean) { + def nonexistentRemovalSets(res0: Boolean) = { val mySet = Set("Michigan", "Ohio", "Wisconsin", "Iowa") val aNewSet = mySet - "Minnesota" @@ -106,18 +95,17 @@ object Sets extends AnyFlatSpec with Matchers with org.scalaexercises.definition /** Two sets can be intersected easily: */ - def easilyIntersectedSets(res0: Boolean) { + def easilyIntersectedSets(res0: Boolean) = { val mySet1 = Set("Michigan", "Ohio", "Wisconsin", "Iowa") val mySet2 = Set("Wisconsin", "Michigan", "Minnesota") - val aNewSet = mySet1 intersect mySet2 - // NOTE: Scala 2.7 used **, deprecated for & or intersect in Scala 2.8 + val aNewSet = mySet1 intersect mySet2 // NOTE: You can use the "&" operator aNewSet.equals(Set("Michigan", "Wisconsin")) should be(res0) } /** Two sets can be joined as their union easily: */ - def easilyJoinedSets(res0: Boolean) { + def easilyJoinedSets(res0: Boolean) = { val mySet1 = Set("Michigan", "Ohio", "Wisconsin", "Iowa") val mySet2 = Set("Wisconsin", "Michigan", "Minnesota") val aNewSet = mySet1 union mySet2 // NOTE: You can also use the "|" operator @@ -127,7 +115,7 @@ object Sets extends AnyFlatSpec with Matchers with org.scalaexercises.definition /** A set is either a subset of another set or it isn't: */ - def subsetSets(res0: Boolean, res1: Boolean) { + def subsetSets(res0: Boolean, res1: Boolean) = { val mySet1 = Set("Michigan", "Ohio", "Wisconsin", "Iowa") val mySet2 = Set("Wisconsin", "Michigan", "Minnesota") val mySet3 = Set("Wisconsin", "Michigan") @@ -138,7 +126,7 @@ object Sets extends AnyFlatSpec with Matchers with org.scalaexercises.definition /** The difference between two sets can be obtained easily: */ - def easilyObtainedDifferencesSets(res0: Boolean) { + def easilyObtainedDifferencesSets(res0: Boolean) = { val mySet1 = Set("Michigan", "Ohio", "Wisconsin", "Iowa") val mySet2 = Set("Wisconsin", "Michigan") val aNewSet = mySet1 diff mySet2 // Note: you can use the "&~" operator if you *really* want to. @@ -148,7 +136,7 @@ object Sets extends AnyFlatSpec with Matchers with org.scalaexercises.definition /** Set equivalency is independent of order: */ - def equivalencySets(res0: Boolean) { + def equivalencySets(res0: Boolean) = { val mySet1 = Set("Michigan", "Ohio", "Wisconsin", "Iowa") val mySet2 = Set("Wisconsin", "Michigan", "Ohio", "Iowa") diff --git a/src/main/scala/stdlib/Traits.scala b/src/main/scala/stdlib/Traits.scala index 9c7471af..1645c59b 100644 --- a/src/main/scala/stdlib/Traits.scala +++ b/src/main/scala/stdlib/Traits.scala @@ -28,7 +28,7 @@ object Traits extends AnyFlatSpec with Matchers with org.scalaexercises.definiti * * A class uses the `extends` keyword to mixin a trait if it is the only relationship the class inherits: */ - def similarToInterfacesTraits(res0: String) { + def similarToInterfacesTraits(res0: String) = { case class Event(name: String) trait EventListener { @@ -38,9 +38,9 @@ object Traits extends AnyFlatSpec with Matchers with org.scalaexercises.definiti class MyListener extends EventListener { def listen(event: Event): String = { event match { - case Event("Moose Stampede") ⇒ + case Event("Moose Stampede") => "An unfortunate moose stampede occurred" - case _ ⇒ "Nothing of importance occurred" + case _ => "Nothing of importance occurred" } } } @@ -52,7 +52,7 @@ object Traits extends AnyFlatSpec with Matchers with org.scalaexercises.definiti /** A class can only extend from one class or trait, any subsequent extension should use the keyword `with`: */ - def extendsFromOneTraits(res0: String) { + def extendsFromOneTraits(res0: String) = { case class Event(name: String) trait EventListener { @@ -64,9 +64,9 @@ object Traits extends AnyFlatSpec with Matchers with org.scalaexercises.definiti class MyListener extends OurListener with EventListener { def listen(event: Event): String = { event match { - case Event("Woodchuck Stampede") ⇒ + case Event("Woodchuck Stampede") => "An unfortunate woodchuck stampede occurred" - case _ ⇒ "Nothing of importance occurred" + case _ => "Nothing of importance occurred" } } } @@ -78,7 +78,7 @@ object Traits extends AnyFlatSpec with Matchers with org.scalaexercises.definiti /** Traits are polymorphic. Any type can be referred to by another type if related by extension: */ - def polymorphicTraits(res0: Boolean, res1: Boolean, res2: Boolean, res3: Boolean) { + def polymorphicTraits(res0: Boolean, res1: Boolean, res2: Boolean, res3: Boolean) = { case class Event(name: String) trait EventListener { @@ -88,9 +88,9 @@ object Traits extends AnyFlatSpec with Matchers with org.scalaexercises.definiti class MyListener extends EventListener { def listen(event: Event): String = { event match { - case Event("Moose Stampede") ⇒ + case Event("Moose Stampede") => "An unfortunate moose stampede occurred" - case _ ⇒ "Nothing of importance occurred" + case _ => "Nothing of importance occurred" } } } @@ -107,7 +107,7 @@ object Traits extends AnyFlatSpec with Matchers with org.scalaexercises.definiti * * Also, the dependencies can't have identical method/property names or else you'll get an `illegal inheritance` error. */ - def selfTypeTraits(res0: Int) { + def selfTypeTraits(res0: Int) = { trait B { def bId = 2 } diff --git a/src/main/scala/stdlib/Traversables.scala b/src/main/scala/stdlib/Traversables.scala index 8e228855..f55b6358 100644 --- a/src/main/scala/stdlib/Traversables.scala +++ b/src/main/scala/stdlib/Traversables.scala @@ -10,7 +10,7 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import scala.language.postfixOps -import Stream.cons +import LazyList.cons /** @param name traversables */ @@ -29,7 +29,7 @@ object Traversables extends AnyFlatSpec with Matchers with org.scalaexercises.de * Traversables are the superclass of `List`, `Array`, `Map`, `Set`, `Stream` and more. The methods involved can be applied to each other in a different type. `++` appends two `Traversable`s together. The resulting `Traversable` is the same type of the first element. */ - def topOfCollectionTraversables(res0: Int, res1: Int) { + def topOfCollectionTraversables(res0: Int, res1: Int) = { val set = Set(1, 9, 10, 22) val list = List(3, 4, 5, 10) val result = set ++ list @@ -41,7 +41,7 @@ object Traversables extends AnyFlatSpec with Matchers with org.scalaexercises.de /** `map` will apply the given function on all elements of a `Traversable` and return a new collection of the result: */ - def mapFunctionTraversables(res0: Option[Int]) { + def mapFunctionTraversables(res0: Option[Int]) = { val set = Set(1, 3, 4, 6) val result = set.map(_ * 4) result.lastOption should be(res0) @@ -49,14 +49,14 @@ object Traversables extends AnyFlatSpec with Matchers with org.scalaexercises.de /** `flatten` will "pack" all child `Traversables` into a single `Traversable`: */ - def flattenFunctionTraversables(res0: List[Int]) { + def flattenFunctionTraversables(res0: List[Int]) = { val list = List(List(1), List(2, 3, 4), List(5, 6, 7), List(8, 9, 10)) list.flatten should be(res0) } /** `flatMap` will not only apply the given function on all elements of a `Traversable`, but all elements within the elements and `flatten` the results: */ - def flatMapFunctionTraversables(res0: List[Int]) { + def flatMapFunctionTraversables(res0: List[Int]) = { val list = List(List(1), List(2, 3, 4), List(5, 6, 7), List(8, 9, 10)) val result = list.flatMap(_.map(_ * 4)) result should be(res0) @@ -64,31 +64,31 @@ object Traversables extends AnyFlatSpec with Matchers with org.scalaexercises.de /** `flatMap` of `Options` will filter out all `None`s but keep the `Some`s: */ - def flatMapOfOptionsTraversables(res0: List[Int]) { + def flatMapOfOptionsTraversables(res0: List[Int]) = { val list = List(1, 2, 3, 4, 5) - val result = list.flatMap(it ⇒ if (it % 2 == 0) Some(it) else None) + val result = list.flatMap(it => if (it % 2 == 0) Some(it) else None) result should be(res0) } /** `collect` will apply a partial function to all elements of a `Traversable` and return a different collection. In this exercise, a case fragment is a partial function: */ - def collectFunctionTraversables(res0: List[Int]) { + def collectFunctionTraversables(res0: List[Int]) = { val list = List(4, 6, 7, 8, 9, 13, 14) val result = list.collect { - case x: Int if (x % 2 == 0) ⇒ x * 3 + case x: Int if (x % 2 == 0) => x * 3 } result should be(res0) } /** Two case fragments can be chained to create a more robust result: */ - def collectFunctionIITraversables(res0: List[Int]) { + def collectFunctionIITraversables(res0: List[Int]) = { val list = List(4, 6, 7, 8, 9, 13, 14) val partialFunction1: PartialFunction[Int, Int] = { - case x: Int if x % 2 == 0 ⇒ x * 3 + case x: Int if x % 2 == 0 => x * 3 } val partialFunction2: PartialFunction[Int, Int] = { - case y: Int if y % 2 != 0 ⇒ y * 4 + case y: Int if y % 2 != 0 => y * 4 } val result = list.collect(partialFunction1 orElse partialFunction2) result should be(res0) @@ -96,15 +96,15 @@ object Traversables extends AnyFlatSpec with Matchers with org.scalaexercises.de /** `foreach` will apply a function to all elements of a `Traversable`, but unlike the `map` function, it will not return anything since the return type is `Unit` - an equivalent to a `void` return type in Java/C++: */ - def foreachFunctionTraversables(res0: List[Int]) { + def foreachFunctionTraversables(res0: List[Int]) = { val list = List(4, 6, 7, 8, 9, 13, 14) - list.foreach(num ⇒ println(num * 4)) + list.foreach(num => println(num * 4)) list should be(res0) } /** `toArray` will convert any `Traversable` to an `Array`, which is a special wrapper around a primitive Java array: */ - def toArrayFunctionTraversables(res0: Boolean) { + def toArrayFunctionTraversables(res0: Boolean) = { val set = Set(4, 6, 7, 8, 9, 13, 14) val result = set.toArray result.isInstanceOf[Array[Int]] should be(res0) @@ -112,7 +112,7 @@ object Traversables extends AnyFlatSpec with Matchers with org.scalaexercises.de /** `toList` will convert any `Traversable` to a `List`. */ - def toListFunctionTraversables(res0: Boolean) { + def toListFunctionTraversables(res0: Boolean) = { val set = Set(4, 6, 7, 8, 9, 13, 14) val result = set.toList @@ -121,7 +121,7 @@ object Traversables extends AnyFlatSpec with Matchers with org.scalaexercises.de /** `toList`, as well as other conversion methods such as `toSet` and `toArray`, will not convert if the collection type is the same: */ - def toListFunctionIITraversables(res0: Boolean) { + def toListFunctionIITraversables(res0: Boolean) = { val list = List(5, 6, 7, 8, 9) val result = list.toList result eq list should be(res0) @@ -129,7 +129,7 @@ object Traversables extends AnyFlatSpec with Matchers with org.scalaexercises.de /** `toIterable` will convert any `Traversable` to an `Iterable`. This is a base `trait` for all Scala collections that define an iterator method to iterate through the collection's elements: */ - def toIterableFunctionTraversables(res0: Boolean) { + def toIterableFunctionTraversables(res0: Boolean) = { val set = Set(4, 6, 7, 8, 9, 13, 14) val result = set.toIterable result.isInstanceOf[Iterable[_]] should be(res0) @@ -137,7 +137,7 @@ object Traversables extends AnyFlatSpec with Matchers with org.scalaexercises.de /** `toSeq` will convert any `Traversable` to a `Seq` which is an ordered `Iterable` and the superclass to `List`, `Queue`, and `Vector`. `Sequences` provide a method apply for indexing. Indices range from 0 up to the length of a sequence: */ - def toSeqFunctionTraversables(res0: Boolean) { + def toSeqFunctionTraversables(res0: Boolean) = { val set = Set(4, 6, 7, 8, 9, 13, 14) val result = set.toSeq result.isInstanceOf[Seq[_]] should be(res0) @@ -145,24 +145,24 @@ object Traversables extends AnyFlatSpec with Matchers with org.scalaexercises.de /** `toIndexedSeq` will convert any `Traversable` to an `IndexedSeq` which is an indexed sequence used in `Vectors` and `Strings`: */ - def toIndexedSeqFunctionTraversables(res0: Boolean) { + def toIndexedSeqFunctionTraversables(res0: Boolean) = { val set = Set(4, 6, 7, 8, 9, 13, 14) val result = set.toIndexedSeq result.isInstanceOf[IndexedSeq[_]] should be(res0) } - /** `toStream` will convert any `Traversable` to a `Stream` which is a lazy list where elements are evaluated as they are needed: + /** `toStream` will convert any `Traversable` to a `LazyList` where elements are evaluated as they are needed: */ - def toStreamFunctionTraversables(res0: Boolean, res1: Stream[Int]) { + def toLazyListFunctionTraversables(res0: Boolean, res1: LazyList[Int]) = { val list = List(4, 6, 7, 8, 9, 13, 14) - val result = list.toStream - result.isInstanceOf[Stream[_]] should be(res0) + val result = list.to(LazyList) + result.isInstanceOf[LazyList[_]] should be(res0) (result take 3) should be(res1) } /** `toSet` will convert any `Traversable` to a `Set` which is a collection of unordered, unique values: */ - def toSetFunctionTraversables(res0: Boolean) { + def toSetFunctionTraversables(res0: Boolean) = { val list = List(4, 6, 7, 8, 9, 13, 14) val result = list.toSet result.isInstanceOf[Set[_]] should be(res0) @@ -170,24 +170,24 @@ object Traversables extends AnyFlatSpec with Matchers with org.scalaexercises.de /** `toMap` will convert any `Traversable` to a `Map`. How it's used depends on the original collection; if it's a `List` or `Seq`, it should be of parameterized type `Tuple2`: */ - def toMapFunctionTraversables(res0: Boolean) { - val list = List("Phoenix" → "Arizona", "Austin" → "Texas") + def toMapFunctionTraversables(res0: Boolean) = { + val list = List("Phoenix" -> "Arizona", "Austin" -> "Texas") val result = list.toMap result.isInstanceOf[Map[_, _]] should be(res0) } /** `toMap` will also convert a `Set` to a `Map`; it should be of parameterized type `Tuple2`: */ - def toMapFunctionIITraversables(res0: Boolean) { - val set = Set("Phoenix" → "Arizona", "Austin" → "Texas") + def toMapFunctionIITraversables(res0: Boolean) = { + val set = Set("Phoenix" -> "Arizona", "Austin" -> "Texas") val result = set.toMap result.isInstanceOf[Map[_, _]] should be(res0) } /** `isEmpty` is pretty self-evident: */ - def isEmptyFunctionTraversables(res0: Boolean, res1: Boolean) { - val map = Map("Phoenix" → "Arizona", "Austin" → "Texas") + def isEmptyFunctionTraversables(res0: Boolean, res1: Boolean) = { + val map = Map("Phoenix" -> "Arizona", "Austin" -> "Texas") map.isEmpty should be(res0) val set = Set() @@ -196,8 +196,8 @@ object Traversables extends AnyFlatSpec with Matchers with org.scalaexercises.de /** `nonEmpty` is pretty self-evident too: */ - def nonEmptyFunctionTraversables(res0: Boolean, res1: Boolean) { - val map = Map("Phoenix" → "Arizona", "Austin" → "Texas") + def nonEmptyFunctionTraversables(res0: Boolean, res1: Boolean) = { + val map = Map("Phoenix" -> "Arizona", "Austin" -> "Texas") map.nonEmpty should be(res0) val set = Set() @@ -206,31 +206,31 @@ object Traversables extends AnyFlatSpec with Matchers with org.scalaexercises.de /** `size` provides the size of the traversable: */ - def sizeFunctionTraversables(res0: Int) { - val map = Map("Phoenix" → "Arizona", "Austin" → "Texas") + def sizeFunctionTraversables(res0: Int) = { + val map = Map("Phoenix" -> "Arizona", "Austin" -> "Texas") map.size should be(res0) } - /** `hasDefiniteSize` will return `true` if the traversable has a finite end, otherwise `false`: + /** `knownSize` will return the number of elements if the traversable has a finite end, otherwise `-1`: */ - def hasDefiniteSizeFunctionTraversables(res0: Boolean, res1: Boolean) { - val map = Map("Phoenix" → "Arizona", "Austin" → "Texas") - map.hasDefiniteSize should be(res0) + def knownSizeFunctionTraversables(res0: Int, res1: Int) = { + val map = Map("Phoenix" -> "Arizona", "Austin" -> "Texas") + map.knownSize should be(res0) - val stream = cons(0, cons(1, Stream.empty)) - stream.hasDefiniteSize should be(res1) + val stream = cons(0, cons(1, LazyList.empty)) + stream.knownSize should be(res1) } /** `head` will return the first element of an ordered collection, or some random element if order is not defined like in a `Set` or `Map`: */ - def headFunctionTraversables(res0: Int) { + def headFunctionTraversables(res0: Int) = { val list = List(10, 19, 45, 1, 22) list.head should be(res0) } /** `headOption` will return the first element as an `Option` of an ordered collection, or some random element if order is not defined. If a first element is not available, then `None` is returned: */ - def headOptionFunctionTraversables(res0: Option[Int], res1: Option[Int]) { + def headOptionFunctionTraversables(res0: Option[Int], res1: Option[Int]) = { val list = List(10, 19, 45, 1, 22) list.headOption should be(res0) @@ -240,14 +240,14 @@ object Traversables extends AnyFlatSpec with Matchers with org.scalaexercises.de /** `last` will return the last element of an ordered collection, or some random element if order is not defined: */ - def lastFunctionTraversables(res0: Int) { + def lastFunctionTraversables(res0: Int) = { val list = List(10, 19, 45, 1, 22) list.last should be(res0) } /** `lastOption` will return the last element as an `Option` of an ordered collection, or some random element if order is not defined. If a last element is not available, then `None` is returned: */ - def lastOptionFunctionTraversables(res0: Option[Int], res1: Option[Int]) { + def lastOptionFunctionTraversables(res0: Option[Int], res1: Option[Int]) = { val list = List(10, 19, 45, 1, 22) list.lastOption should be(res0) @@ -257,7 +257,7 @@ object Traversables extends AnyFlatSpec with Matchers with org.scalaexercises.de /** `find` will locate the first item that matches the predicate `p` as `Some`, or `None` if an element is not found: */ - def findFunctionTraversables(res0: Option[Int], res1: Option[Int]) { + def findFunctionTraversables(res0: Option[Int], res1: Option[Int]) = { val list = List(10, 19, 45, 1, 22) list.find(_ % 2 != 0) should be(res0) @@ -267,79 +267,79 @@ object Traversables extends AnyFlatSpec with Matchers with org.scalaexercises.de /** `tail` will return the rest of the collection without the head: */ - def tailFunctionTraversables(res0: List[Int]) { + def tailFunctionTraversables(res0: List[Int]) = { val list = List(10, 19, 45, 1, 22) list.tail should be(res0) } /** `init` will return the rest of the collection without the last: */ - def initFunctionTraversables(res0: List[Int]) { + def initFunctionTraversables(res0: List[Int]) = { val list = List(10, 19, 45, 1, 22) list.init should be(res0) } /** Given a `from` index, and a `to` index, `slice` will return the part of the collection including `from`, and excluding `to`: */ - def sliceFunctionTraversables(res0: List[Int]) { + def sliceFunctionTraversables(res0: List[Int]) = { val list = List(10, 19, 45, 1, 22) list.slice(1, 3) should be(res0) } /** `take` will return the first number of elements given: */ - def takeFunctionTraversables(res0: List[Int]) { + def takeFunctionTraversables(res0: List[Int]) = { val list = List(10, 19, 45, 1, 22) list.take(3) should be(res0) } - /** `take` is used often with `Streams`, since they are also `Traversable`: + /** `take` is used often with `LazyList`, since they are also `Traversable`: */ - def takeFunctionIITraversables(res0: List[Int]) { - def streamer(v: Int): Stream[Int] = cons(v, streamer(v + 1)) - val a = streamer(2) + def takeFunctionIITraversables(res0: List[Int]) = { + def makeLazyList(v: Int): LazyList[Int] = cons(v, makeLazyList(v + 1)) + val a = makeLazyList(2) (a take 3 toList) should be(res0) } /** `drop` will take the rest of the `Traversable` except the number of elements given: */ - def dropFunctionTraversables(res0: List[Int]) { - def streamer(v: Int): Stream[Int] = cons(v, streamer(v + 1)) - val a = streamer(2) + def dropFunctionTraversables(res0: List[Int]) = { + def makeLazyList(v: Int): LazyList[Int] = cons(v, makeLazyList(v + 1)) + val a = makeLazyList(2) ((a drop 6) take 3).toList should be(res0) } /** `takeWhile` will continually accumulate elements until a predicate is no longer satisfied: */ - def takeWhileFunctionTraversables(res0: List[Int]) { + def takeWhileFunctionTraversables(res0: List[Int]) = { val list = List(87, 44, 5, 4, 200, 10, 39, 100) list.takeWhile(_ < 100) should be(res0) } /** `dropWhile` will continually drop elements until a predicate is no longer satisfied: */ - def dropWhileFunctionTraversables(res0: List[Int]) { + def dropWhileFunctionTraversables(res0: List[Int]) = { val list = List(87, 44, 5, 4, 200, 10, 39, 100) list.dropWhile(_ < 100) should be(res0) } /** `filter` will take out all elements that don't satisfy a predicate. (An `Array` is also `Traversable`.) */ - def filterFunctionTraversables(res0: Array[Int]) { + def filterFunctionTraversables(res0: Array[Int]) = { val array = Array(87, 44, 5, 4, 200, 10, 39, 100) array.filter(_ < 100) should be(res0) } /** `filterNot` will take out all elements that satisfy a predicate: */ - def filterNotFunctionTraversables(res0: Array[Int]) { + def filterNotFunctionTraversables(res0: Array[Int]) = { val array = Array(87, 44, 5, 4, 200, 10, 39, 100) array.filterNot(_ < 100) should be(res0) } /** `splitAt` will split a `Traversable` at a position, returning a 2 product `Tuple`. `splitAt` is also defined as `(xs take n, xs drop n)` */ - def splitAtFunctionTraversables(res0: Array[Int], res1: Array[Int]) { + def splitAtFunctionTraversables(res0: Array[Int], res1: Array[Int]) = { val array = Array(87, 44, 5, 4, 200, 10, 39, 100) val result = array splitAt 3 result._1 should be(res0) @@ -348,7 +348,7 @@ object Traversables extends AnyFlatSpec with Matchers with org.scalaexercises.de /** `span` will split a `Traversable` according to a predicate, returning a 2 product `Tuple`. `span` is also defined as `(xs takeWhile p, xs dropWhile p)` */ - def spanFunctionTraversables(res0: Array[Int], res1: Array[Int]) { + def spanFunctionTraversables(res0: Array[Int], res1: Array[Int]) = { val array = Array(87, 44, 5, 4, 200, 10, 39, 100) val result = array span (_ < 100) result._1 should be(res0) @@ -357,7 +357,7 @@ object Traversables extends AnyFlatSpec with Matchers with org.scalaexercises.de /** `partition` will split a `Traversable` according to a predicate, returning a 2 product `Tuple`. The left-hand side contains the elements satisfied by the predicate whereas the right hand side contains the rest of the elements. `partition` is also defined as `(xs filter p, xs filterNot p)` */ - def partitionFunctionTraversables(res0: Array[Int], res1: Array[Int]) { + def partitionFunctionTraversables(res0: Array[Int], res1: Array[Int]) = { val array = Array(87, 44, 5, 4, 200, 10, 39, 100) val result = array partition (_ < 100) result._1 should be(res0) @@ -366,27 +366,27 @@ object Traversables extends AnyFlatSpec with Matchers with org.scalaexercises.de /** `groupBy` will categorize a `Traversable` according to a given function and return a map with the results. This exercise uses partial function chaining: */ - def groupByFunctionTraversables(res0: Int, res1: Int) { + def groupByFunctionTraversables(res0: Int, res1: Int) = { val array = Array(87, 44, 5, 4, 200, 10, 39, 100) val oddAndSmallPartial: PartialFunction[Int, String] = { - case x: Int if x % 2 != 0 && x < 100 ⇒ "Odd and less than 100" + case x: Int if x % 2 != 0 && x < 100 => "Odd and less than 100" } val evenAndSmallPartial: PartialFunction[Int, String] = { - case x: Int if x != 0 && x % 2 == 0 && x < 100 ⇒ "Even and less than 100" + case x: Int if x != 0 && x % 2 == 0 && x < 100 => "Even and less than 100" } val negativePartial: PartialFunction[Int, String] = { - case x: Int if x < 0 ⇒ "Negative Number" + case x: Int if x < 0 => "Negative Number" } val largePartial: PartialFunction[Int, String] = { - case x: Int if x > 99 ⇒ "Large Number" + case x: Int if x > 99 => "Large Number" } val zeroPartial: PartialFunction[Int, String] = { - case x: Int if x == 0 ⇒ "Zero" + case x: Int if x == 0 => "Zero" } val result = array groupBy { @@ -403,7 +403,7 @@ object Traversables extends AnyFlatSpec with Matchers with org.scalaexercises.de /** `forall` will determine if a predicate is valid for all members of a `Traversable`: */ - def forallFunctionTraversables(res0: Boolean) { + def forallFunctionTraversables(res0: Boolean) = { val list = List(87, 44, 5, 4, 200, 10, 39, 100) val result = list forall (_ < 100) result should be(res0) @@ -411,7 +411,7 @@ object Traversables extends AnyFlatSpec with Matchers with org.scalaexercises.de /** `exists` will determine if a predicate is valid for some members of a `Traversable`: */ - def existsFunctionTraversables(res0: Boolean) { + def existsFunctionTraversables(res0: Boolean) = { val list = List(87, 44, 5, 4, 200, 10, 39, 100) val result = list exists (_ < 100) result should be(res0) @@ -419,7 +419,7 @@ object Traversables extends AnyFlatSpec with Matchers with org.scalaexercises.de /** `count` will count the number of elements that satisfy a predicate in a `Traversable`: */ - def countFunctionTraversables(res0: Int) { + def countFunctionTraversables(res0: Int) = { val list = List(87, 44, 5, 4, 200, 10, 39, 100) val result = list count (_ < 100) result should be(res0) @@ -429,9 +429,9 @@ object Traversables extends AnyFlatSpec with Matchers with org.scalaexercises.de * * Given a `Traversable (x1, x2, x3, x4)`, an initial value of `init`, an operation `op`, `foldLeft` is defined as: `(((init op x1) op x2) op x3) op x4)` */ - def foldLeftFunctionTraversables(res0: Int, res1: Int, res2: Int) { + def foldLeftFunctionTraversables(res0: Int, res1: Int, res2: Int) = { val list = List(5, 4, 3, 2, 1) - val result = list.foldLeft(0) { (`running total`, `next element`) ⇒ + val result = list.foldLeft(0) { (`running total`, `next element`) => `running total` - `next element` } result should be(res0) @@ -446,9 +446,9 @@ object Traversables extends AnyFlatSpec with Matchers with org.scalaexercises.de * * Given a `Traversable (x1, x2, x3, x4)`, an initial value of `init`, an operation `op`, `foldRight` is defined as: `x1 op (x2 op (x3 op (x4 op init)))` */ - def foldRightFunctionTraversables(res0: Int, res1: Int, res2: Int) { + def foldRightFunctionTraversables(res0: Int, res1: Int, res2: Int) = { val list = List(5, 4, 3, 2, 1) - val result = list.foldRight(0) { (`next element`, `running total`) ⇒ + val result = list.foldRight(0) { (`next element`, `running total`) => `next element` - `running total` } result should be(res0) @@ -461,7 +461,7 @@ object Traversables extends AnyFlatSpec with Matchers with org.scalaexercises.de /** `reduceLeft` is similar to `foldLeft`, except that the seed is the head value: */ - def reduceLeftFunctionTraversables(res0: Int, res1: String) { + def reduceLeftFunctionTraversables(res0: Int, res1: String) = { val intList = List(5, 4, 3, 2, 1) intList.reduceLeft { _ + _ @@ -475,7 +475,7 @@ object Traversables extends AnyFlatSpec with Matchers with org.scalaexercises.de /** `reduceRight` is similar to `foldRight`, except that the seed is the last value: */ - def reduceRightFunctionTraversables(res0: Int, res1: String) { + def reduceRightFunctionTraversables(res0: Int, res1: String) = { val intList = List(5, 4, 3, 2, 1) intList.reduceRight { _ + _ @@ -489,7 +489,7 @@ object Traversables extends AnyFlatSpec with Matchers with org.scalaexercises.de /** There are some methods that take much of the folding work out by providing basic functionality. `sum` will add all the elements, `product` will multiply, `min` would determine the smallest element, and `max` the largest: */ - def sumFunctionTraversables(res0: Int, res1: Int, res2: Int, res3: Int) { + def sumFunctionTraversables(res0: Int, res1: Int, res2: Int, res3: Int) = { val intList = List(5, 4, 3, 2, 1) intList.sum should be(res0) intList.product should be(res1) @@ -505,7 +505,7 @@ object Traversables extends AnyFlatSpec with Matchers with org.scalaexercises.de * * There is also a `reduce` (and `fold`) available, which works exactly like `reduceLeft` (and `foldLeft`) and it should be the prefered method to call unless there is a strong reason to use `reduceRight` (or `foldRight`). */ - def reduceRightAsReduceLeft(res0: Int, res1: Int, res2: Int) { + def reduceRightAsReduceLeft(res0: Int, res1: Int, res2: Int) = { val intList = List(5, 4, 3, 2, 1) intList.reduceRight((x, y) => x - y) should be(res0) intList.reverse.reduceLeft((x, y) => y - x) should be(res1) @@ -520,7 +520,7 @@ object Traversables extends AnyFlatSpec with Matchers with org.scalaexercises.de res0: List[Int], res1: List[Int], res2: List[Int], - res3: List[Int]) { + res3: List[Int]) = { val list = List(List(1, 2, 3), List(4, 5, 6), List(7, 8, 9)) list.transpose should be(List(res0, res1, res2)) @@ -530,25 +530,25 @@ object Traversables extends AnyFlatSpec with Matchers with org.scalaexercises.de /** `mkString` will format a `Traversable` using a given string as the delimiter: */ - def mkStringFunctionTraversables(res0: String) { + def mkStringFunctionTraversables(res0: String) = { val list = List(1, 2, 3, 4, 5) list.mkString(",") should be(res0) } /** `mkString` will also take a beginning and ending string to surround the list.: */ - def mkStringFunctionIITraversables(res0: String) { + def mkStringFunctionIITraversables(res0: String) = { val list = List(1, 2, 3, 4, 5) list.mkString(">", ",", "<") should be(res0) } /** `addString` will take a StringBuilder to add the contents of list into the builder. */ - def addStringFunctionTraversables(res0: String) { + def addStringFunctionTraversables(res0: String) = { val stringBuilder = new StringBuilder() val list = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15) stringBuilder.append("I want all numbers 6-12: ") - list.filter(it ⇒ it > 5 && it < 13).addString(stringBuilder, ",") + list.filter(it => it > 5 && it < 13).addString(stringBuilder, ",") stringBuilder.mkString should be(res0) } diff --git a/src/main/scala/stdlib/Tuples.scala b/src/main/scala/stdlib/Tuples.scala index 2bb1bcf1..76e08750 100644 --- a/src/main/scala/stdlib/Tuples.scala +++ b/src/main/scala/stdlib/Tuples.scala @@ -29,7 +29,7 @@ object Tuples extends AnyFlatSpec with Matchers with org.scalaexercises.definiti * }}} * As you can see, tuples can be created easily: */ - def oneIndexedTuples(res0: String, res1: String) { + def oneIndexedTuples(res0: String, res1: String) = { val tuple = ("apple", "dog") val fruit = tuple._1 val animal = tuple._2 @@ -40,7 +40,7 @@ object Tuples extends AnyFlatSpec with Matchers with org.scalaexercises.definiti /** Tuples may be of mixed type: */ - def mixedTypeTuples(res0: Int, res1: String) { + def mixedTypeTuples(res0: Int, res1: String) = { val tuple5 = ("a", 1, 2.2, new Date(), "five") tuple5._2 should be(res0) @@ -49,7 +49,7 @@ object Tuples extends AnyFlatSpec with Matchers with org.scalaexercises.definiti /** You can assign multiple variables at once using tuples: */ - def assignVariablesTuples(res0: String, res1: Int, res2: Double) { + def assignVariablesTuples(res0: String, res1: Int, res2: Double) = { val student = ("Sean Rogers", 21, 3.5) val (name, age, gpa) = student @@ -60,7 +60,7 @@ object Tuples extends AnyFlatSpec with Matchers with org.scalaexercises.definiti /** The `swap` method can be used to swap the elements of a Tuple2: */ - def swappedTuples(res0: Int, res1: String) { + def swappedTuples(res0: Int, res1: String) = { val tuple = ("apple", 3).swap tuple._1 should be(res0) tuple._2 should be(res1) diff --git a/src/main/scala/stdlib/TypeSignatures.scala b/src/main/scala/stdlib/TypeSignatures.scala index da0b3e3f..ca9c5bfb 100644 --- a/src/main/scala/stdlib/TypeSignatures.scala +++ b/src/main/scala/stdlib/TypeSignatures.scala @@ -33,7 +33,7 @@ object TypeSignatures * A trait can be declared containing a type, where a concrete implementer will satisfy the type: * */ - def typeSignatureTypeSignatures(res0: Boolean) { + def typeSignatureTypeSignatures(res0: Boolean) = { trait Randomizer[A] { def draw(): A } @@ -51,14 +51,14 @@ object TypeSignatures /** Class meta-information can be retrieved by class name by using `classOf[className]`: */ - def retrieveMetaInformationTypeSignatures(res0: String, res1: String) { + def retrieveMetaInformationTypeSignatures(res0: String, res1: String) = { classOf[String].getCanonicalName should be(res0) classOf[String].getSimpleName should be(res1) } /** Class meta-information can be derived from an object reference using `getClass()`: */ - def deriveMetaInformationTypeSignatures(res0: Boolean, res1: String, res2: String) { + def deriveMetaInformationTypeSignatures(res0: Boolean, res1: String, res2: String) = { val zoom = "zoom" zoom.isInstanceOf[String] should be(res0) zoom.getClass.getCanonicalName should be(res1) @@ -67,7 +67,7 @@ object TypeSignatures /** `isInstanceOf[className]` is used to determine if an object reference is an instance of a given class: */ - def isInstanceOfFunctionTypeSignatures(res0: Boolean, res1: Boolean, res2: Boolean) { + def isInstanceOfFunctionTypeSignatures(res0: Boolean, res1: Boolean, res2: Boolean) = { trait Randomizer[A] { def draw(): A } diff --git a/src/main/scala/stdlib/TypeVariance.scala b/src/main/scala/stdlib/TypeVariance.scala index 58485cf7..71772958 100644 --- a/src/main/scala/stdlib/TypeVariance.scala +++ b/src/main/scala/stdlib/TypeVariance.scala @@ -22,7 +22,7 @@ object TypeVariance extends AnyFlatSpec with Matchers with org.scalaexercises.de * * Using type inference the type that you instantiate will be the val or var reference type: */ - def syntacticOverheadTypeVariance(res0: String) { + def syntacticOverheadTypeVariance(res0: String) = { class MyContainer[A](val a: A)(implicit manifest: scala.reflect.Manifest[A]) { def contents = manifest.runtimeClass.getSimpleName } @@ -33,7 +33,7 @@ object TypeVariance extends AnyFlatSpec with Matchers with org.scalaexercises.de /** You can explicitly declare the type variable of the object during instantiation: */ - def typeVariableTypeVariance(res0: String) { + def typeVariableTypeVariance(res0: String) = { class MyContainer[A](val a: A)(implicit manifest: scala.reflect.Manifest[A]) { def contents = manifest.runtimeClass.getSimpleName } @@ -44,7 +44,7 @@ object TypeVariance extends AnyFlatSpec with Matchers with org.scalaexercises.de /** You can coerce your object to a type: */ - def coerceObjectTypeVariance(res0: String) { + def coerceObjectTypeVariance(res0: String) = { class MyContainer[A](val a: A)(implicit manifest: scala.reflect.Manifest[A]) { def contents = manifest.runtimeClass.getSimpleName } @@ -81,7 +81,7 @@ object TypeVariance extends AnyFlatSpec with Matchers with org.scalaexercises.de * * So, how do we get to set a Fruit basket to an Orange basket? You make it covariant using `+`. This will allow you to set the container to either a variable with the same type or parent type. In other words, you can assign `MyContainer[Fruit]` or `MyContainer[Citrus]`. */ - def polymorphismTypeVariance(res0: String) { + def polymorphismTypeVariance(res0: String) = { class MyContainer[+A](val a: A)(implicit manifest: scala.reflect.Manifest[A]) { def contents = manifest.runtimeClass.getSimpleName } @@ -92,7 +92,7 @@ object TypeVariance extends AnyFlatSpec with Matchers with org.scalaexercises.de /** The problem with covariance is that you can't mutate, set or change the object since it has to guarantee that what you put into it is a valid type. In other words the reference is a fruit basket, but we still have to make sure that no other fruit can be placed in our orange basket: */ - def covarianceInmutableTypeVariance(res0: String) { + def covarianceInmutableTypeVariance(res0: String) = { class MyContainer[+A](val a: A)(implicit manifest: scala.reflect.Manifest[A]) { def contents = manifest.runtimeClass.getSimpleName } @@ -107,7 +107,7 @@ object TypeVariance extends AnyFlatSpec with Matchers with org.scalaexercises.de /** Declaring `-` indicates contravariance variance. Using `-` you can apply any container with a certain type to a container with a superclass of that type. This is reverse to covariant. In our example, we can set a citrus basket to an orange or tangelo basket. Since an orange or tangelo basket are a citrus basket. Contravariance is the opposite of covariance: */ - def contravarianceVarianceTypeVariance(res0: String, res1: String, res2: String, res3: String) { + def contravarianceVarianceTypeVariance(res0: String, res1: String, res2: String, res3: String) = { class MyContainer[-A](a: A)(implicit manifest: scala.reflect.Manifest[A]) { //Can't receive a val because it would be in a covariant position def contents = manifest.runtimeClass.getSimpleName } @@ -131,7 +131,7 @@ object TypeVariance extends AnyFlatSpec with Matchers with org.scalaexercises.de * * Invariance means you need to specify the type exactly: */ - def invarianceVarianceTypeVariance(res0: String) { + def invarianceVarianceTypeVariance(res0: String) = { class MyContainer[A](val a: A)(implicit manifest: scala.reflect.Manifest[A]) { def contents = manifest.runtimeClass.getSimpleName } diff --git a/src/main/scala/stdlib/UniformAccessPrinciple.scala b/src/main/scala/stdlib/UniformAccessPrinciple.scala index ccbaa3d6..12208022 100644 --- a/src/main/scala/stdlib/UniformAccessPrinciple.scala +++ b/src/main/scala/stdlib/UniformAccessPrinciple.scala @@ -22,7 +22,7 @@ object UniformAccessPrinciple * This principle states that variables and parameterless functions should be accessed using the same syntax. Scala supports this principle by allowing parentheses to not be placed at call sites of parameterless functions. As a result, a parameterless function definition can be changed to a `val`, or vice versa, without affecting client code: * */ - def uniformAccessPrincipleUniformAccessPrinciple(res0: Int, res1: Int) { + def uniformAccessPrincipleUniformAccessPrinciple(res0: Int, res1: Int) = { class Test1(val age: Int = 10) class Test2(_age: Int) { def age: Int = _age diff --git a/src/test/scala/stdlib/MapsSpec.scala b/src/test/scala/stdlib/MapsSpec.scala index 638747fe..c9da7376 100644 --- a/src/test/scala/stdlib/MapsSpec.scala +++ b/src/test/scala/stdlib/MapsSpec.scala @@ -103,15 +103,6 @@ class MapsSpec extends RefSpec with Checkers { ) } - def `key removal with tuples` = { - check( - Test.testSuccess( - Maps.removedWithTupleMaps _, - false :: true :: true :: 2 :: 4 :: HNil - ) - ) - } - def `non-existent element removal` = { check( Test.testSuccess( diff --git a/src/test/scala/stdlib/SetsSpec.scala b/src/test/scala/stdlib/SetsSpec.scala index 08736e7b..e364328c 100644 --- a/src/test/scala/stdlib/SetsSpec.scala +++ b/src/test/scala/stdlib/SetsSpec.scala @@ -76,15 +76,6 @@ class SetsSpec extends RefSpec with Checkers { ) } - def `we can remove multiple members with tuples` = { - check( - Test.testSuccess( - Sets.tupleRemovingSets _, - false :: true :: 2 :: HNil - ) - ) - } - def `we can remove values that are not part of the set` = { check( Test.testSuccess( diff --git a/src/test/scala/stdlib/TraversablesSpec.scala b/src/test/scala/stdlib/TraversablesSpec.scala index 423c5dfb..a5d2f7bd 100644 --- a/src/test/scala/stdlib/TraversablesSpec.scala +++ b/src/test/scala/stdlib/TraversablesSpec.scala @@ -133,8 +133,8 @@ class TraversablesSpec extends RefSpec with Checkers { def `to stream function` = { check( Test.testSuccess( - Traversables.toStreamFunctionTraversables _, - true :: Stream(4, 6, 7) :: HNil + Traversables.toLazyListFunctionTraversables _, + true :: LazyList(4, 6, 7) :: HNil ) ) } @@ -184,11 +184,11 @@ class TraversablesSpec extends RefSpec with Checkers { ) } - def `hasDefiniteSize function` = { + def `knownSize function` = { check( Test.testSuccess( - Traversables.hasDefiniteSizeFunctionTraversables _, - true :: false :: HNil + Traversables.knownSizeFunctionTraversables _, + 2 :: -1 :: HNil ) ) } diff --git a/version.sbt b/version.sbt index 404aa03e..3f478e0c 100644 --- a/version.sbt +++ b/version.sbt @@ -1 +1 @@ -version in ThisBuild := "0.5.0-SNAPSHOT" +version in ThisBuild := "0.6.0-SNAPSHOT" From 219c27ed07722337c6e5acbc7b51f33c815da1d5 Mon Sep 17 00:00:00 2001 From: Enrique Nieto <48894338+kiroco12@users.noreply.github.com> Date: Mon, 3 Feb 2020 10:08:21 +0100 Subject: [PATCH 2/2] Update project/build.properties Co-Authored-By: Juan Pedro Moreno <4879373+juanpedromoreno@users.noreply.github.com> --- project/build.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/project/build.properties b/project/build.properties index eb9d0270..a82bb05e 100644 --- a/project/build.properties +++ b/project/build.properties @@ -1 +1 @@ -sbt.version=1.3.5 \ No newline at end of file +sbt.version=1.3.7