From d5556922a9295e58b053c1573facb97ee832396b Mon Sep 17 00:00:00 2001 From: Juan Pedro Moreno Date: Tue, 28 Mar 2017 16:39:50 +0200 Subject: [PATCH] Integrates sbt-org-policies plugin --- .scalafmt.conf | 23 ++ .travis.yml | 3 - README.md | 7 +- build.sbt | 56 ++--- project/ProjectPlugin.scala | 47 ++++ project/build.properties | 2 +- project/plugins.sbt | 4 +- src/main/scala/stdlib/Asserts.scala | 73 +++--- src/main/scala/stdlib/ByNameParameter.scala | 13 +- src/main/scala/stdlib/CaseClasses.scala | 200 +++++++++------- src/main/scala/stdlib/Classes.scala | 61 ++--- src/main/scala/stdlib/EmptyValues.scala | 75 +++--- src/main/scala/stdlib/Enumerations.scala | 103 +++++--- src/main/scala/stdlib/Extractors.scala | 121 +++++----- src/main/scala/stdlib/ForExpressions.scala | 15 +- src/main/scala/stdlib/Formatting.scala | 19 +- .../scala/stdlib/HigherOrderFunctions.scala | 87 ++++--- src/main/scala/stdlib/Implicits.scala | 127 +++++----- .../InfixPrefixandPostfixOperators.scala | 40 ++-- src/main/scala/stdlib/InfixTypes.scala | 35 +-- src/main/scala/stdlib/Iterables.scala | 122 ++++++---- src/main/scala/stdlib/Lists.scala | 67 ++++-- src/main/scala/stdlib/LiteralBooleans.scala | 19 +- src/main/scala/stdlib/LiteralNumbers.scala | 48 +++- src/main/scala/stdlib/LiteralStrings.scala | 39 +-- src/main/scala/stdlib/Maps.scala | 90 ++++--- .../stdlib/NamedandDefaultArguments.scala | 146 ++++++------ .../NamedandDefaultArgumentsHelper.scala | 28 ++- src/main/scala/stdlib/Objects.scala | 17 +- src/main/scala/stdlib/Options.scala | 63 ++--- src/main/scala/stdlib/OptionsHelper.scala | 8 +- src/main/scala/stdlib/ParentClasses.scala | 55 +++-- src/main/scala/stdlib/PartialFunctions.scala | 37 +-- .../stdlib/PartiallyAppliedFunctions.scala | 38 ++- src/main/scala/stdlib/PatternMatching.scala | 85 ++++--- src/main/scala/stdlib/Ranges.scala | 43 ++-- .../scala/stdlib/RepeatedParameters.scala | 51 ++-- .../stdlib/RepeatedParametersHelper.scala | 8 +- .../scala/stdlib/SequencesandArrays.scala | 42 ++-- src/main/scala/stdlib/Sets.scala | 73 +++--- src/main/scala/stdlib/StdLib.scala | 10 +- src/main/scala/stdlib/Traits.scala | 58 +++-- src/main/scala/stdlib/Traversables.scala | 222 +++++++++--------- src/main/scala/stdlib/Tuples.scala | 45 ++-- src/main/scala/stdlib/TypeSignatures.scala | 45 ++-- src/main/scala/stdlib/TypeVariance.scala | 98 ++++---- .../scala/stdlib/TypeVarianceHelper.scala | 13 +- .../scala/stdlib/UniformAccessPrinciple.scala | 22 +- src/test/scala/stdlib/AssertsSpec.scala | 14 +- .../scala/stdlib/ByNameParameterSpec.scala | 5 + src/test/scala/stdlib/CaseClassesSpec.scala | 5 + src/test/scala/stdlib/ClassesSpec.scala | 5 + src/test/scala/stdlib/EmptyValuesSpec.scala | 5 + src/test/scala/stdlib/EnumerationsSpec.scala | 6 +- src/test/scala/stdlib/ExtractorsSpec.scala | 5 + .../scala/stdlib/ForExpressionsSpec.scala | 5 + src/test/scala/stdlib/FormattingSpec.scala | 5 + .../stdlib/HigherOrderFunctionsSpec.scala | 14 +- src/test/scala/stdlib/ImplicitsSpec.scala | 5 + .../InfixPrefixAndPostfixOperatorsSpec.scala | 5 + src/test/scala/stdlib/InfixTypesSpec.scala | 5 + src/test/scala/stdlib/IterablesSpec.scala | 5 + src/test/scala/stdlib/ListsSpec.scala | 5 + .../scala/stdlib/LiteralBooleansSpec.scala | 5 + .../scala/stdlib/LiteralNumbersSpec.scala | 5 + .../scala/stdlib/LiteralStringsSpec.scala | 5 + src/test/scala/stdlib/MapsSpec.scala | 5 + .../stdlib/NamedAndDefaultArgumentsSpec.scala | 5 + src/test/scala/stdlib/ObjectsSpec.scala | 5 + src/test/scala/stdlib/OptionsSpec.scala | 5 + src/test/scala/stdlib/ParentClassesSpec.scala | 5 + .../scala/stdlib/PartialFunctionsSpec.scala | 5 + .../PartiallyAppliedFunctionsSpec.scala | 5 + .../scala/stdlib/PatternMatchingSpec.scala | 5 + src/test/scala/stdlib/RangesSpec.scala | 5 + .../scala/stdlib/RepeatedParametersSpec.scala | 5 + .../scala/stdlib/SequencesAndArraysSpec.scala | 5 + src/test/scala/stdlib/SetsSpec.scala | 5 + src/test/scala/stdlib/TraitsSpec.scala | 5 + src/test/scala/stdlib/TraversablesSpec.scala | 5 + src/test/scala/stdlib/TuplesSpec.scala | 5 + .../scala/stdlib/TypeSignaturesSpec.scala | 5 + src/test/scala/stdlib/TypeVarianceSpec.scala | 5 + .../stdlib/UniformAccessPrincipleSpec.scala | 5 + version.sbt | 1 + 85 files changed, 1753 insertions(+), 1150 deletions(-) create mode 100644 .scalafmt.conf create mode 100644 project/ProjectPlugin.scala create mode 100644 version.sbt diff --git a/.scalafmt.conf b/.scalafmt.conf new file mode 100644 index 00000000..106c0cc5 --- /dev/null +++ b/.scalafmt.conf @@ -0,0 +1,23 @@ +style = defaultWithAlign +maxColumn = 100 + +continuationIndent.callSite = 2 + +newlines { + sometimesBeforeColonInMethodReturnType = false +} + +align { + arrowEnumeratorGenerator = false + ifWhileOpenParen = false + openParenCallSite = false + openParenDefnSite = false +} + +docstrings = JavaDoc + +rewrite { + rules = [SortImports, RedundantBraces] + redundantBraces.maxLines = 1 +} + \ No newline at end of file diff --git a/.travis.yml b/.travis.yml index 043835a4..1f143e14 100644 --- a/.travis.yml +++ b/.travis.yml @@ -15,6 +15,3 @@ after_success: - if [ "$TRAVIS_BRANCH" = "master" -a "$TRAVIS_PULL_REQUEST" = "false" ]; then sbt compile publishSigned; fi -- if [ "$TRAVIS_PULL_REQUEST" = "true" ]; then - echo "Not in master branch, skipping deploy and release"; - fi diff --git a/README.md b/README.md index ac5cb55d..fdc3e9e0 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,9 @@ -#Scala Exercises - Stdlib library - +# Scala Exercises - Stdlib library ------------------------ This repository hosts a content library for the [Scala Exercises](https://www.scala-exercises.org/) platform, including interactive exercises related to the Scala standard library. -## About Scala exercises +## About Scala exercises "Scala Exercises" brings exercises for the Stdlib, Cats, Shapeless and many other great libraries for Scala to your browser. Offering hundreds of solvable exercises organized into several categories covering the basics of the Scala language and it's most important libraries. @@ -15,7 +14,7 @@ Scala Exercises is available at [scala-exercises.org](https://scala-exercises.or Contributions welcome! Please join our [Gitter channel](https://gitter.im/scala-exercises/scala-exercises) to get involved, or visit our [GitHub site](https://github.com/scala-exercises). -##License +## License Copyright (C) 2015-2016 47 Degrees, LLC. Reactive, scalable software solutions. diff --git a/build.sbt b/build.sbt index ddc21f1a..2add93d4 100644 --- a/build.sbt +++ b/build.sbt @@ -1,51 +1,23 @@ +val scalaExerciesV = "0.4.0-SNAPSHOT" + +def dep(artifactId: String) = "org.scala-exercises" %% artifactId % scalaExerciesV + lazy val stdlib = (project in file(".")) -.settings(publishSettings:_*) .enablePlugins(ExerciseCompilerPlugin) .settings( - organization := "org.scala-exercises", name := "exercises-stdlib", - scalaVersion := "2.11.8", - version := "0.3.0-SNAPSHOT", - resolvers ++= Seq( - Resolver.sonatypeRepo("snapshots"), - Resolver.sonatypeRepo("releases") - ), libraryDependencies ++= Seq( - "com.chuusai" %% "shapeless" % "2.2.5", - "org.scalatest" %% "scalatest" % "2.2.4", - "org.scala-exercises" %% "exercise-compiler" % version.value, - "org.scala-exercises" %% "definitions" % version.value, - "org.scalacheck" %% "scalacheck" % "1.12.5", - "com.github.alexarchambault" %% "scalacheck-shapeless_1.12" % "0.3.1" - ), - licenses := Seq("Apache License, Version 2.0" -> url("http://www.apache.org/licenses/LICENSE-2.0.txt")) + dep("exercise-compiler"), + dep("definitions"), + %%("shapeless"), + %%("scalatest"), + %%("scalacheck"), + %%("scheckShapeless") + ) ) - // Distribution -lazy val gpgFolder = sys.env.getOrElse("PGP_FOLDER", ".") - -lazy val publishSettings = Seq( - organizationName := "Scala Exercises", - organizationHomepage := Some(new URL("http://scala-exercises.org")), - startYear := Some(2016), - description := "Scala Exercises: The path to enlightenment", - homepage := Some(url("http://scala-exercises.org")), - pgpPassphrase := Some(sys.env.getOrElse("PGP_PASSPHRASE", "").toCharArray), - pgpPublicRing := file(s"$gpgFolder/pubring.gpg"), - pgpSecretRing := file(s"$gpgFolder/secring.gpg"), - credentials += Credentials("Sonatype Nexus Repository Manager", "oss.sonatype.org", sys.env.getOrElse("PUBLISH_USERNAME", ""), sys.env.getOrElse("PUBLISH_PASSWORD", "")), - scmInfo := Some(ScmInfo(url("https://github.com/scala-exercises/exercises-stdlib"), "https://github.com/scala-exercises/exercises-stdlib.git")), - licenses := Seq("Apache License, Version 2.0" -> url("http://www.apache.org/licenses/LICENSE-2.0.txt")), - publishMavenStyle := true, - publishArtifact in Test := false, - pomIncludeRepository := Function.const(false), - publishTo := { - val nexus = "https://oss.sonatype.org/" - if (isSnapshot.value) - Some("Snapshots" at nexus + "content/repositories/snapshots") - else - Some("Releases" at nexus + "service/local/staging/deploy/maven2") - } -) +pgpPassphrase := Some(getEnvVar("PGP_PASSPHRASE").getOrElse("").toCharArray) +pgpPublicRing := file(s"$gpgFolder/pubring.gpg") +pgpSecretRing := file(s"$gpgFolder/secring.gpg") \ No newline at end of file diff --git a/project/ProjectPlugin.scala b/project/ProjectPlugin.scala new file mode 100644 index 00000000..47cc24f9 --- /dev/null +++ b/project/ProjectPlugin.scala @@ -0,0 +1,47 @@ +import de.heikoseeberger.sbtheader.HeaderPattern +import de.heikoseeberger.sbtheader.HeaderPlugin.autoImport._ +import sbt.Keys._ +import sbt._ +import sbtorgpolicies._ +import sbtorgpolicies.model._ +import sbtorgpolicies.OrgPoliciesPlugin.autoImport._ + +object ProjectPlugin extends AutoPlugin { + + override def trigger: PluginTrigger = allRequirements + + override def requires: Plugins = plugins.JvmPlugin && OrgPoliciesPlugin + + override def projectSettings: Seq[Def.Setting[_]] = + Seq( + description := "Scala Exercises: The path to enlightenment", + startYear := Option(2016), + orgGithubSetting := GitHubSettings( + organization = "scala-exercises", + project = name.value, + organizationName = "Scala Exercises", + groupId = "org.scala-exercises", + organizationHomePage = url("https://www.scala-exercises.org"), + organizationEmail = "hello@47deg.com" + ), + orgLicenseSetting := ApacheLicense, + scalaVersion := "2.11.8", + scalaOrganization := "org.scala-lang", + crossScalaVersions := Seq("2.11.8"), + resolvers ++= Seq( + Resolver.mavenLocal, + Resolver.sonatypeRepo("snapshots"), + Resolver.sonatypeRepo("releases") + ), + scalacOptions := sbtorgpolicies.model.scalacCommonOptions, + headers := Map( + "scala" -> (HeaderPattern.cStyleBlockComment, + s"""|/* + | * scala-exercises - ${name.value} + | * Copyright (C) 2015-2016 47 Degrees, LLC. + | */ + | + |""".stripMargin) + ) + ) +} diff --git a/project/build.properties b/project/build.properties index 7d789d45..5f32afe7 100644 --- a/project/build.properties +++ b/project/build.properties @@ -1 +1 @@ -sbt.version=0.13.12 \ No newline at end of file +sbt.version=0.13.13 \ No newline at end of file diff --git a/project/plugins.sbt b/project/plugins.sbt index eb6e308e..ad634fcd 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.3.0-SNAPSHOT", "0.13", "2.10") -addSbtPlugin("com.jsuereth" % "sbt-pgp" % "1.0.0") +addSbtPlugin("org.scala-exercises" % "sbt-exercise" % "0.4.0-SNAPSHOT", "0.13", "2.10") +addSbtPlugin("com.47deg" % "sbt-org-policies" % "0.3.2") diff --git a/src/main/scala/stdlib/Asserts.scala b/src/main/scala/stdlib/Asserts.scala index 2ac589c0..01f55e93 100644 --- a/src/main/scala/stdlib/Asserts.scala +++ b/src/main/scala/stdlib/Asserts.scala @@ -1,49 +1,54 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalatest._ /** @param name asserts - */ + */ object Asserts extends FlatSpec with Matchers with org.scalaexercises.definitions.Section { /** ScalaTest makes three assertions available by default in any style trait. You can use: - * - * - `assert` for general assertions; - * - `assertResult` to differentiate expected from actual values; - * - `intercept` to ensure a bit of code throws an expected exception. - * - * In any Scala program, you can write assertions by invoking `assert` and passing in a `Boolean` expression: - * - * {{{ - * val left = 2 - * val right = 1 - * assert(left == right) - * }}} - * - * If the passed expression is `true`, `assert` will return normally. If `false`, - * Scala's `assert` will complete abruptly with an `AssertionError`. This behavior is provided by - * the `assert` method defined in object `Predef`, whose members are implicitly imported into every Scala source file. - * - * - * ScalaTest provides a domain specific language (DSL) for expressing assertions in tests - * using the word `should`. ScalaTest matchers provides five different ways to check equality, each designed to address a different need. They are: - * - * {{{ - * result should equal (3) // can customize equality - * result should === (3) // can customize equality and enforce type constraints - * result should be (3) // cannot customize equality, so fastest to compile - * result shouldEqual 3 // can customize equality, no parentheses required - * result shouldBe 3 // cannot customize equality, so fastest to compile, no parentheses required - * }}} - * - * Come on, your turn: true and false values can be compared with should matchers: - */ + * + * - `assert` for general assertions; + * - `assertResult` to differentiate expected from actual values; + * - `intercept` to ensure a bit of code throws an expected exception. + * + * In any Scala program, you can write assertions by invoking `assert` and passing in a `Boolean` expression: + * + * {{{ + * val left = 2 + * val right = 1 + * assert(left == right) + * }}} + * + * If the passed expression is `true`, `assert` will return normally. If `false`, + * Scala's `assert` will complete abruptly with an `AssertionError`. This behavior is provided by + * the `assert` method defined in object `Predef`, whose members are implicitly imported into every Scala source file. + * + * + * ScalaTest provides a domain specific language (DSL) for expressing assertions in tests + * using the word `should`. ScalaTest matchers provides five different ways to check equality, each designed to address a different need. They are: + * + * {{{ + * result should equal (3) // can customize equality + * result should === (3) // can customize equality and enforce type constraints + * result should be (3) // cannot customize equality, so fastest to compile + * result shouldEqual 3 // can customize equality, no parentheses required + * result shouldBe 3 // cannot customize equality, so fastest to compile, no parentheses required + * }}} + * + * Come on, your turn: true and false values can be compared with should matchers: + */ def scalaTestAsserts(res0: Boolean) { true should be(res0) } /** Booleans in asserts can test equality: - */ + */ def booleanAsserts(res0: Int) { val v1 = 4 v1 shouldEqual res0 @@ -52,7 +57,7 @@ object Asserts extends FlatSpec with Matchers with org.scalaexercises.definition } /** Sometimes we expect you to fill in the values: - */ + */ 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 74bd365d..a44473b9 100644 --- a/src/main/scala/stdlib/ByNameParameter.scala +++ b/src/main/scala/stdlib/ByNameParameter.scala @@ -1,13 +1,18 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalatest._ /** @param name byname_parameter - */ + */ object ByNameParameter extends FlatSpec with Matchers with org.scalaexercises.definitions.Section { /** `() => 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] = { try { @@ -25,7 +30,7 @@ object ByNameParameter extends FlatSpec with Matchers with org.scalaexercises.de } /** 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] = { //x is a call by name parameter @@ -47,7 +52,7 @@ object ByNameParameter extends FlatSpec with Matchers with org.scalaexercises.de } /** By name parameters can also be used with `object` and `apply` to make interesting block-like calls: - */ + */ def withApplyByNameParameter(res0: String) { object PigLatinizer { def apply(x: ⇒ String) = x.tail + x.head + "ay" diff --git a/src/main/scala/stdlib/CaseClasses.scala b/src/main/scala/stdlib/CaseClasses.scala index a4179afa..3eea5c7c 100644 --- a/src/main/scala/stdlib/CaseClasses.scala +++ b/src/main/scala/stdlib/CaseClasses.scala @@ -1,92 +1,97 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalatest._ /** @param name case_classes - */ + */ object CaseClasses extends FlatSpec with Matchers with org.scalaexercises.definitions.Section { /** Scala supports the notion of ''case classes''. Case classes are regular classes which export their constructor parameters and which provide a recursive decomposition mechanism via pattern matching. - * - * Here is an example for a class hierarchy which consists of an abstract superclass `Term` and three concrete case classes `Var`, `Fun`, and `App`: - * - * {{{ - * abstract class Term - * case class Var(name: String) extends Term - * case class Fun(arg: String, body: Term) extends Term - * case class App(f: Term, v: Term) extends Term - * }}} - * - * This class hierarchy can be used to represent terms of the untyped lambda calculus. To facilitate the construction of case class instances, Scala does not require that the `new` primitive is used. One can simply use the class name as a function. - * - * Here is an example: - * - * {{{ - * Fun("x", Fun("y", App(Var("x"), Var("y")))) - * }}} - * - * The constructor parameters of case classes are treated as public values and can be accessed directly. - * - * {{{ - * val x = Var("x") - * println(x.name) - * }}} - * - * For every case class the Scala compiler generates an `equals` method which implements structural equality and a `toString` method. For instance, - * - * {{{ - * val x1 = Var("x") - * val x2 = Var("x") - * val y1 = Var("y") - * println("" + x1 + " == " + x2 + " => " + (x1 == x2)) - * println("" + x1 + " == " + y1 + " => " + (x1 == y1)) - * }}} - * - * will print - * - * {{{ - * Var(x) == Var(x) => true - * Var(x) == Var(y) => false - * }}} - * - * It only makes sense to define case classes if pattern matching is used to decompose data structures. The following object defines a pretty printer function for our lambda calculus representation: - * - * {{{ - * object TermTest extends Application { - * def printTerm(term: Term) { - * term match { - * case Var(n) => - * print(n) - * case Fun(x, b) => - * print("^" + x + ".") - * printTerm(b) - * case App(f, v) => - * print("(") - * printTerm(f) - * print(" ") - * printTerm(v) - * print(")") - * } - * } - * def isIdentityFun(term: Term): Boolean = term match { - * case Fun(x, Var(y)) if x == y => true - * case _ => false - * } - * val id = Fun("x", Var("x")) - * val t = Fun("x", Fun("y", App(Var("x"), Var("y")))) - * printTerm(t) - * println - * println(isIdentityFun(id)) - * println(isIdentityFun(t)) - * } - * }}} - * - * In our example, the function `printTerm` is expressed as a pattern matching statement starting with the `match` keyword and consisting of sequences of `case Pattern => Body` clauses. - * - * The program above also defines a function `isIdentityFun` which checks if a given term corresponds to a simple identity function. This example uses deep patterns and guards. After matching a pattern with a given value, the guard (defined after the keyword `if`) is evaluated. If it returns `true`, the match succeeds; otherwise, it fails and the next pattern will be tried. - * - * Case classes have an automatic equals method that works: - */ + * + * Here is an example for a class hierarchy which consists of an abstract superclass `Term` and three concrete case classes `Var`, `Fun`, and `App`: + * + * {{{ + * abstract class Term + * case class Var(name: String) extends Term + * case class Fun(arg: String, body: Term) extends Term + * case class App(f: Term, v: Term) extends Term + * }}} + * + * This class hierarchy can be used to represent terms of the untyped lambda calculus. To facilitate the construction of case class instances, Scala does not require that the `new` primitive is used. One can simply use the class name as a function. + * + * Here is an example: + * + * {{{ + * Fun("x", Fun("y", App(Var("x"), Var("y")))) + * }}} + * + * The constructor parameters of case classes are treated as public values and can be accessed directly. + * + * {{{ + * val x = Var("x") + * println(x.name) + * }}} + * + * For every case class the Scala compiler generates an `equals` method which implements structural equality and a `toString` method. For instance, + * + * {{{ + * val x1 = Var("x") + * val x2 = Var("x") + * val y1 = Var("y") + * println("" + x1 + " == " + x2 + " => " + (x1 == x2)) + * println("" + x1 + " == " + y1 + " => " + (x1 == y1)) + * }}} + * + * will print + * + * {{{ + * Var(x) == Var(x) => true + * Var(x) == Var(y) => false + * }}} + * + * It only makes sense to define case classes if pattern matching is used to decompose data structures. The following object defines a pretty printer function for our lambda calculus representation: + * + * {{{ + * object TermTest extends Application { + * def printTerm(term: Term) { + * term match { + * case Var(n) => + * print(n) + * case Fun(x, b) => + * print("^" + x + ".") + * printTerm(b) + * case App(f, v) => + * print("(") + * printTerm(f) + * print(" ") + * printTerm(v) + * print(")") + * } + * } + * def isIdentityFun(term: Term): Boolean = term match { + * case Fun(x, Var(y)) if x == y => true + * case _ => false + * } + * val id = Fun("x", Var("x")) + * val t = Fun("x", Fun("y", App(Var("x"), Var("y")))) + * printTerm(t) + * println + * println(isIdentityFun(id)) + * println(isIdentityFun(t)) + * } + * }}} + * + * In our example, the function `printTerm` is expressed as a pattern matching statement starting with the `match` keyword and consisting of sequences of `case Pattern => Body` clauses. + * + * The program above also defines a function `isIdentityFun` which checks if a given term corresponds to a simple identity function. This example uses deep patterns and guards. After matching a pattern with a given value, the guard (defined after the keyword `if`) is evaluated. If it returns `true`, the match succeeds; otherwise, it fails and the next pattern will be tried. + * + * Case classes have an automatic equals method that works: + */ def caseClassesSupportEquality(res0: Boolean, res1: Boolean, res2: Boolean, res3: Boolean) { case class Person(first: String, last: String) @@ -102,7 +107,7 @@ object CaseClasses extends FlatSpec with Matchers with org.scalaexercises.defini } /** Case classes have an automatic hashcode method that works: - */ + */ def hashcodeMethodCaseClasses(res0: Boolean, res1: Boolean) { case class Person(first: String, last: String) @@ -115,7 +120,7 @@ object CaseClasses extends FlatSpec with Matchers with org.scalaexercises.defini } /** Case classes can be created in a convenient way: - */ + */ def creationCaseClasses(res0: Boolean, res1: Boolean, res2: Boolean) { case class Dog(name: String, breed: String) @@ -129,7 +134,7 @@ object CaseClasses extends FlatSpec with Matchers with org.scalaexercises.defini } /** Case classes have a convenient toString method defined: - */ + */ def toStringMethodCaseClasses(res0: String) { case class Dog(name: String, breed: String) val d1 = Dog("Scooby", "Doberman") @@ -137,7 +142,7 @@ object CaseClasses extends FlatSpec with Matchers with org.scalaexercises.defini } /** Case classes have automatic properties: - */ + */ def propertiesCaseClasses(res0: String, res1: String) { case class Dog(name: String, breed: String) @@ -147,7 +152,7 @@ object CaseClasses extends FlatSpec with Matchers with org.scalaexercises.defini } /** Case classes can have mutable properties: - */ + */ 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") @@ -162,7 +167,7 @@ object CaseClasses extends FlatSpec with Matchers with org.scalaexercises.defini } /** There are safer alternatives for altering case classes: - */ + */ def alteringCaseClasses(res0: String, res1: String, res2: String, res3: String) { case class Dog(name: String, breed: String) // Doberman @@ -178,8 +183,21 @@ object CaseClasses extends FlatSpec with Matchers with org.scalaexercises.defini } /** Case classes can have default and named parameters: - */ - def parametersCaseClasses(res0: String, res1: String, res2: Int, res3: String, res4: String, res5: String, res6: Int, res7: String, res8: String, res9: String, res10: Int, res11: String, res12: Boolean) { + */ + def parametersCaseClasses( + res0: String, + res1: String, + res2: Int, + res3: String, + res4: String, + res5: String, + res6: Int, + res7: String, + res8: String, + res9: String, + res10: Int, + res11: String, + 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 @@ -205,7 +223,7 @@ object CaseClasses extends FlatSpec with Matchers with org.scalaexercises.defini } /** Case classes can be disassembled to their constituent parts as a tuple: - */ + */ 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") @@ -219,7 +237,7 @@ object CaseClasses extends FlatSpec with Matchers with org.scalaexercises.defini } /** Case classes are `Serializable`: - */ + */ 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 6ada3d42..7581e19f 100644 --- a/src/main/scala/stdlib/Classes.scala +++ b/src/main/scala/stdlib/Classes.scala @@ -1,39 +1,44 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalatest._ /** @param name classes - */ + */ object Classes extends FlatSpec with Matchers with org.scalaexercises.definitions.Section { /** Classes in Scala are static templates that can be instantiated into many objects at runtime. - * Here is a class definition which defines a class Point: - * - * {{{ - * class Point(x: Int, y: Int) { - * override def toString(): String = "(" + x + ", " + y + ")" - * } - * }}} - * The class defines two variables `x` and `y` and one method `toString`. - * - * Classes in Scala are parameterized with constructor arguments. The code above defines two constructor arguments, `x` and `y`; they are both visible in the whole body of the class. In our example they are used to implement `toString`. - * - * Classes are instantiated with the `new` primitive, as the following example will show: - * - * {{{ - * object Classes { - * def main(args: Array[String]) { - * val pt = new Point(1, 2) - * println(pt) - * } - * } - * }}} - * - * The program defines an executable application `Classes` in the form of a top-level singleton object with a `main` method. The `main` method creates a new `Point` and stores it in value `pt`. - * - * 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: - * - */ + * Here is a class definition which defines a class Point: + * + * {{{ + * class Point(x: Int, y: Int) { + * override def toString(): String = "(" + x + ", " + y + ")" + * } + * }}} + * The class defines two variables `x` and `y` and one method `toString`. + * + * Classes in Scala are parameterized with constructor arguments. The code above defines two constructor arguments, `x` and `y`; they are both visible in the whole body of the class. In our example they are used to implement `toString`. + * + * Classes are instantiated with the `new` primitive, as the following example will show: + * + * {{{ + * object Classes { + * def main(args: Array[String]) { + * val pt = new Point(1, 2) + * println(pt) + * } + * } + * }}} + * + * The program defines an executable application `Classes` in the form of a top-level singleton object with a `main` method. The `main` method creates a new `Point` and stores it in value `pt`. + * + * 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) { class ClassWithValParameter(val name: String) val aClass = new ClassWithValParameter("Gandalf") diff --git a/src/main/scala/stdlib/EmptyValues.scala b/src/main/scala/stdlib/EmptyValues.scala index e4aba087..253d2701 100644 --- a/src/main/scala/stdlib/EmptyValues.scala +++ b/src/main/scala/stdlib/EmptyValues.scala @@ -1,72 +1,77 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalatest._ /** @param name empty_values - * - */ + * + */ object EmptyValues extends FlatSpec with Matchers with org.scalaexercises.definitions.Section { /** ==null== - * - * Scala's `null` is the same as in Java. Any reference type can be `null`, like Strings, Objects, or your own classes. Also just like Java, value types like Ints can't be `null`. - * - * ==Null== - * - * [[http://www.scala-lang.org/api/current/index.html#scala.Null Null]] is a trait whose only instance is `null`. It is a subtype of all reference types, but not of value types. It purpose in existing is to make it so reference types can be assigned `null` and value types can't. - * - * ==Nothing== - * - * [[http://www.scala-lang.org/api/current/index.html#scala.Nothing Nothing]] is a trait that is guaranteed to have zero instances. It is a subtype of all other types. It has two main reasons for existing: to provide a return type for methods that never return normally (i.e. a method that always throws an exception). The other reason is to provide a type for Nil (explained below). - * - * ==Unit== - * - * [[http://www.scala-lang.org/api/current/index.html#scala.Unit Unit]] in Scala is the equivalent of `void` in Java. It's used in a function's signature when that function doesn't return a value. - * - * ==Nil== - * - * [[http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Nil$ Nil]] is just an empty list, exactly like the result of `List()`. It is of type `List[Nothing]`. And since we know there are no instances of Nothing, we now have a list that is statically verifiable as empty. Nice to have. - * - * An empty list can be represented by another nothing value: `Nil` - */ + * + * Scala's `null` is the same as in Java. Any reference type can be `null`, like Strings, Objects, or your own classes. Also just like Java, value types like Ints can't be `null`. + * + * ==Null== + * + * [[http://www.scala-lang.org/api/current/index.html#scala.Null Null]] is a trait whose only instance is `null`. It is a subtype of all reference types, but not of value types. It purpose in existing is to make it so reference types can be assigned `null` and value types can't. + * + * ==Nothing== + * + * [[http://www.scala-lang.org/api/current/index.html#scala.Nothing Nothing]] is a trait that is guaranteed to have zero instances. It is a subtype of all other types. It has two main reasons for existing: to provide a return type for methods that never return normally (i.e. a method that always throws an exception). The other reason is to provide a type for Nil (explained below). + * + * ==Unit== + * + * [[http://www.scala-lang.org/api/current/index.html#scala.Unit Unit]] in Scala is the equivalent of `void` in Java. It's used in a function's signature when that function doesn't return a value. + * + * ==Nil== + * + * [[http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Nil$ Nil]] is just an empty list, exactly like the result of `List()`. It is of type `List[Nothing]`. And since we know there are no instances of Nothing, we now have a list that is statically verifiable as empty. Nice to have. + * + * An empty list can be represented by another nothing value: `Nil` + */ 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`: - */ + * + * `None` equals `None`: + */ def avoidingNullEmptyValues(res0: Boolean) { None === None shouldBe res0 } /** `None` should be identical to `None`: - */ + */ def identicalNoneEmptyValues(res0: Boolean) { None eq None shouldBe res0 } /** `None` can be converted to a String: - */ + */ def noneToStringEmptyValues(res0: String) { assert(None.toString === res0) } /** `None` can be converted to an empty list: - */ + */ def noneToListEmptyValues(res0: Boolean) { None.toList === Nil shouldBe res0 } /** `None` is considered empty: - */ + */ 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) { None.asInstanceOf[Any] === None shouldBe res0 None.asInstanceOf[AnyRef] === None shouldBe res1 @@ -74,7 +79,7 @@ object EmptyValues extends FlatSpec with Matchers with org.scalaexercises.defini } /** `None` can be used with `Option` instead of null references: - */ + */ def noneWithOptionEmptyValues(res0: Boolean, res1: Option[String]) { val optional: Option[String] = None assert(optional.isEmpty === res0) @@ -82,7 +87,7 @@ object EmptyValues extends FlatSpec with Matchers with org.scalaexercises.defini } /** `Some` is the opposite of `None` for `Option` types: - */ + */ def someAgainstNoneEmptyValues(res0: Boolean, res1: Boolean) { val optional: Option[String] = Some("Some Value") assert((optional == None) === res0, "Some(value) should not equal None") @@ -90,9 +95,9 @@ object EmptyValues extends FlatSpec with Matchers with org.scalaexercises.defini } /** `Option.getOrElse` can be used to provide a default in the case of `None`: - */ + */ def getOrElseEmptyValues(res0: String, res1: String) { - val optional: Option[String] = Some("Some Value") + 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") assert(optional2.getOrElse("No Value") === res1, "Should return the specified default value") diff --git a/src/main/scala/stdlib/Enumerations.scala b/src/main/scala/stdlib/Enumerations.scala index 8e7b6ba6..abf722da 100644 --- a/src/main/scala/stdlib/Enumerations.scala +++ b/src/main/scala/stdlib/Enumerations.scala @@ -1,27 +1,38 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalatest._ /** @param name enumerations - * - */ + * + */ object Enumerations extends FlatSpec with Matchers with org.scalaexercises.definitions.Section { /** To create an enumeration, create an object that extends the abstract class `Enumeration`, and set a `val` variable to the method `Value`. This is a trick to give values to each `val`. - * - * `Value` assigns a numerical value to fields: - */ - def createEnumerationEnumerations(res0: Int, res1: Int, res2: String, res3: String, res4: Boolean, res5: Boolean) { + * + * `Value` assigns a numerical value to fields: + */ + def createEnumerationEnumerations( + res0: Int, + res1: Int, + res2: String, + res3: String, + res4: Boolean, + res5: Boolean) { object Planets extends Enumeration { val Mercury = Value - val Venus = Value - val Earth = Value - val Mars = Value + val Venus = Value + val Earth = Value + val Mars = Value val Jupiter = Value - val Saturn = Value - val Uranus = Value + val Saturn = Value + val Uranus = Value val Neptune = Value - val Pluto = Value + val Pluto = Value } Planets.Mercury.id should be(res0) @@ -35,20 +46,26 @@ object Enumerations extends FlatSpec with Matchers with org.scalaexercises.defin } /** You can create an enumeration with your own index and your own Strings, in this exercise we will start with an index of one and use Greek names instead of Roman: - */ - def ownIndexEnumerations(res0: Int, res1: Int, res2: String, res3: String, res4: Boolean, res5: Boolean) { + */ + def ownIndexEnumerations( + res0: Int, + res1: Int, + res2: String, + res3: String, + res4: Boolean, + res5: Boolean) { object GreekPlanets extends Enumeration { val Mercury = Value(1, "Hermes") - val Venus = Value(2, "Aphrodite") + val Venus = Value(2, "Aphrodite") //Fun Fact: Tellus is Roman for (Mother) Earth - val Earth = Value(3, "Gaia") - val Mars = Value(4, "Ares") + val Earth = Value(3, "Gaia") + val Mars = Value(4, "Ares") val Jupiter = Value(5, "Zeus") - val Saturn = Value(6, "Cronus") - val Uranus = Value(7, "Ouranus") + val Saturn = Value(6, "Cronus") + val Uranus = Value(7, "Ouranus") val Neptune = Value(8, "Poseidon") - val Pluto = Value(9, "Hades") + val Pluto = Value(9, "Hades") } GreekPlanets.Mercury.id should be(res0) @@ -62,8 +79,14 @@ object Enumerations extends FlatSpec with Matchers with org.scalaexercises.defin } /** Enumerations can be declared in one line if you are merely setting variables to `Value`: - */ - def oneLineEnumerations(res0: Int, res1: Int, res2: String, res3: String, res4: Boolean, res5: Boolean) { + */ + def oneLineEnumerations( + res0: Int, + res1: Int, + res2: String, + res3: String, + res4: Boolean, + res5: Boolean) { object Planets extends Enumeration { val Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune, Pluto = Value } @@ -79,19 +102,25 @@ object Enumerations extends FlatSpec with Matchers with org.scalaexercises.defin } /** Enumerations can be declared with a string value only: - */ - def stringValueEnumerations(res0: Int, res1: Int, res2: String, res3: String, res4: Boolean, res5: Boolean) { + */ + def stringValueEnumerations( + res0: Int, + res1: Int, + res2: String, + res3: String, + res4: Boolean, + res5: Boolean) { object GreekPlanets extends Enumeration { val Mercury = Value("Hermes") - val Venus = Value("Aphrodite") - val Earth = Value("Gaia") - val Mars = Value("Ares") + val Venus = Value("Aphrodite") + val Earth = Value("Gaia") + val Mars = Value("Ares") val Jupiter = Value("Zeus") - val Saturn = Value("Cronus") - val Uranus = Value("Ouranus") + val Saturn = Value("Cronus") + val Uranus = Value("Ouranus") val Neptune = Value("Poseidon") - val Pluto = Value("Hades") + val Pluto = Value("Hades") } GreekPlanets.Mercury.id should be(res0) @@ -105,7 +134,7 @@ object Enumerations extends FlatSpec with Matchers with org.scalaexercises.defin } /** You can extend the `Enumeration` by extending the `Value` class. - */ + */ def extendingValueEnumerations(res0: Double, res1: Double) { object Planets extends Enumeration { @@ -122,14 +151,14 @@ object Enumerations extends FlatSpec with Matchers with org.scalaexercises.defin } val Mercury = new PlanetValue(0, "Mercury", 3.303e+23, 2.4397e6) - val Venus = new PlanetValue(1, "Venus", 4.869e+24, 6.0518e6) - val Earth = new PlanetValue(2, "Earth", 5.976e+24, 6.37814e6) - val Mars = new PlanetValue(3, "Mars", 6.421e+23, 3.3972e6) + val Venus = new PlanetValue(1, "Venus", 4.869e+24, 6.0518e6) + val Earth = new PlanetValue(2, "Earth", 5.976e+24, 6.37814e6) + val Mars = new PlanetValue(3, "Mars", 6.421e+23, 3.3972e6) val Jupiter = new PlanetValue(4, "Jupiter", 1.9e+27, 7.1492e7) - val Saturn = new PlanetValue(5, "Saturn", 5.688e+26, 6.0268e7) - val Uranus = new PlanetValue(6, "Uranus", 8.686e+25, 2.5559e7) + val Saturn = new PlanetValue(5, "Saturn", 5.688e+26, 6.0268e7) + val Uranus = new PlanetValue(6, "Uranus", 8.686e+25, 2.5559e7) val Neptune = new PlanetValue(7, "Neptune", 1.024e+26, 2.4746e7) - val Pluto = new PlanetValue(8, "Pluto", 1.27e+22, 1.137e6) + val Pluto = new PlanetValue(8, "Pluto", 1.27e+22, 1.137e6) } diff --git a/src/main/scala/stdlib/Extractors.scala b/src/main/scala/stdlib/Extractors.scala index 0600d071..70605069 100644 --- a/src/main/scala/stdlib/Extractors.scala +++ b/src/main/scala/stdlib/Extractors.scala @@ -1,52 +1,57 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalatest._ /** @param name extractors - * - */ + * + */ object Extractors extends FlatSpec with Matchers with org.scalaexercises.definitions.Section { /** In Scala, patterns can be defined independently of case classes. To this end, a method named `unapply` is defined to yield a so-called extractor. - * - * For instance, the following code defines an extractor object `Twice`. - * - * {{{ - * object Twice { - * def apply(x: Int): Int = x * 2 - * def unapply(z: Int): Option[Int] = if (z%2 == 0) Some(z/2) else None - * } - * - * object TwiceTest extends Application { - * val x = Twice(21) - * x match { case Twice(n) => Console.println(n) } // prints 21 - * } - * }}} - * - * There are two syntactic conventions at work here: - * - * - The pattern `case Twice(n)` will cause an invocation of `Twice.unapply`, which is used to match even number; the return value of the `unapply` signals whether the argument has matched or not, and any sub-values that can be used for further matching. Here, the sub-value is `z/2` - * - The `apply` method is not necessary for pattern matching. It is only used to mimick a constructor. `val x = Twice(21)` expands to `val x = Twice.apply(21)`. - * - * The code in the preceding example would be expanded as follows: - * - * {{{ - * object TwiceTest extends Application { - * val x = Twice.apply(21) - * Twice.unapply(x) match { case Some(n) => Console.println(n) } // prints 21 - * } - * }}} - * The return type of an `unapply` should be chosen as follows: - * - * - If it is just a test, return a `Boolean`. For instance `case even()` - * - If it returns a single sub-value of type `T`, return a `Option[T]` - * - If you want to return several sub-values `T1,...,Tn`, group them in an optional tuple `Option[(T1,...,Tn)]`. - * - * Sometimes, the number of sub-values is fixed and we would like to return a sequence. For this reason, you can also define patterns through `unapplySeq`. The last sub-value type `Tn` has to be `Seq[S]`. This mechanism is used for instance in pattern `case List(x1, ..., xn)`. - * - * When you create a case class, it automatically can be used with pattern matching since it has an extractor: - * - */ + * + * For instance, the following code defines an extractor object `Twice`. + * + * {{{ + * object Twice { + * def apply(x: Int): Int = x * 2 + * def unapply(z: Int): Option[Int] = if (z%2 == 0) Some(z/2) else None + * } + * + * object TwiceTest extends Application { + * val x = Twice(21) + * x match { case Twice(n) => Console.println(n) } // prints 21 + * } + * }}} + * + * There are two syntactic conventions at work here: + * + * - The pattern `case Twice(n)` will cause an invocation of `Twice.unapply`, which is used to match even number; the return value of the `unapply` signals whether the argument has matched or not, and any sub-values that can be used for further matching. Here, the sub-value is `z/2` + * - The `apply` method is not necessary for pattern matching. It is only used to mimick a constructor. `val x = Twice(21)` expands to `val x = Twice.apply(21)`. + * + * The code in the preceding example would be expanded as follows: + * + * {{{ + * object TwiceTest extends Application { + * val x = Twice.apply(21) + * Twice.unapply(x) match { case Some(n) => Console.println(n) } // prints 21 + * } + * }}} + * The return type of an `unapply` should be chosen as follows: + * + * - If it is just a test, return a `Boolean`. For instance `case even()` + * - If it returns a single sub-value of type `T`, return a `Option[T]` + * - If you want to return several sub-values `T1,...,Tn`, group them in an optional tuple `Option[(T1,...,Tn)]`. + * + * Sometimes, the number of sub-values is fixed and we would like to return a sequence. For this reason, you can also define patterns through `unapplySeq`. The last sub-value type `Tn` has to be `Seq[S]`. This mechanism is used for instance in pattern `case List(x1, ..., xn)`. + * + * When you create a case class, it automatically can be used with pattern matching since it has an extractor: + * + */ def extractorsExtractors(res0: String) { case class Employee(firstName: String, lastName: String) @@ -60,7 +65,7 @@ object Extractors extends FlatSpec with Matchers with org.scalaexercises.definit } /** 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) { class Car(val make: String, val model: String, val year: Short, val topSpeed: Short) @@ -77,7 +82,7 @@ object Extractors extends FlatSpec with Matchers with org.scalaexercises.definit } /** An extractor can also be used in pattern matching: - */ + */ def patternMatchingExtractors(res0: String, res1: String) { class Car(val make: String, val model: String, val year: Short, val topSpeed: Short) @@ -95,7 +100,7 @@ object Extractors extends FlatSpec with Matchers with org.scalaexercises.definit } /** 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) { class Car(val make: String, val model: String, val year: Short, val topSpeed: Short) @@ -113,7 +118,7 @@ object Extractors extends FlatSpec with Matchers with org.scalaexercises.definit } /** As long as the method signatures aren't the same, you can have as many unapply methods as you want: - */ + */ 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) @@ -133,7 +138,7 @@ object Extractors extends FlatSpec with Matchers with org.scalaexercises.definit } /** An extractor can be any stable object, including instantiated classes with an unapply method: - */ + */ 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) @@ -150,12 +155,12 @@ object Extractors extends FlatSpec with Matchers with org.scalaexercises.definit } /** 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) { class Employee( - val firstName: String, - val middleName: Option[String], - val lastName: String + val firstName: String, + val middleName: Option[String], + val lastName: String ) object Employee { @@ -175,12 +180,12 @@ object Extractors extends FlatSpec with Matchers with org.scalaexercises.definit } /** In this exercise we use `unapply` for pattern matching employee objects: - */ + */ def unapplyForPatternMatchingExtractors(res0: String) { class Employee( - val firstName: String, - val middleName: Option[String], - val lastName: String + val firstName: String, + val middleName: Option[String], + val lastName: String ) object Employee { @@ -193,9 +198,11 @@ object Extractors extends FlatSpec with Matchers with org.scalaexercises.definit val singri = new Employee("Singri", None, "Keerthi") val result = singri match { - case Employee("Singri", None, x) ⇒ "Yay, Singri %s! with no middle name!".format(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 Employee("Singri", None, x) ⇒ + "Yay, Singri %s! with no middle name!".format(x) + case Employee("Singri", Some(x), _) ⇒ + "Yay, Singri with a middle name of %s".format(x) + 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 a25487bd..a2970868 100644 --- a/src/main/scala/stdlib/ForExpressions.scala +++ b/src/main/scala/stdlib/ForExpressions.scala @@ -1,14 +1,19 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalatest._ /** @param name for_expressions - * - */ + * + */ object ForExpressions extends FlatSpec with Matchers with org.scalaexercises.definitions.Section { /** `for` expressions can nest, with later generators varying more rapidly than earlier ones: - */ + */ def canBeNestedForExpressions(res0: Int, res1: Int) { val xValues = 1 to 4 val yValues = 1 to 2 @@ -20,13 +25,13 @@ object ForExpressions extends FlatSpec with Matchers with org.scalaexercises.def } /** Using `for` we can make more readable code: - */ + */ 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 + num ← numList if (num % 2 == 0) } yield (num) diff --git a/src/main/scala/stdlib/Formatting.scala b/src/main/scala/stdlib/Formatting.scala index 6bdb1329..6938840d 100644 --- a/src/main/scala/stdlib/Formatting.scala +++ b/src/main/scala/stdlib/Formatting.scala @@ -1,21 +1,26 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalatest._ /** @param name formatting - * - */ + * + */ object Formatting extends FlatSpec with Matchers with org.scalaexercises.definitions.Section { /** String can be placed in format: - */ + */ 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) { val a = 'a' val b = 'B' @@ -28,7 +33,7 @@ object Formatting extends FlatSpec with Matchers with org.scalaexercises.definit } /** Character Literals can be an escape sequence, including octal or hexidecimal: - */ + */ def escapeSequenceFormatting(res0: String, res1: String, res2: String, res3: String) { val c = '\u0061' //unicode for a val d = '\141' //octal for a @@ -42,14 +47,14 @@ object Formatting extends FlatSpec with Matchers with org.scalaexercises.definit } /** Formatting can also include numbers: - */ + */ 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) { val j = 190 val k = "vodka" diff --git a/src/main/scala/stdlib/HigherOrderFunctions.scala b/src/main/scala/stdlib/HigherOrderFunctions.scala index 0e5dc3b4..ed6a85e3 100644 --- a/src/main/scala/stdlib/HigherOrderFunctions.scala +++ b/src/main/scala/stdlib/HigherOrderFunctions.scala @@ -1,18 +1,34 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalatest._ /** @param name higher_order_functions - * - */ -object HigherOrderFunctions extends FlatSpec with Matchers with org.scalaexercises.definitions.Section { + * + */ +object HigherOrderFunctions + extends FlatSpec + with Matchers + with org.scalaexercises.definitions.Section { /** Meet lambda. Scala provides a relatively lightweight syntax for defining anonymous functions. Anonymous functions in source code are called function literals and at run time, function literals are instantiated into objects called function values. - * - * Scala supports first-class functions, which means you can express functions in function literal syntax, i.e. ` (x: Int) => x + 1`, and those functions can be represented by objects, which are called function values. - */ - def meetLambdaHigherOrderFunctions(res0: Int, res1: Int, res2: Int, res3: Int, res4: Int, res5: Int) { - def lambda = { x: Int ⇒ x + 1 } + * + * Scala supports first-class functions, which means you can express functions in function literal syntax, i.e. ` (x: Int) => x + 1`, and those functions can be represented by objects, which are called function values. + */ + def meetLambdaHigherOrderFunctions( + res0: Int, + res1: Int, + res2: Int, + res3: Int, + res4: Int, + res5: Int) { + def lambda = { x: Int ⇒ + x + 1 + } def lambda2 = (x: Int) ⇒ x + 2 val lambda3 = (x: Int) ⇒ x + 3 @@ -22,7 +38,7 @@ object HigherOrderFunctions extends FlatSpec with Matchers with org.scalaexercis def lambda5(x: Int) = x + 1 - val result = lambda(3) + val result = lambda(3) val `result1andhalf` = lambda.apply(3) val result2 = lambda2(3) @@ -39,26 +55,26 @@ object HigherOrderFunctions extends FlatSpec with Matchers with org.scalaexercis } /** 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 result = lambda(5) result should be(res0) } - /** Here the only variable used in the function body, `i * 10`, is `i`, which is defined as a parameter to the function. - * - *{{{ - * val multiplier = (i:Int) => i * 10 - * }}} - * - * 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. - */ + /** Here the only variable used in the function body, `i * 10`, is `i`, which is defined as a parameter to the function. + * + *{{{ + * val multiplier = (i:Int) => i * 10 + * }}} + * + * 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) { var incrementer = 1 - def closure = { - x: Int ⇒ x + incrementer + def closure = { x: Int ⇒ + x + incrementer } val result1 = closure(10) @@ -71,12 +87,12 @@ object HigherOrderFunctions extends FlatSpec with Matchers with org.scalaexercis } /** We can take that closure and throw it into a method and it will still hold the environment: - */ + */ 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) @@ -87,15 +103,14 @@ object HigherOrderFunctions extends FlatSpec with Matchers with org.scalaexercis } /** Function returning another function: - */ + */ 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 } } - addWithoutSyntaxSugar(1). - isInstanceOf[Function1[Int, Int]] should be(res0) + addWithoutSyntaxSugar(1).isInstanceOf[Function1[Int, Int]] should be(res0) addWithoutSyntaxSugar(2)(3) should be(res1) @@ -104,7 +119,7 @@ object HigherOrderFunctions extends FlatSpec with Matchers with org.scalaexercis } /** Function returning another function using an anonymous function: - */ + */ def returningAnonymousFunctionHigherOrderFunctions(res0: Boolean, res1: Int, res2: Int) { def addWithSyntaxSugar(x: Int) = (y: Int) ⇒ x + y @@ -116,7 +131,7 @@ object HigherOrderFunctions extends FlatSpec with Matchers with org.scalaexercis } /** `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 @@ -124,22 +139,24 @@ object HigherOrderFunctions extends FlatSpec with Matchers with org.scalaexercis } /** Function taking another function as a parameter. Helps in composing functions. - * - * Hint: a map method applies the function to each element of a list. - */ - def functionAsParameterHigherOrderFunctions(res0: List[String], res1: List[String], res2: List[Int]) { + * + * Hint: a map method applies the function to each element of a list. + */ + def functionAsParameterHigherOrderFunctions( + res0: List[String], + res1: List[String], + res2: 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 ⇒ x.toLowerCase + makeWhatEverYouLike(List("ABC", "XYZ", "123"), { x ⇒ + x.toLowerCase }) should be(res1) //using it inline diff --git a/src/main/scala/stdlib/Implicits.scala b/src/main/scala/stdlib/Implicits.scala index c94697e0..d4269872 100644 --- a/src/main/scala/stdlib/Implicits.scala +++ b/src/main/scala/stdlib/Implicits.scala @@ -1,68 +1,74 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalatest._ import scala.language.implicitConversions /** @param name implicits - * - */ + * + */ object Implicits extends FlatSpec with Matchers with org.scalaexercises.definitions.Section { - /** The actual arguments that are eligible to be passed to an implicit parameter fall into two categories: - * - * - First, eligible are all identifiers x that can be accessed at the point of the method call without a prefix and that denote an implicit definition or an implicit parameter. - * - Second, eligible are also all members of companion modules of the implicit parameter's type that are labeled implicit. - * - * In the following example we define a method `sum` which computes the sum of a list of elements using the monoid's `add` and `unit` operations. Please note that implicit values can not be top-level, they have to be members of a template. - * - * {{{ - * abstract class SemiGroup[A] { - * def add(x: A, y: A): A - * } - * abstract class Monoid[A] extends SemiGroup[A] { - * def unit: A - * } - * object ImplicitTest extends App { - * implicit object StringMonoid extends Monoid[String] { - * def add(x: String, y: String): String = x concat y - * def unit: String = "" - * } - * implicit object IntMonoid extends Monoid[Int] { - * def add(x: Int, y: Int): Int = x + y - * def unit: Int = 0 - * } - * def sum[A](xs: List[A])(implicit m: Monoid[A]): A = - * if (xs.isEmpty) m.unit - * else m.add(xs.head, sum(xs.tail)) - * println(sum(List(1, 2, 3))) - * println(sum(List("a", "b", "c"))) - * } - * }}} - * - * Here is the output of the Scala program: - * - * {{{ - * 6 - * abc - * }}} - * - * Implicits wrap around existing classes to provide extra functionality. This is similar to monkey patching in Ruby and meta-programming in Groovy. - * - * Creating a method `isOdd` for `Int`, which doesn't exist: - */ + /** The actual arguments that are eligible to be passed to an implicit parameter fall into two categories: + * + * - First, eligible are all identifiers x that can be accessed at the point of the method call without a prefix and that denote an implicit definition or an implicit parameter. + * - Second, eligible are also all members of companion modules of the implicit parameter's type that are labeled implicit. + * + * In the following example we define a method `sum` which computes the sum of a list of elements using the monoid's `add` and `unit` operations. Please note that implicit values can not be top-level, they have to be members of a template. + * + * {{{ + * abstract class SemiGroup[A] { + * def add(x: A, y: A): A + * } + * abstract class Monoid[A] extends SemiGroup[A] { + * def unit: A + * } + * object ImplicitTest extends App { + * implicit object StringMonoid extends Monoid[String] { + * def add(x: String, y: String): String = x concat y + * def unit: String = "" + * } + * implicit object IntMonoid extends Monoid[Int] { + * def add(x: Int, y: Int): Int = x + y + * def unit: Int = 0 + * } + * def sum[A](xs: List[A])(implicit m: Monoid[A]): A = + * if (xs.isEmpty) m.unit + * else m.add(xs.head, sum(xs.tail)) + * println(sum(List(1, 2, 3))) + * println(sum(List("a", "b", "c"))) + * } + * }}} + * + * Here is the output of the Scala program: + * + * {{{ + * 6 + * abc + * }}} + * + * Implicits wrap around existing classes to provide extra functionality. This is similar to monkey patching in Ruby and meta-programming in Groovy. + * + * Creating a method `isOdd` for `Int`, which doesn't exist: + */ def implicitsParametersImplicits(res0: Boolean, res1: Boolean) { class KoanIntWrapper(val original: Int) { def isOdd = original % 2 != 0 } - implicit def thisMethodNameIsIrrelevant(value: Int) = new KoanIntWrapper(value) + implicit def thisMethodNameIsIrrelevant(value: Int) = + new KoanIntWrapper(value) 19.isOdd should be(res0) 20.isOdd should be(res1) } /** Implicits rules can be imported into your scope with an import: - */ + */ def importedImplicits(res0: Boolean, res1: Boolean) { object MyPredef { @@ -72,7 +78,8 @@ object Implicits extends FlatSpec with Matchers with org.scalaexercises.definiti def isEven = !isOdd } - implicit def thisMethodNameIsIrrelevant(value: Int) = new KoanIntWrapper(value) + implicit def thisMethodNameIsIrrelevant(value: Int) = + new KoanIntWrapper(value) } import MyPredef._ @@ -82,14 +89,21 @@ object Implicits extends FlatSpec with Matchers with org.scalaexercises.definiti } /** Implicits can be used to automatically convert a value's type to another: - */ - def convertTypeImplicits(res0: Boolean, res1: Boolean, res2: Boolean, res3: Boolean, res4: Boolean) { + */ + def convertTypeImplicits( + res0: Boolean, + res1: Boolean, + res2: Boolean, + res3: Boolean, + res4: Boolean) { import java.math.BigInteger - implicit def Int2BigIntegerConvert(value: Int): BigInteger = new BigInteger(value.toString) + implicit def Int2BigIntegerConvert(value: Int): BigInteger = + new BigInteger(value.toString) def add(a: BigInteger, b: BigInteger) = a.add(b) - add(Int2BigIntegerConvert(3), Int2BigIntegerConvert(6)) == Int2BigIntegerConvert(9) should be(res0) + add(Int2BigIntegerConvert(3), Int2BigIntegerConvert(6)) == Int2BigIntegerConvert(9) should be( + res0) add(3, 6) == 9 should be(res1) add(3, 6) == Int2BigIntegerConvert(9) should be(res2) @@ -99,9 +113,10 @@ object Implicits extends FlatSpec with Matchers with org.scalaexercises.definiti } /** 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 howMuchCanIMake_?(hours: Int)(implicit dollarsPerHour: BigDecimal) = dollarsPerHour * hours + def howMuchCanIMake_?(hours: Int)(implicit dollarsPerHour: BigDecimal) = + dollarsPerHour * hours implicit val hourlyRate = BigDecimal(34) @@ -109,19 +124,19 @@ object Implicits extends FlatSpec with Matchers with org.scalaexercises.definiti } /** Implicit Function Parameters can contain a list of implicits: - */ + */ def listOfImplicitsImplicits(res0: String) { def howMuchCanIMake_?(hours: Int)(implicit amount: BigDecimal, currencyName: String) = (amount * hours).toString() + " " + currencyName - implicit val hourlyRate = BigDecimal(34) + implicit val hourlyRate = BigDecimal(34) implicit val currencyName = "Dollars" howMuchCanIMake_?(30) should be(res0) } /** Default arguments, though, are preferred to Implicit Function Parameters: - */ + */ 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 f6a04c90..14539d89 100644 --- a/src/main/scala/stdlib/InfixPrefixandPostfixOperators.scala +++ b/src/main/scala/stdlib/InfixPrefixandPostfixOperators.scala @@ -1,23 +1,31 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalatest._ import scala.language.postfixOps /** @param name infix_prefix_and_postfix_operators - * - */ -object InfixPrefixandPostfixOperators extends FlatSpec with Matchers with org.scalaexercises.definitions.Section { + * + */ +object InfixPrefixandPostfixOperators + extends FlatSpec + with Matchers + with org.scalaexercises.definitions.Section { /** 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) { 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 + g.+(4) should be(res1) // same result but not using the infix operator } /** Infix operators do NOT work if an object has a method that takes two parameters: - */ + */ def notWithTwoInfixPrefixandPostfixOperators(res0: Int, res1: Int) { val g: String = "Check out the big brains on Brad!" @@ -29,14 +37,14 @@ object InfixPrefixandPostfixOperators extends FlatSpec with Matchers with org.sc } /** Any method which does not require a parameter can be used as a postfix operator: `a.m` can be written as `a m`. - * - * For instance, `a.+(b)` is equivalent to `a + b` and `a.!` is the same as `a!`. - * - * Postfix operators have lower precedence than infix operators, so: - * - `foo bar baz` means `foo.bar(baz)`. - * - `foo bar baz bam` means `(foo.bar(baz)).bam` - * - `foo bar baz bam bim` means `(foo.bar(baz)).bam(bim)`. - */ + * + * For instance, `a.+(b)` is equivalent to `a + b` and `a.!` is the same as `a!`. + * + * Postfix operators have lower precedence than infix operators, so: + * - `foo bar baz` means `foo.bar(baz)`. + * - `foo bar baz bam` means `(foo.bar(baz)).bam` + * - `foo bar baz bam bim` means `(foo.bar(baz)).bam(bim)`. + */ 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. @@ -44,14 +52,14 @@ object InfixPrefixandPostfixOperators extends FlatSpec with Matchers with org.sc } /** Prefix operators work if an object has a method name that starts with `unary_` : - */ + */ 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) { class Stereo { def unary_+ = "on" diff --git a/src/main/scala/stdlib/InfixTypes.scala b/src/main/scala/stdlib/InfixTypes.scala index 93c0f154..6b5f595d 100644 --- a/src/main/scala/stdlib/InfixTypes.scala +++ b/src/main/scala/stdlib/InfixTypes.scala @@ -1,37 +1,41 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalatest._ /** @param name infix_types - * - */ + * + */ object InfixTypes extends FlatSpec with Matchers with org.scalaexercises.definitions.Section { /** An infix type `T1 op T2` consists of an infix operator `op` which gets applied to two - * type operands `T1` and `T2`. The type is equivalent to the type application `op[T1,T2]`. - * - * The infix operator `op` may be an arbitrary identifier, except for `*`, which is reserved - * as a postfix modifier denoting a repeated parameter type. - * - * 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: - */ + * type operands `T1` and `T2`. The type is equivalent to the type application `op[T1,T2]`. + * + * The infix operator `op` may be an arbitrary identifier, except for `*`, which is reserved + * as a postfix modifier denoting a repeated parameter type. + * + * 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) { case class Person(name: String) class Loves[A, B](val a: A, val b: B) - def announceCouple(couple: Person Loves Person) = { + def announceCouple(couple: Person Loves Person) = //Notice our type: Person loves Person! couple.a.name + " is in love with " + couple.b.name - } - val romeo = new Person("Romeo") + val romeo = new Person("Romeo") val juliet = new Person("Juliet") announceCouple(new Loves(romeo, juliet)) should be(res0) } /** 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) { case class Person(name: String) { def loves(person: Person) = new Loves(this, person) @@ -39,12 +43,11 @@ object InfixTypes extends FlatSpec with Matchers with org.scalaexercises.definit class Loves[A, B](val a: A, val b: B) - def announceCouple(couple: Person Loves Person) = { + def announceCouple(couple: Person Loves Person) = //Notice our type: Person loves Person! couple.a.name + " is in love with " + couple.b.name - } - val romeo = new Person("Romeo") + val romeo = new Person("Romeo") val juliet = new Person("Juliet") announceCouple(romeo loves juliet) should be(res0) diff --git a/src/main/scala/stdlib/Iterables.scala b/src/main/scala/stdlib/Iterables.scala index 0617bdd9..9e6cbcaf 100644 --- a/src/main/scala/stdlib/Iterables.scala +++ b/src/main/scala/stdlib/Iterables.scala @@ -1,82 +1,114 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalatest._ /** @param name iterables - * - */ + * + */ object Iterables extends FlatSpec with Matchers with org.scalaexercises.definitions.Section { /** The next trait from the top in the collections hierarchy is `Iterable`. All methods in this trait are defined in terms of an abstract method, `iterator`, which yields the collection's elements one by one. The `foreach` method from trait `Traversable` is implemented in `Iterable` in terms of `iterator`. Here is the actual implementation: - * - * {{{ - * def foreach[U](f: Elem => U): Unit = { - * val it = iterator - * while (it.hasNext) f(it.next()) - * } - * }}} - * - * Quite a few subclasses of `Iterable` override this standard implementation of `foreach` in `Iterable`, because they can provide a more efficient implementation. Remember that `foreach` is the basis of the implementation of all operations in `Traversable`, so its performance matters. - * - * 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 foreach[U](f: Elem => U): Unit = { + * val it = iterator + * while (it.hasNext) f(it.next()) + * } + * }}} + * + * Quite a few subclasses of `Iterable` override this standard implementation of `foreach` in `Iterable`, because they can provide a more efficient implementation. Remember that `foreach` is the basis of the implementation of all operations in `Traversable`, so its performance matters. + * + * 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) { val list = List(3, 5, 9, 11, 15, 19, 21) - val it = list.iterator + val it = list.iterator if (it.hasNext) { it.next should be(res0) } } /** `grouped` will return fixed-size `Iterable` chucks of an `Iterable`: - */ - def groupedIterables(res0: Int, res1: Int, res2: Int, res3: Int, res4: Int, res5: Int, res6: Int, res7: Int, res8: Int) { + */ + def groupedIterables( + res0: Int, + res1: Int, + res2: Int, + res3: Int, + res4: Int, + res5: Int, + res6: Int, + res7: Int, + res8: Int) { val list = List(3, 5, 9, 11, 15, 19, 21, 24, 32) - val it = list grouped 3 + val it = list grouped 3 it.next() should be(List(res0, res1, res2)) it.next() should be(List(res3, res4, res5)) it.next() should be(List(res6, res7, res8)) } /** `sliding` will return an `Iterable` that shows a sliding window of an `Iterable`. - */ - def slidingIterables(res0: Int, res1: Int, res2: Int, res3: Int, res4: Int, res5: Int, res6: Int, res7: Int, res8: Int) { + */ + def slidingIterables( + res0: Int, + res1: Int, + res2: Int, + res3: Int, + res4: Int, + res5: Int, + res6: Int, + res7: Int, + res8: Int) { val list = List(3, 5, 9, 11, 15, 19, 21, 24, 32) - val it = list sliding 3 + val it = list sliding 3 it.next() should be(List(res0, res1, res2)) it.next() should be(List(res3, res4, res5)) it.next() should be(List(res6, res7, res8)) } /** `sliding` can take the size of the window as well the size of the step during each iteration: - */ - def slidingWindowIterables(res0: Int, res1: Int, res2: Int, res3: Int, res4: Int, res5: Int, res6: Int, res7: Int, res8: Int) { + */ + def slidingWindowIterables( + res0: Int, + res1: Int, + res2: Int, + res3: Int, + res4: Int, + res5: Int, + res6: Int, + res7: Int, + res8: Int) { val list = List(3, 5, 9, 11, 15, 19, 21, 24, 32) - val it = list sliding (3, 3) + val it = list sliding (3, 3) it.next() should be(List(res0, res1, res2)) it.next() should be(List(res3, res4, res5)) it.next() should be(List(res6, res7, res8)) } /** `takeRight` is the opposite of 'take' in `Traversable`. It retrieves the last elements of an `Iterable`: - */ + */ 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) { val list = List(3, 5, 9, 11, 15, 19, 21, 24, 32) (list dropRight 3) should be(List(res0, res1, res2, res3, res4, res5)) } /** `zip` will stitch two iterables into an iterable of pairs of corresponding elements from both iterables. - * - * e.g. `Iterable(x1, x2, x3) zip Iterable(y1, y2, y3)` will return `((x1, y1), (x2, y2), (x3, y3))`: - */ + * + * 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) { val xs = List(3, 5, 9) val ys = List("Bob", "Ann", "Stella") @@ -84,10 +116,10 @@ object Iterables extends FlatSpec with Matchers with org.scalaexercises.definiti } /** If two Iterables aren't the same size, then `zip` will only zip what can be paired. - * - * e.g. `Iterable(x1, x2, x3) zip Iterable(y1, y2)` will return `((x1, y1), (x2, y2))`: - * - */ + * + * 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) { val xs = List(3, 5, 9) val ys = List("Bob", "Ann") @@ -95,10 +127,20 @@ object Iterables extends FlatSpec with Matchers with org.scalaexercises.definiti } /** If two `Iterables` aren't the same size, then `zipAll` can provide fillers for what it couldn't find a complement for. - * - * e.g. `Iterable(x1, x2, x3) zipAll (Iterable(y1, y2), x, y)` will return `((x1,y1), (x2, y2), (x3, y)))`: - */ - def zipAllIterables(res0: Int, res1: String, res2: Int, res3: String, res4: Int, res5: Int, res6: String, res7: Int, res8: String, res9: String) { + * + * e.g. `Iterable(x1, x2, x3) zipAll (Iterable(y1, y2), x, y)` will return `((x1,y1), (x2, y2), (x3, y)))`: + */ + def zipAllIterables( + res0: Int, + res1: String, + res2: Int, + res3: String, + res4: Int, + res5: Int, + res6: String, + res7: Int, + res8: 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, "?"))) @@ -110,14 +152,14 @@ object Iterables extends FlatSpec with Matchers with org.scalaexercises.definiti } /** `zipWithIndex` will zip an `Iterable` with its integer index: - */ + */ 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) { val xs = List("Manny", "Moe", "Jack") val ys = List("Manny", "Moe", "Jack") diff --git a/src/main/scala/stdlib/Lists.scala b/src/main/scala/stdlib/Lists.scala index 3523f7f4..94dd4414 100644 --- a/src/main/scala/stdlib/Lists.scala +++ b/src/main/scala/stdlib/Lists.scala @@ -1,16 +1,21 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalatest._ /** @param name lists - * - */ + * + */ object Lists extends FlatSpec with Matchers with org.scalaexercises.definitions.Section { /** Scala Lists are quite similar to arrays, which means all the elements of a list have the same type - but there are two important differences. First, lists are immutable, which means elements of a list cannot be changed by assignment. Second, lists represent a linked list whereas arrays are flat. The type of a list that has elements of type `T` is written as `List[T]`. - * - * `eq` tests identity (same object): - */ + * + * `eq` tests identity (same object): + */ def similarToArraysLists(res0: Boolean) { val a = List(1, 2, 3) val b = List(1, 2, 3) @@ -18,7 +23,7 @@ object Lists extends FlatSpec with Matchers with org.scalaexercises.definitions. } /** `==` tests equality (same content): - */ + */ def sameContentLists(res0: Boolean) { val a = List(1, 2, 3) val b = List(1, 2, 3) @@ -26,10 +31,16 @@ object Lists extends FlatSpec with Matchers with org.scalaexercises.definitions. } /** Nil lists are identical, even of different types: - */ - def nilListsLists(res0: Boolean, res1: Boolean, res2: Boolean, res3: Boolean, res4: Boolean, res5: Boolean) { + */ + def nilListsLists( + res0: Boolean, + res1: Boolean, + res2: Boolean, + res3: Boolean, + res4: Boolean, + res5: Boolean) { val a: List[String] = Nil - val b: List[Int] = Nil + val b: List[Int] = Nil (a == Nil) should be(res0) (a eq Nil) should be(res1) @@ -42,14 +53,14 @@ object Lists extends FlatSpec with Matchers with org.scalaexercises.definitions. } /** Lists can be easily created: - */ + */ 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) { val a = List(1, 2, 3) a.headOption should equal(Some(res0)) @@ -57,7 +68,7 @@ object Lists extends FlatSpec with Matchers with org.scalaexercises.definitions. } /** Lists can be accessed by position: - */ + */ def byPositionLists(res0: Int, res1: Int, res2: Int) { val a = List(1, 3, 5, 7, 9) a(0) should equal(res0) @@ -70,7 +81,7 @@ object Lists extends FlatSpec with Matchers with org.scalaexercises.definitions. } /** Lists are immutable: - */ + */ 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 @@ -80,7 +91,7 @@ object Lists extends FlatSpec with Matchers with org.scalaexercises.definitions. } /** Lists have many useful utility methods: - */ + */ def usefulMethodsLists(res0: Int, res1: List[Int], res2: List[Int], res3: List[Int]) { val a = List(1, 3, 5, 7, 9) @@ -91,14 +102,18 @@ object Lists extends FlatSpec with Matchers with org.scalaexercises.definitions. a.reverse should equal(res1) // map a function to double the numbers over the list - a.map { v ⇒ v * 2 } should equal(res2) + a.map { v ⇒ + v * 2 + } should equal(res2) // filter any values divisible by 3 in the list - a.filter { v ⇒ v % 3 == 0 } should equal(res3) + 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) { val a = List(1, 2, 3) @@ -112,7 +127,7 @@ object Lists extends FlatSpec with Matchers with org.scalaexercises.definitions. } /** Functions over lists can use `()` instead of `{}`: - */ + */ 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)) @@ -120,7 +135,7 @@ object Lists extends FlatSpec with Matchers with org.scalaexercises.definitions. } /** Lists can be reduced with a mathematical operation: - */ + */ def reducingListsLists(res0: Int, res1: Int) { val a = List(1, 3, 5, 7) a.reduceLeft(_ + _) should equal(res0) @@ -128,7 +143,7 @@ object Lists extends FlatSpec with Matchers with org.scalaexercises.definitions. } /** `foldLeft` is like `reduce`, but with an explicit starting value: - */ + */ 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 @@ -139,15 +154,21 @@ object Lists extends FlatSpec with Matchers with org.scalaexercises.definitions. } /** You can create a list from a range: - */ + */ def fromRangeLists(res0: List[Int]) { val a = (1 to 5).toList a should be(res0) } /** Lists reuse their tails: - */ - def reuseTailsLists(res0: Int, res1: Int, res2: Int, res3: List[Int], res4: List[Int], res5: List[Int]) { + */ + def reuseTailsLists( + res0: Int, + res1: Int, + res2: Int, + res3: List[Int], + res4: 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 7da3a570..2b16b9ea 100644 --- a/src/main/scala/stdlib/LiteralBooleans.scala +++ b/src/main/scala/stdlib/LiteralBooleans.scala @@ -1,15 +1,26 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalatest._ /** @param name literal_booleans - * - */ + * + */ object LiteralBooleans extends FlatSpec with Matchers with org.scalaexercises.definitions.Section { /** Boolean literals are either true or false, using the `true` or `false` keyword: - */ - def literalBooleanLiteralBooleans(res0: Boolean, res1: Boolean, res2: Boolean, res3: Boolean, res4: Boolean, res5: Boolean) { + */ + def literalBooleanLiteralBooleans( + res0: Boolean, + res1: Boolean, + res2: Boolean, + res3: Boolean, + res4: 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 5c933a3e..81bd1342 100644 --- a/src/main/scala/stdlib/LiteralNumbers.scala +++ b/src/main/scala/stdlib/LiteralNumbers.scala @@ -1,15 +1,27 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalatest._ /** @param name literal_numbers - * - */ + * + */ object LiteralNumbers extends FlatSpec with Matchers with org.scalaexercises.definitions.Section { /** Integer literals are 32-bit and can be created from decimals as well as hexadecimals: - */ - def integerLiteralsLiteralNumbers(res0: Int, res1: Int, res2: Int, res3: Int, res4: Int, res5: Int, res6: Int) { + */ + def integerLiteralsLiteralNumbers( + res0: Int, + res1: Int, + res2: Int, + res3: Int, + res4: Int, + res5: Int, + res6: Int) { val a = 2 val b = 31 val c = 0x30F @@ -27,8 +39,15 @@ object LiteralNumbers extends FlatSpec with Matchers with org.scalaexercises.def } /** Long literals are 64-bit. They are specified by appending an `L` or `l` at the end of the declaration: - */ - def longLiteralsLiteralNumbers(res0: Long, res1: Long, res2: Long, res3: Long, res4: Long, res5: Long, res6: Long) { + */ + def longLiteralsLiteralNumbers( + res0: Long, + res1: Long, + res2: Long, + res3: Long, + res4: Long, + res5: Long, + res6: Long) { val a = 2L val b = 31L val c = 0x30FL @@ -47,10 +66,19 @@ object LiteralNumbers extends FlatSpec with Matchers with org.scalaexercises.def } /** Float and Double literals conform to [[https://en.wikipedia.org/wiki/IEEE_floating_point IEEE-754]]. Floats are 32-bit, while doubles are 64-bit. - * Floats can be defined using a f or F suffix, while doubles use a d or D suffix. - * Exponents are specified using e or E. - */ - def floatsAndDoublesLiteralNumbers(res0: Double, res1: Double, res2: Double, res3: Double, res4: Double, res5: Double, res6: Double, res7: Double, res8: Double) { + * Floats can be defined using a f or F suffix, while doubles use a d or D suffix. + * Exponents are specified using e or E. + */ + def floatsAndDoublesLiteralNumbers( + res0: Double, + res1: Double, + res2: Double, + res3: Double, + res4: Double, + res5: Double, + res6: Double, + res7: 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 595fd3af..237d7146 100644 --- a/src/main/scala/stdlib/LiteralStrings.scala +++ b/src/main/scala/stdlib/LiteralStrings.scala @@ -1,14 +1,19 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalatest._ /** @param name literal_strings - * - */ + * + */ object LiteralStrings extends FlatSpec with Matchers with org.scalaexercises.definitions.Section { /** Character literals are quoted with single quotes: - */ + */ def characterLiteralsLiteralStrings(res0: String, res1: String) { val a = 'a' val b = 'B' @@ -18,7 +23,7 @@ object LiteralStrings extends FlatSpec with Matchers with org.scalaexercises.def } /** Character literals can use hexadecimal Unicode: - */ + */ def characterLiteralsUnicodeLiteralStrings(res0: String) { val c = '\u0061' //unicode for a @@ -26,14 +31,14 @@ object LiteralStrings extends FlatSpec with Matchers with org.scalaexercises.def } /** Character literals can use octal as well: - */ + */ def characterLiteralsOctalLiteralStrings(res0: String) { val d = '\141' //octal for a d.toString should be(res0) } /** Character literals can use escape sequences: - */ + */ def escapeSequenceLiteralStrings(res0: String, res1: String) { val e = '\"' val f = '\\' @@ -43,16 +48,16 @@ object LiteralStrings extends FlatSpec with Matchers with org.scalaexercises.def } /** One-line String literals are surrounded by quotation marks: - */ + */ def oneLineLiteralStrings(res0: String) { val a = "To be or not to be" a should be(res0) } - /* TODO rework exercise compiler issue where multiline string literals are not + /* TODO rework exercise compiler issue where multiline string literals are not /** multilineLiteralStrings - * - * Multiline String literals are surrounded by three quotation marks. - */ + * + * Multiline String literals are surrounded by three quotation marks. + */ def multilineLiteralStrings(res0: Int) { val a = """An apple a day @@ -61,14 +66,14 @@ object LiteralStrings extends FlatSpec with Matchers with org.scalaexercises.def } /** stripMarginLiteralStrings - * - * Use stripMargin to prettify multi-line strings: - * Multiline String literals can use | to specify the starting position - * of subsequent lines, then use stripMargin to remove the surplus indentation. - */ + * + * Use stripMargin to prettify multi-line strings: + * 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) { - val a = """An apple a day keeps + val a = """An apple a day keeps | the doctor away""" a.stripMargin.split('\n')(1).charAt(0) should be(res0) diff --git a/src/main/scala/stdlib/Maps.scala b/src/main/scala/stdlib/Maps.scala index 8e4fd055..db3cac53 100644 --- a/src/main/scala/stdlib/Maps.scala +++ b/src/main/scala/stdlib/Maps.scala @@ -1,46 +1,52 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalatest._ /** @param name maps - * - */ + * + */ object Maps extends FlatSpec with Matchers with org.scalaexercises.definitions.Section { /** A `Map` is an `Iterable` consisting of pairs of keys and values (also named mappings or associations). Scala's Predef class offers an implicit conversion that lets you write `key -> value` as an alternate syntax for the pair `(key, value)`. For instance `Map("x" -> 24, "y" -> 25, "z" -> 26)` means exactly the same as `Map(("x", 24), ("y", 25), ("z", 26))`, but reads better. - * - * The fundamental operations on maps are similar to those on sets. They are summarized in the following table and fall into the following categories: - * - * - Lookup operations `apply`, `get`, `getOrElse`, `contains`, and `isDefinedAt`. These turn maps into partial functions from keys to values. The fundamental lookup method for a map is: `def get(key): Option[Value]`. The operation "`m get key`" tests whether the map contains an association for the given key. If so, it returns the associated value in a `Some`. If no key is defined in the map, get returns `None`. Maps also define an `apply` method that returns the value associated with a given key directly, without wrapping it in an `Option`. If the key is not defined in the map, an exception is raised. - * - Additions and updates `+`, `++`, `updated`, which let you add new bindings to a map or change existing bindings. - * - Removals `-`, `--`, which remove bindings from a map. - * - Subcollection producers `keys`, `keySet`, `keysIterator`, `values`, `valuesIterator`, which return a map's keys and values separately in various forms. - * - Transformations `filterKeys` and `mapValues`, which produce a new map by filtering and transforming bindings of an existing map. - * - * Maps can be created easily: - */ + * + * The fundamental operations on maps are similar to those on sets. They are summarized in the following table and fall into the following categories: + * + * - Lookup operations `apply`, `get`, `getOrElse`, `contains`, and `isDefinedAt`. These turn maps into partial functions from keys to values. The fundamental lookup method for a map is: `def get(key): Option[Value]`. The operation "`m get key`" tests whether the map contains an association for the given key. If so, it returns the associated value in a `Some`. If no key is defined in the map, get returns `None`. Maps also define an `apply` method that returns the value associated with a given key directly, without wrapping it in an `Option`. If the key is not defined in the map, an exception is raised. + * - Additions and updates `+`, `++`, `updated`, which let you add new bindings to a map or change existing bindings. + * - Removals `-`, `--`, which remove bindings from a map. + * - Subcollection producers `keys`, `keySet`, `keysIterator`, `values`, `valuesIterator`, which return a map's keys and values separately in various forms. + * - Transformations `filterKeys` and `mapValues`, which produce a new map by filtering and transforming bindings of an existing map. + * + * Maps can be created easily: + */ def keyAndValueMaps(res0: Int) { - val myMap = Map("MI" → "Michigan", "OH" → "Ohio", "WI" → "Wisconsin", "IA" → "Iowa") + val myMap = + 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") 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 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") @@ -53,18 +59,19 @@ object Maps extends FlatSpec with Matchers with org.scalaexercises.definitions.S } - /** Maps may be accessed: - */ + /** Maps may be accessed: + */ def mayBeAccessedMaps(res0: String, res1: String) { - val myMap = Map("MI" → "Michigan", "OH" → "Ohio", "WI" → "Wisconsin", "IA" → "Iowa") + val myMap = + 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") + 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) @@ -72,7 +79,7 @@ object Maps extends FlatSpec with Matchers with org.scalaexercises.definitions.S } /** Map keys may be of mixed type: - */ + */ def mixedTypeKeysMaps(res0: String, res1: String) { val myMap = Map("Ann Arbor" → "MI", 49931 → "MI") myMap("Ann Arbor") should be(res0) @@ -80,10 +87,11 @@ object Maps extends FlatSpec with Matchers with org.scalaexercises.definitions.S } /** 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: - */ + * Default values may be provided using either `getOrElse` or `withDefaultValue` for the entire map: + */ def defaultValuesMayBeProvidedMaps(res0: String, res1: String) { - val myMap = Map("MI" → "Michigan", "OH" → "Ohio", "WI" → "Wisconsin", "IA" → "Iowa") + val myMap = + Map("MI" → "Michigan", "OH" → "Ohio", "WI" → "Wisconsin", "IA" → "Iowa") intercept[NoSuchElementException] { myMap("TX") } @@ -94,18 +102,20 @@ object Maps extends FlatSpec with Matchers with org.scalaexercises.definitions.S } /** Map elements can be removed easily: - */ + */ def easilyRemovedMaps(res0: Boolean, res1: Boolean) { - val myMap = Map("MI" → "Michigan", "OH" → "Ohio", "WI" → "Wisconsin", "IA" → "Iowa") + val myMap = + 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) } /** Map elements can be removed in multiple: - */ + */ def removedInMultipleMaps(res0: Boolean, res1: Boolean, res2: Boolean, res3: Int, res4: Int) { - val myMap = Map("MI" → "Michigan", "OH" → "Ohio", "WI" → "Wisconsin", "IA" → "Iowa") + val myMap = + Map("MI" → "Michigan", "OH" → "Ohio", "WI" → "Wisconsin", "IA" → "Iowa") val aNewMap = myMap -- List("MI", "OH") aNewMap.contains("MI") should be(res0) @@ -117,9 +127,10 @@ object Maps extends FlatSpec with Matchers with org.scalaexercises.definitions.S } /** 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 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) @@ -130,19 +141,22 @@ object Maps extends FlatSpec with Matchers with org.scalaexercises.definitions.S } /** Attempted removal of nonexistent elements from a map is handled gracefully: - */ + */ def attemptedRemovalMaps(res0: Boolean) { - val myMap = Map("MI" → "Michigan", "OH" → "Ohio", "WI" → "Wisconsin", "IA" → "Iowa") + val myMap = + Map("MI" → "Michigan", "OH" → "Ohio", "WI" → "Wisconsin", "IA" → "Iowa") val aNewMap = myMap - "MN" aNewMap.equals(myMap) should be(res0) } /** Map equivalency is independent of order: - */ + */ def orderIndependentMaps(res0: Boolean) { - val myMap1 = Map("MI" → "Michigan", "OH" → "Ohio", "WI" → "Wisconsin", "IA" → "Iowa") - val myMap2 = Map("WI" → "Wisconsin", "MI" → "Michigan", "IA" → "Iowa", "OH" → "Ohio") + val myMap1 = + Map("MI" → "Michigan", "OH" → "Ohio", "WI" → "Wisconsin", "IA" → "Iowa") + val myMap2 = + 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 cd225932..7ad20715 100644 --- a/src/main/scala/stdlib/NamedandDefaultArguments.scala +++ b/src/main/scala/stdlib/NamedandDefaultArguments.scala @@ -1,71 +1,79 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import NamedandDefaultArgumentsHelper._ import org.scalatest._ /** @param name named_and_default_arguments - * - */ -object NamedandDefaultArguments extends FlatSpec with Matchers with org.scalaexercises.definitions.Section { + * + */ +object NamedandDefaultArguments + extends FlatSpec + with Matchers + with org.scalaexercises.definitions.Section { /** When calling methods and functions, you can use the name of the variables explicitly in the call, like so: - * - * {{{ - * def printName(first:String, last:String) = { - * println(first + " " + last) - * } - * - * printName("John","Smith") // Prints "John Smith" - * printName(first = "John",last = "Smith") // Prints "John Smith" - * printName(last = "Smith",first = "John") // Prints "John Smith" - * }}} - * - * Note that once you are using parameter names in your calls, the order doesn't matter, so long as all parameters are named. This feature works well with default parameter values: - * - * {{{ - * def printName(first:String = "John", last:String = "Smith") = { - * println(first + " " + last) - * } - * printName(last = "Jones") // Prints "John Jones" - * }}} - * - * Given classes below: - * - * {{{ - * class WithoutClassParameters() { - * def addColors(red: Int, green: Int, blue: Int) = { - * (red, green, blue) - * } - * - * def addColorsWithDefaults(red: Int = 0, green: Int = 0, blue: Int = 0) = { - * (red, green, blue) - * } - * } - * - * 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) - * } - * - * def addColorsWithDefaults(red: Int = 0, green: Int = 0, blue: Int = 0) = { - * (red + defaultRed, green + defaultGreen, blue + defaultBlue) - * } - * } - * - * class WithClassParametersInClassDefinition(val defaultRed: Int = 0, val defaultGreen: Int = 255, val defaultBlue: Int = 100) { - * def addColors(red: Int, green: Int, blue: Int) = { - * (red + defaultRed, green + defaultGreen, blue + defaultBlue) - * } - * - * def addColorsWithDefaults(red: Int = 0, green: Int = 0, blue: Int = 0) = { - * (red + defaultRed, green + defaultGreen, blue + defaultBlue) - * } - * } - * - * }}} - * - * Can specify arguments in any order if you use their names: - */ + * + * {{{ + * def printName(first:String, last:String) = { + * println(first + " " + last) + * } + * + * printName("John","Smith") // Prints "John Smith" + * printName(first = "John",last = "Smith") // Prints "John Smith" + * printName(last = "Smith",first = "John") // Prints "John Smith" + * }}} + * + * Note that once you are using parameter names in your calls, the order doesn't matter, so long as all parameters are named. This feature works well with default parameter values: + * + * {{{ + * def printName(first:String = "John", last:String = "Smith") = { + * println(first + " " + last) + * } + * printName(last = "Jones") // Prints "John Jones" + * }}} + * + * Given classes below: + * + * {{{ + * class WithoutClassParameters() { + * def addColors(red: Int, green: Int, blue: Int) = { + * (red, green, blue) + * } + * + * def addColorsWithDefaults(red: Int = 0, green: Int = 0, blue: Int = 0) = { + * (red, green, blue) + * } + * } + * + * 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) + * } + * + * def addColorsWithDefaults(red: Int = 0, green: Int = 0, blue: Int = 0) = { + * (red + defaultRed, green + defaultGreen, blue + defaultBlue) + * } + * } + * + * class WithClassParametersInClassDefinition(val defaultRed: Int = 0, val defaultGreen: Int = 255, val defaultBlue: Int = 100) { + * def addColors(red: Int, green: Int, blue: Int) = { + * (red + defaultRed, green + defaultGreen, blue + defaultBlue) + * } + * + * def addColorsWithDefaults(red: Int = 0, green: Int = 0, blue: Int = 0) = { + * (red + defaultRed, green + defaultGreen, blue + defaultBlue) + * } + * } + * + * }}} + * + * Can specify arguments in any order if you use their names: + */ def classWithoutParametersNamedandDefaultArguments(res0: Int, res1: Int, res2: Int) { val me = new WithoutClassParameters() @@ -77,43 +85,43 @@ object NamedandDefaultArguments extends FlatSpec with Matchers with org.scalaexe } /** Can default arguments if you leave them off: - */ + */ def defaultArgumentsNamedandDefaultArguments(res0: Int, res1: Int, res2: Int) { - val me = new WithoutClassParameters() + val me = new WithoutClassParameters() val myColor = me.addColorsWithDefaults(green = 255) 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) { - val me = new WithClassParameters(40, 50, 60) + val me = new WithClassParameters(40, 50, 60) val myColor = me.addColors(green = 50, red = 60, blue = 40) 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) { - val me = new WithClassParameters(10, 20, 30) + val me = new WithClassParameters(10, 20, 30) val myColor = me.addColorsWithDefaults(green = 70) myColor should equal(res0, res1, res2) } /** Can default class parameters and have default arguments too: - */ + */ def defaultClassArgumentsNamedandDefaultArguments(res0: Int, res1: Int, res2: Int) { - val me = new WithClassParametersInClassDefinition() + val me = new WithClassParametersInClassDefinition() val myColor = me.addColorsWithDefaults(green = 70) myColor should equal(res0, res1, res2) } /** Default parameters can be functional too: - */ + */ def functionalDefaulParametersNamedandDefaultArguments(res0: Int, res1: Int) { def reduce(a: Int, f: (Int, Int) ⇒ Int = _ + _): Int = f(a, a) diff --git a/src/main/scala/stdlib/NamedandDefaultArgumentsHelper.scala b/src/main/scala/stdlib/NamedandDefaultArgumentsHelper.scala index 35e2b589..730576cf 100644 --- a/src/main/scala/stdlib/NamedandDefaultArgumentsHelper.scala +++ b/src/main/scala/stdlib/NamedandDefaultArgumentsHelper.scala @@ -1,35 +1,37 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib object NamedandDefaultArgumentsHelper { class WithoutClassParameters() { - def addColors(red: Int, green: Int, blue: Int) = { + def addColors(red: Int, green: Int, blue: Int) = (red, green, blue) - } - def addColorsWithDefaults(red: Int = 0, green: Int = 0, blue: Int = 0) = { + def addColorsWithDefaults(red: Int = 0, green: Int = 0, blue: Int = 0) = (red, green, blue) - } } class WithClassParameters(val defaultRed: Int, val defaultGreen: Int, val defaultBlue: Int) { - def addColors(red: Int, green: Int, blue: Int) = { + def addColors(red: Int, green: Int, blue: Int) = (red + defaultRed, green + defaultGreen, blue + defaultBlue) - } - def addColorsWithDefaults(red: Int = 0, green: Int = 0, blue: Int = 0) = { + def addColorsWithDefaults(red: Int = 0, green: Int = 0, blue: Int = 0) = (red + defaultRed, green + defaultGreen, blue + defaultBlue) - } } - class WithClassParametersInClassDefinition(val defaultRed: Int = 0, val defaultGreen: Int = 255, val defaultBlue: Int = 100) { - def addColors(red: Int, green: Int, blue: Int) = { + class WithClassParametersInClassDefinition( + val defaultRed: Int = 0, + val defaultGreen: Int = 255, + val defaultBlue: Int = 100) { + def addColors(red: Int, green: Int, blue: Int) = (red + defaultRed, green + defaultGreen, blue + defaultBlue) - } - def addColorsWithDefaults(red: Int = 0, green: Int = 0, blue: Int = 0) = { + def addColorsWithDefaults(red: Int = 0, green: Int = 0, blue: Int = 0) = (red + defaultRed, green + defaultGreen, blue + defaultBlue) - } } } diff --git a/src/main/scala/stdlib/Objects.scala b/src/main/scala/stdlib/Objects.scala index a44d62da..c773bf3a 100644 --- a/src/main/scala/stdlib/Objects.scala +++ b/src/main/scala/stdlib/Objects.scala @@ -1,14 +1,19 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalatest._ /** @param name objects - * - */ + * + */ object Objects extends FlatSpec with Matchers with org.scalaexercises.definitions.Section { /** 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) { object Greeting { def english = "Hi" @@ -22,7 +27,7 @@ object Objects extends FlatSpec with Matchers with org.scalaexercises.definition } /** Here is a proof that an object is a singleton, and not a static method in a class: - */ + */ def notStaticMethodObjects(res0: Boolean, res1: Boolean) { object Greeting { def english = "Hi" @@ -41,7 +46,7 @@ object Objects extends FlatSpec with Matchers with org.scalaexercises.definition } /** 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) { class Movie(val name: String, val year: Short) @@ -61,7 +66,7 @@ object Objects extends FlatSpec with Matchers with org.scalaexercises.definition } /** A companion object can also see private values and variables of the corresponding classes' instantiated objects: - */ + */ def privateValuesObjects(res0: String, res1: String) { class Person(val name: String, private val superheroName: String) //The superhero name is private! diff --git a/src/main/scala/stdlib/Options.scala b/src/main/scala/stdlib/Options.scala index dba5dee9..d253a628 100644 --- a/src/main/scala/stdlib/Options.scala +++ b/src/main/scala/stdlib/Options.scala @@ -1,19 +1,24 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import OptionsHelper._ import org.scalatest._ /** @param name options - * - */ + * + */ object Options extends FlatSpec with Matchers with org.scalaexercises.definitions.Section { /** If you have worked with Java at all in the past, it is very likely that you have come across a `NullPointerException` at some time (other languages will throw similarly named errors in such a case). Usually this happens because some method returns null when you were not expecting it and thus not dealing with that possibility in your client code. A value of `null` is often abused to represent an absent optional value. - * - * Scala tries to solve the problem by getting rid of `null` values altogether and providing its own type for representing optional values, i.e. values that may be present or not: the `Option[A]` trait. - * - * `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`. - */ + * + * Scala tries to solve the problem by getting rid of `null` values altogether and providing its own type for representing optional values, i.e. values that may be present or not: the `Option[A]` trait. + * + * `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]) { val someValue: Option[String] = Some("I am wrapped in something") someValue should be(res0) @@ -23,15 +28,15 @@ object Options extends FlatSpec with Matchers with org.scalaexercises.definition } /** Let's write a function that may or not give us a string, thus returning `Option[String]`: - * - * {{{ - * def maybeItWillReturnSomething(flag: Boolean): Option[String] = { - * if (flag) Some("Found value") else None - * } - * }}} - * - * Using `getOrElse` we can provide a default value ("No value") when the optional argument (`None`) does not exist: - */ + * + * {{{ + * def maybeItWillReturnSomething(flag: Boolean): Option[String] = { + * if (flag) Some("Found value") else None + * } + * }}} + * + * Using `getOrElse` we can provide a default value ("No value") when the optional argument (`None`) does not exist: + */ def getOrElseOptions(res0: String, res1: String, res2: String) { val value1 = maybeItWillReturnSomething(true) val value2 = maybeItWillReturnSomething(false) @@ -45,7 +50,7 @@ object Options extends FlatSpec with Matchers with org.scalaexercises.definition } /** Checking whether option has value: - */ + */ def isEmptyOptions(res0: Boolean, res1: Boolean) { val value1 = maybeItWillReturnSomething(true) val value2 = maybeItWillReturnSomething(false) @@ -55,7 +60,7 @@ object Options extends FlatSpec with Matchers with org.scalaexercises.definition } /** Option can also be used with pattern matching: - */ + */ def matchOptions(res0: Double, res1: Double) { val someValue: Option[Double] = Some(20.0) val value = someValue match { @@ -72,15 +77,15 @@ object Options extends FlatSpec with Matchers with org.scalaexercises.definition } /** An alternative for pattern matching is performing collection style operations. - * This is possible because an option could be looked at as a collection with either one or zero elements. - * - * One of these operations is `map`. This operation allows us to map the inner value to a different type while preserving the option: - */ + * This is possible because an option could be looked at as a collection with either one or zero elements. + * + * 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]) { - val number: Option[Int] = Some(3) + val number: Option[Int] = Some(3) val noNumber: Option[Int] = None - val result1 = number.map(_ * 1.5) - val result2 = noNumber.map(_ * 1.5) + val result1 = number.map(_ * 1.5) + val result2 = noNumber.map(_ * 1.5) result1 should be(res0) result2 should be(res1) @@ -89,12 +94,12 @@ object Options extends FlatSpec with Matchers with org.scalaexercises.definition } /** 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) { - val number: Option[Int] = Some(3) + val number: Option[Int] = Some(3) val noNumber: Option[Int] = None - val result1 = number.fold(0)(_ * 3) - val result2 = noNumber.fold(0)(_ * 3) + val result1 = number.fold(0)(_ * 3) + val result2 = noNumber.fold(0)(_ * 3) result1 should be(res0) result2 should be(res1) diff --git a/src/main/scala/stdlib/OptionsHelper.scala b/src/main/scala/stdlib/OptionsHelper.scala index 22974057..41c9ac5f 100644 --- a/src/main/scala/stdlib/OptionsHelper.scala +++ b/src/main/scala/stdlib/OptionsHelper.scala @@ -1,9 +1,13 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib object OptionsHelper { - def maybeItWillReturnSomething(flag: Boolean): Option[String] = { + def maybeItWillReturnSomething(flag: Boolean): Option[String] = if (flag) Some("Found value") else None - } } diff --git a/src/main/scala/stdlib/ParentClasses.scala b/src/main/scala/stdlib/ParentClasses.scala index 56a2a87b..02a8378e 100644 --- a/src/main/scala/stdlib/ParentClasses.scala +++ b/src/main/scala/stdlib/ParentClasses.scala @@ -1,34 +1,39 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalatest._ /** @param name parent_classes - * - */ + * + */ object ParentClasses extends FlatSpec with Matchers with org.scalaexercises.definitions.Section { /** In contrast to Java, all values in Scala are objects (including numerical values and functions). Since Scala is class-based, all values are instances of a class. - * - * Class hierarchy is linear, a class can only extend from one parent class: - * - */ + * + * Class hierarchy is linear, a class can only extend from one parent class: + * + */ 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) + class Pilot(override val firstName: String, override val lastName: String, val squadron: Long) + extends Soldier(firstName, lastName) val pilot = new Pilot("John", "Yossarian", 256) pilot.firstName should be(res0) pilot.lastName should be(res1) } /** A class that extends from another is polymorphic: - */ + */ 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) + class Pilot(override val firstName: String, override val lastName: String, val squadron: Long) + extends Soldier(firstName, lastName) - val pilot = new Pilot("John", "Yossarian", 256) + val pilot = new Pilot("John", "Yossarian", 256) val soldier: Soldier = pilot soldier.firstName should be(res0) @@ -36,16 +41,16 @@ object ParentClasses extends FlatSpec with Matchers with org.scalaexercises.defi } /** An abstract class, as in Java, cannot be instantiated and only inherited: - * - * {{{ - * abstract class Soldier(val firstName: String, val lastName: String) {} - * - * // if you uncomment this line, it will fail compilation - * //val soldier = new Soldier - * }}} - * - * A class can be placed inside an abstract class just like in Java: - */ + * + * {{{ + * abstract class Soldier(val firstName: String, val lastName: String) {} + * + * // if you uncomment this line, it will fail compilation + * //val soldier = new Soldier + * }}} + * + * A class can be placed inside an abstract class just like in Java: + */ def abstractClassParentClasses(res0: Int) { abstract class Soldier(val firstName: String, val lastName: String) { @@ -54,10 +59,10 @@ object ParentClasses extends FlatSpec with Matchers with org.scalaexercises.defi } } - class Pilot(override val firstName: String, override val lastName: String, - val squadron: Long) extends Soldier(firstName, lastName) + class Pilot(override val firstName: String, override val lastName: String, val squadron: Long) + extends Soldier(firstName, lastName) - val pilot = new Pilot("John", "Yossarian", 256) + val pilot = new Pilot("John", "Yossarian", 256) val catchNo = new pilot.Catch(22) //using the pilot instance's path, create an catch object for it. catchNo.number should be(res0) } diff --git a/src/main/scala/stdlib/PartialFunctions.scala b/src/main/scala/stdlib/PartialFunctions.scala index dc188d94..5ccadf0c 100644 --- a/src/main/scala/stdlib/PartialFunctions.scala +++ b/src/main/scala/stdlib/PartialFunctions.scala @@ -1,22 +1,31 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalatest._ /** @param name partial_functions - * - */ -object PartialFunctions extends FlatSpec with Matchers with org.scalaexercises.definitions.Section { + * + */ +object PartialFunctions + extends FlatSpec + with Matchers + with org.scalaexercises.definitions.Section { /** 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) { - val doubleEvens: PartialFunction[Int, Int] = new PartialFunction[Int, Int] { - //States that this partial function will take on the task - def isDefinedAt(x: Int) = x % 2 == 0 + val doubleEvens: PartialFunction[Int, Int] = + new PartialFunction[Int, Int] { + //States that this partial function will take on the task + def isDefinedAt(x: Int) = x % 2 == 0 - //What we do if this partial function matches - def apply(v1: Int) = v1 * 2 - } + //What we do if this partial function matches + def apply(v1: Int) = v1 * 2 + } val tripleOdds: PartialFunction[Int, Int] = new PartialFunction[Int, Int] { def isDefinedAt(x: Int) = x % 2 != 0 @@ -31,7 +40,7 @@ object PartialFunctions extends FlatSpec with Matchers with org.scalaexercises.d } /** 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) { //These case statements are called case statements with guards val doubleEvens: PartialFunction[Int, Int] = { @@ -47,7 +56,7 @@ object PartialFunctions extends FlatSpec with Matchers with org.scalaexercises.d } /** The result of partial functions can have an `andThen` function added to the end of the chain: - */ + */ def andThenPartialFunctions(res0: Int, res1: Int) { //These are called case statements with guards val doubleEvens: PartialFunction[Int, Int] = { @@ -57,14 +66,14 @@ object PartialFunctions extends FlatSpec with Matchers with org.scalaexercises.d 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) } /** `andThen` can be used to continue onto another chain of logic: - */ + */ def chainOfLogicPartialFunctions(res0: String, res1: String) { val doubleEvens: PartialFunction[Int, Int] = { case x if (x % 2) == 0 ⇒ x * 2 diff --git a/src/main/scala/stdlib/PartiallyAppliedFunctions.scala b/src/main/scala/stdlib/PartiallyAppliedFunctions.scala index 998cddbb..7fba07cf 100644 --- a/src/main/scala/stdlib/PartiallyAppliedFunctions.scala +++ b/src/main/scala/stdlib/PartiallyAppliedFunctions.scala @@ -1,33 +1,46 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalatest._ /** @param name partially_applied_functions - * - */ -object PartiallyAppliedFunctions extends FlatSpec with Matchers with org.scalaexercises.definitions.Section { + * + */ +object PartiallyAppliedFunctions + extends FlatSpec + with Matchers + with org.scalaexercises.definitions.Section { /** 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 sum(a: Int, b: Int, c: Int) = a + b + c - val sum3 = sum _ + val sum3 = sum _ sum3(1, 9, 7) should be(res0) sum(4, 5, 6) should be(res1) } /** Partially applied functions can replace any number of arguments: - */ + */ def anyNumberArgumentsPartiallyAppliedFunctions(res0: Int, res1: Int) { def sum(a: Int, b: Int, c: Int) = a + b + c - val sumC = sum(1, 10, _: Int) + val sumC = sum(1, 10, _: Int) sumC(4) should be(res0) sum(4, 5, 6) should be(res1) } /** 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 @@ -39,13 +52,12 @@ object PartiallyAppliedFunctions extends FlatSpec with Matchers with org.scalaex } /** 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 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) + val xs = List(12, 11, 5, 20, 3, 13, 2) customFilter(onlyEven)(xs) should be(res0) val onlyEvenFilter = customFilter(onlyEven) _ diff --git a/src/main/scala/stdlib/PatternMatching.scala b/src/main/scala/stdlib/PatternMatching.scala index b6b13492..5f5621b3 100644 --- a/src/main/scala/stdlib/PatternMatching.scala +++ b/src/main/scala/stdlib/PatternMatching.scala @@ -1,33 +1,38 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalatest._ /** @param name pattern_matching - * - */ + * + */ object PatternMatching extends FlatSpec with Matchers with org.scalaexercises.definitions.Section { /** Scala has a built-in general pattern matching mechanism. It allows to match on any sort of data with a first-match policy. - * Here is a small example which shows how to match against an integer value: - * - * {{{ - * object MatchTest1 extends App { - * def matchTest(x: Int): String = x match { - * case 1 => "one" - * case 2 => "two" - * case _ => "many" // case _ will trigger if all other cases fail. - * } - * println(matchTest(3)) // prints "many" - * } - * }}} - * - * The block with the `case` statements defines a function which maps integers to strings. The `match` keyword provides a convenient way of applying a function (like the pattern matching function above) to an object. - * - * Scala's pattern matching statement is most useful for matching on algebraic types expressed via `case classes`. - * Scala also allows the definition of patterns independently of case classes, using `unapply` methods in extractor objects. - * - * Pattern matching returns something: - */ + * Here is a small example which shows how to match against an integer value: + * + * {{{ + * object MatchTest1 extends App { + * def matchTest(x: Int): String = x match { + * case 1 => "one" + * case 2 => "two" + * case _ => "many" // case _ will trigger if all other cases fail. + * } + * println(matchTest(3)) // prints "many" + * } + * }}} + * + * The block with the `case` statements defines a function which maps integers to strings. The `match` keyword provides a convenient way of applying a function (like the pattern matching function above) to an object. + * + * Scala's pattern matching statement is most useful for matching on algebraic types expressed via `case classes`. + * Scala also allows the definition of patterns independently of case classes, using `unapply` methods in extractor objects. + * + * Pattern matching returns something: + */ def patternMatchingMechanismPatternMatching(res0: Int) { val stuff = "blue" @@ -38,14 +43,15 @@ object PatternMatching extends FlatSpec with Matchers with org.scalaexercises.de println("BLUE"); 2 case "green" ⇒ println("GREEN"); 3 - case _ ⇒ println(stuff); 0 // case _ will trigger if all other cases fail. + case _ ⇒ + println(stuff); 0 // case _ will trigger if all other cases fail. } myStuff should be(res0) } /** Pattern matching can return complex values: - */ + */ def returnComplexPatternMatching(res0: Int, res1: Int, res2: Int) { val stuff = "blue" @@ -60,7 +66,7 @@ object PatternMatching extends FlatSpec with Matchers with org.scalaexercises.de } /** Pattern matching can match complex expressions: - */ + */ def complexExpressionsPatternMatching(res0: String) { def goldilocks(expr: Any) = expr match { case ("porridge", "Papa") ⇒ "Papa eating porridge" @@ -73,7 +79,7 @@ object PatternMatching extends FlatSpec with Matchers with org.scalaexercises.de } /** Pattern matching can wildcard parts of expressions: - */ + */ def wildcardParsPatternMatching(res0: String, res1: String) { def goldilocks(expr: Any) = expr match { case ("porridge", _) ⇒ "eating" @@ -87,13 +93,14 @@ object PatternMatching extends FlatSpec with Matchers with org.scalaexercises.de } /** Pattern matching can substitute parts of expressions: - */ + */ def substitutePartsPatternMatching(res0: String, res1: String) { def goldilocks(expr: Any) = 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 ("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?" } goldilocks(("porridge", "Papa")) should be(res0) @@ -123,7 +130,7 @@ object PatternMatching extends FlatSpec with Matchers with org.scalaexercises.de // } /** 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) { val foodItem = "porridge" @@ -141,7 +148,7 @@ object PatternMatching extends FlatSpec with Matchers with org.scalaexercises.de } /** 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 patternEquals(i: Int, j: Int) = j match { case `i` ⇒ true @@ -153,7 +160,7 @@ object PatternMatching extends FlatSpec with Matchers with org.scalaexercises.de } /** 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) { val secondElement = List(1, 2, 3) match { case x :: xs ⇒ xs.head @@ -164,7 +171,7 @@ object PatternMatching extends FlatSpec with Matchers with org.scalaexercises.de } /** 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) { val secondElement = List(1, 2, 3) match { case x :: y :: xs ⇒ y @@ -175,7 +182,7 @@ object PatternMatching extends FlatSpec with Matchers with org.scalaexercises.de } /** Same koan as above, but we are pattern matching a list with only one item! - */ + */ def againstListsIIIPatternMatching(res0: Int) { val secondElement = List(1) match { case x :: y :: xs ⇒ y // only matches a list with two or more items @@ -186,7 +193,7 @@ object PatternMatching extends FlatSpec with Matchers with org.scalaexercises.de } /** 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) { val r = List(1, 2, 3) match { case x :: y :: Nil ⇒ y // only matches a list with exactly two items @@ -197,11 +204,11 @@ object PatternMatching extends FlatSpec with Matchers with org.scalaexercises.de } /** If a pattern is exactly one element longer than a `List`, it extracts the final `Nil`: - */ + */ def againstListsVPatternMatching(res0: Boolean) { val r = List(1, 2, 3) match { case x :: y :: z :: tail ⇒ tail - case _ ⇒ 0 + case _ ⇒ 0 } r == Nil should be(res0) diff --git a/src/main/scala/stdlib/Ranges.scala b/src/main/scala/stdlib/Ranges.scala index fc6ce8e0..b4a4b915 100644 --- a/src/main/scala/stdlib/Ranges.scala +++ b/src/main/scala/stdlib/Ranges.scala @@ -1,24 +1,29 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalatest._ /** @param name ranges - * - */ + * + */ object Ranges extends FlatSpec with Matchers with org.scalaexercises.definitions.Section { /** A Range is an ordered sequence of integers that are equally spaced apart. For example, "1, 2, 3" is a range, as is "5, 8, 11, 14". To create a range in Scala, use the predefined methods `to` and `by`. `1 to 3` generates `Range(1, 2, 3)` and `5 to 14 by 3` generates `Range(5, 8, 11, 14)`. - * - * If you want to create a range that is exclusive of its upper limit, then use the convenience method `until` instead of `to`: `1 until 3` generates `Range(1, 2)`. - * - * Ranges are represented in constant space, because they can be defined by just three numbers: their start, their end, and the stepping value. Because of this representation, most operations on ranges are extremely fast. + * + * If you want to create a range that is exclusive of its upper limit, then use the convenience method `until` instead of `to`: `1 until 3` generates `Range(1, 2)`. + * + * Ranges are represented in constant space, because they can be defined by just three numbers: their start, their end, and the stepping value. Because of this representation, most operations on ranges are extremely fast. * - * A range's upper bound is not inclusive: - */ + * A range's upper bound is not inclusive: + */ def upperNotInclusiveRangeExercises(res0: Int, res1: Int, res2: Int) { val someNumbers = Range(0, 10) - val second = someNumbers(1) - val last = someNumbers.last + val second = someNumbers(1) + val last = someNumbers.last someNumbers.size should be(res0) second should be(res1) @@ -26,20 +31,20 @@ object Ranges extends FlatSpec with Matchers with org.scalaexercises.definitions } /** Ranges can be specified using 'until': - */ + */ def untilRangeExercises(res0: Boolean) { val someNumbers = Range(0, 10) - val otherRange = 0 until 10 + val otherRange = 0 until 10 (someNumbers == otherRange) should be(res0) } /** Range can specify a step for an increment: - */ + */ def incrementsRangeExercises(res0: Int, res1: Int, res2: Int) { val someNumbers = Range(2, 10, 3) - val second = someNumbers(1) - val last = someNumbers.last + val second = someNumbers(1) + val last = someNumbers.last someNumbers.size should be(res0) second should be(res1) @@ -47,7 +52,7 @@ object Ranges extends FlatSpec with Matchers with org.scalaexercises.definitions } /** A range does not include its upper bound, even in a step increment: - */ + */ def upperInIncrementRangeExercises(res0: Boolean, res1: Boolean, res2: Boolean) { val someNumbers = Range(0, 34, 2) someNumbers.contains(33) should be(res0) @@ -56,7 +61,7 @@ object Ranges extends FlatSpec with Matchers with org.scalaexercises.definitions } /** Range can specify to include its upper bound value: - */ + */ def specifyUpperRangeExercises(res0: Boolean) { val someNumbers = Range(0, 34).inclusive @@ -64,10 +69,10 @@ object Ranges extends FlatSpec with Matchers with org.scalaexercises.definitions } /** Inclusive ranges can be specified using 'to': - */ + */ def inclusiveWithToRangeExercises(res0: Boolean) { val someNumbers = Range(0, 34).inclusive - val otherRange = 0 to 34 + val otherRange = 0 to 34 (someNumbers == otherRange) should be(res0) } diff --git a/src/main/scala/stdlib/RepeatedParameters.scala b/src/main/scala/stdlib/RepeatedParameters.scala index bce99fa9..f63ac78c 100644 --- a/src/main/scala/stdlib/RepeatedParameters.scala +++ b/src/main/scala/stdlib/RepeatedParameters.scala @@ -1,39 +1,52 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import RepeatedParametersHelper._ import org.scalatest._ /** @param name repeated_parameters - * - */ -object RepeatedParameters extends FlatSpec with Matchers with org.scalaexercises.definitions.Section { + * + */ +object RepeatedParameters + extends FlatSpec + with Matchers + with org.scalaexercises.definitions.Section { /** A repeated parameter must be the last parameter and this will let you add as many extra parameters as needed. - * - * Given: - * - * {{{ - * def repeatedParameterMethod(x: Int, y: String, z: Any*) = { - * "%d %ss can give you %s".format(x, y, z.mkString(", ")) - * } - * }}} - * Resolve: - * - */ + * + * Given: + * + * {{{ + * def repeatedParameterMethod(x: Int, y: String, z: Any*) = { + * "%d %ss can give you %s".format(x, y, z.mkString(", ")) + * } + * }}} + * Resolve: + * + */ def theLastParameterRepeatedParameters(res0: String) { - repeatedParameterMethod(3, "egg", "a delicious sandwich", "protein", "high cholesterol") should be(res0) + 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) { - repeatedParameterMethod(3, "egg", List("a delicious sandwich", "protein", "high cholesterol")) should be(res0) + 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) { - repeatedParameterMethod(3, "egg", List("a delicious sandwich", "protein", "high cholesterol"): _*) should be(res0) + repeatedParameterMethod( + 3, + "egg", + List("a delicious sandwich", "protein", "high cholesterol"): _*) should be(res0) } } diff --git a/src/main/scala/stdlib/RepeatedParametersHelper.scala b/src/main/scala/stdlib/RepeatedParametersHelper.scala index 6d36c0b4..3b50c83e 100644 --- a/src/main/scala/stdlib/RepeatedParametersHelper.scala +++ b/src/main/scala/stdlib/RepeatedParametersHelper.scala @@ -1,8 +1,12 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib object RepeatedParametersHelper { - def repeatedParameterMethod(x: Int, y: String, z: Any*) = { + def repeatedParameterMethod(x: Int, y: String, z: Any*) = "%d %ss can give you %s".format(x, y, z.mkString(", ")) - } } diff --git a/src/main/scala/stdlib/SequencesandArrays.scala b/src/main/scala/stdlib/SequencesandArrays.scala index 9bdeccf4..8ffa82b6 100644 --- a/src/main/scala/stdlib/SequencesandArrays.scala +++ b/src/main/scala/stdlib/SequencesandArrays.scala @@ -1,16 +1,24 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalatest._ /** @param name sequences_and_arrays - * - */ -object SequencesandArrays extends FlatSpec with Matchers with org.scalaexercises.definitions.Section { + * + */ +object SequencesandArrays + extends FlatSpec + with Matchers + with org.scalaexercises.definitions.Section { /** Scala provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. - * - * A list can be converted to an array: - */ + * + * A list can be converted to an array: + */ def sequentialCollectionSequencesandArrays(res0: Int, res1: Int, res2: Int) { val l = List(1, 2, 3) val a = l.toArray @@ -18,10 +26,10 @@ object SequencesandArrays extends FlatSpec with Matchers with org.scalaexercises } /** Sequences are special cases of iterable collections of class `Iterable`. Unlike iterables, sequences always have a defined order of elements. - * - * Any sequence can be converted to a list: - * - */ + * + * Any sequence can be converted to a list: + * + */ def orderedElementsSequencesandArrays(res0: List[Int]) { val a = Array(1, 2, 3) val s = a.toSeq @@ -30,37 +38,37 @@ object SequencesandArrays extends FlatSpec with Matchers with org.scalaexercises } /** You can create a sequence from a `for` loop: - */ + */ 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 s.toList should be(res0) } /** You can filter any sequence based on a predicate: - */ + */ def filterPredicateSequencesandArrays(res0: String, res1: String) { - val s = Seq("hello", "to", "you") + val s = Seq("hello", "to", "you") val filtered = s.filter(_.length > 2) filtered should be(Seq(res0, res1)) } /** You can also filter Arrays in the same way: - */ + */ def filterArraySequencesandArrays(res0: String, res1: String) { - val a = Array("hello", "to", "you", "again") + val a = Array("hello", "to", "you", "again") val filtered = a.filter(_.length > 3) filtered should be(Array(res0, res1)) } /** You can map values in a sequence through a function: - */ + */ def mapValuesSequencesandArrays(res0: List[String]) { val s = Seq("hello", "world") val r = s map { diff --git a/src/main/scala/stdlib/Sets.scala b/src/main/scala/stdlib/Sets.scala index ba3b3f54..5a685d89 100644 --- a/src/main/scala/stdlib/Sets.scala +++ b/src/main/scala/stdlib/Sets.scala @@ -1,37 +1,42 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalatest._ /** @param name sets - * - */ + * + */ object Sets extends FlatSpec with Matchers with org.scalaexercises.definitions.Section { /** `Set`s are `Iterable`s that contain no duplicate elements. The operations on sets are summarized in the following table for general sets and in the table after that for mutable sets. They fall into the following categories: - * - * - **Tests**: `contains`, `apply`, `subsetOf`. The `contains` method asks whether a set contains a given element. The `apply` method for a set is the same as `contains`, so `set(elem)` is the same as `set contains elem`. That means sets can also be used as test functions that return true for the elements they contain. - * - **Additions**: `+` and `++`, which add one or more elements to a set, yielding a new set. - * - **Removals**: `-`, `--`, which remove one or more elements from a set, yielding a new set. - * - **Set operations**: union, intersection, and set difference. Each of these operations exists in two forms: alphabetic and symbolic. The alphabetic versions are `intersect`, `union`, and `diff`, whereas the symbolic versions are `&`, `|`, and `&~`. In fact, the `++` that Set inherits from `Traversable` can be seen as yet another alias of `union` or `|`, except that `++` takes a `Traversable` argument whereas `union` and `|` take sets. - * - * Sets can be created easily: - */ + * + * - **Tests**: `contains`, `apply`, `subsetOf`. The `contains` method asks whether a set contains a given element. The `apply` method for a set is the same as `contains`, so `set(elem)` is the same as `set contains elem`. That means sets can also be used as test functions that return true for the elements they contain. + * - **Additions**: `+` and `++`, which add one or more elements to a set, yielding a new set. + * - **Removals**: `-`, `--`, which remove one or more elements from a set, yielding a new set. + * - **Set operations**: union, intersection, and set difference. Each of these operations exists in two forms: alphabetic and symbolic. The alphabetic versions are `intersect`, `union`, and `diff`, whereas the symbolic versions are `&`, `|`, and `&~`. In fact, the `++` that Set inherits from `Traversable` can be seen as yet another alias of `union` or `|`, except that `++` takes a `Traversable` argument whereas `union` and `|` take sets. + * + * Sets can be created easily: + */ def noDuplicatesSets(res0: Int) { val mySet = Set("Michigan", "Ohio", "Wisconsin", "Iowa") mySet.size should be(res0) } /** Sets contain distinct values: - */ + */ 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) { - val mySet = Set("Michigan", "Ohio", "Wisconsin", "Iowa") + val mySet = Set("Michigan", "Ohio", "Wisconsin", "Iowa") val aNewSet = mySet + "Illinois" aNewSet.contains("Illinois") should be(res0) @@ -39,7 +44,7 @@ object Sets extends FlatSpec with Matchers with org.scalaexercises.definitions.S } /** Sets may be of mixed type: - */ + */ def mixedTypeSets(res0: Boolean, res1: Boolean) { val mySet = Set("Michigan", "Ohio", 12) @@ -48,7 +53,7 @@ object Sets extends FlatSpec with Matchers with org.scalaexercises.definitions.S } /** Sets can be checked for member existence: - */ + */ def checkExistenceSets(res0: Boolean, res1: Boolean) { val mySet = Set("Michigan", "Ohio", 12) @@ -57,9 +62,9 @@ object Sets extends FlatSpec with Matchers with org.scalaexercises.definitions.S } /** Set elements can be removed easily: - */ + */ def easilyRemovedSets(res0: Boolean, res1: Boolean) { - val mySet = Set("Michigan", "Ohio", "Wisconsin", "Iowa") + val mySet = Set("Michigan", "Ohio", "Wisconsin", "Iowa") val aNewSet = mySet - "Michigan" aNewSet.contains("Michigan") should be(res0) @@ -67,9 +72,9 @@ object Sets extends FlatSpec with Matchers with org.scalaexercises.definitions.S } /** Set elements can be removed in multiple: - */ + */ def multipleRemovingSets(res0: Boolean, res1: Boolean, res2: Int) { - val mySet = Set("Michigan", "Ohio", "Wisconsin", "Iowa") + val mySet = Set("Michigan", "Ohio", "Wisconsin", "Iowa") val aNewSet = mySet -- List("Michigan", "Ohio") aNewSet.contains("Michigan") should be(res0) @@ -78,9 +83,9 @@ object Sets extends FlatSpec with Matchers with org.scalaexercises.definitions.S } /** Set elements can be removed with a tuple: - */ + */ def tupleRemovingSets(res0: Boolean, res1: Boolean, res2: Int) { - val mySet = Set("Michigan", "Ohio", "Wisconsin", "Iowa") + val mySet = Set("Michigan", "Ohio", "Wisconsin", "Iowa") val aNewSet = mySet - ("Michigan", "Ohio") // Notice: single '-' operator for tuples aNewSet.contains("Michigan") should be(res0) @@ -89,19 +94,19 @@ object Sets extends FlatSpec with Matchers with org.scalaexercises.definitions.S } /** Attempted removal of nonexistent elements from a set is handled gracefully: - */ + */ def nonexistentRemovalSets(res0: Boolean) { - val mySet = Set("Michigan", "Ohio", "Wisconsin", "Iowa") + val mySet = Set("Michigan", "Ohio", "Wisconsin", "Iowa") val aNewSet = mySet - "Minnesota" aNewSet.equals(mySet) should be(res0) } /** Two sets can be intersected easily: - */ + */ def easilyIntersectedSets(res0: Boolean) { - val mySet1 = Set("Michigan", "Ohio", "Wisconsin", "Iowa") - val mySet2 = Set("Wisconsin", "Michigan", "Minnesota") + 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 @@ -109,17 +114,17 @@ object Sets extends FlatSpec with Matchers with org.scalaexercises.definitions.S } /** Two sets can be joined as their union easily: - */ + */ def easilyJoinedSets(res0: Boolean) { - val mySet1 = Set("Michigan", "Ohio", "Wisconsin", "Iowa") - val mySet2 = Set("Wisconsin", "Michigan", "Minnesota") + 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 aNewSet.equals(Set("Michigan", "Wisconsin", "Ohio", "Iowa", "Minnesota")) should be(res0) } /** A set is either a subset of another set or it isn't: - */ + */ def subsetSets(res0: Boolean, res1: Boolean) { val mySet1 = Set("Michigan", "Ohio", "Wisconsin", "Iowa") val mySet2 = Set("Wisconsin", "Michigan", "Minnesota") @@ -130,17 +135,17 @@ object Sets extends FlatSpec with Matchers with org.scalaexercises.definitions.S } /** The difference between two sets can be obtained easily: - */ + */ def easilyObtainedDifferencesSets(res0: Boolean) { - val mySet1 = Set("Michigan", "Ohio", "Wisconsin", "Iowa") - val mySet2 = Set("Wisconsin", "Michigan") + 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. aNewSet.equals(Set("Ohio", "Iowa")) should be(res0) } /** Set equivalency is independent of order: - */ + */ 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/StdLib.scala b/src/main/scala/stdlib/StdLib.scala index 1421e654..8ae45e8d 100644 --- a/src/main/scala/stdlib/StdLib.scala +++ b/src/main/scala/stdlib/StdLib.scala @@ -1,16 +1,16 @@ /* - * scala-exercises-content + * scala-exercises - exercises-stdlib * Copyright (C) 2015-2016 47 Degrees, LLC. */ package stdlib /** Scala fuses object-oriented and functional programming in a statically typed programming language. - * - * @param name std_lib - */ + * + * @param name std_lib + */ object StdLib extends org.scalaexercises.definitions.Library { - override def owner = "scala-exercises" + override def owner = "scala-exercises" override def repository = "exercises-stdlib" override def color = Some("#26525B") diff --git a/src/main/scala/stdlib/Traits.scala b/src/main/scala/stdlib/Traits.scala index 82deed77..9898dc38 100644 --- a/src/main/scala/stdlib/Traits.scala +++ b/src/main/scala/stdlib/Traits.scala @@ -1,26 +1,31 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalatest._ /** @param name traits - */ + */ object Traits extends FlatSpec with Matchers with org.scalaexercises.definitions.Section { /** Similar to interfaces in Java, traits are used to define object types by specifying the signature of the supported methods. Unlike Java, Scala allows traits to be partially implemented; i.e. it is possible to define default implementations for some methods. In contrast to classes, traits may not have constructor parameters. - * - * Here is an example: - * - * {{{ - * trait Similarity { - * def isSimilar(x: Any): Boolean - * def isNotSimilar(x: Any): Boolean = !isSimilar(x) - * } - * }}} - * - * This trait consists of two methods `isSimilar` and `isNotSimilar`. While `isSimilar` does not provide a concrete method implementation (it is abstract in the terminology of Java), method `isNotSimilar` defines a concrete implementation. Consequently, classes that integrate this trait only have to provide a concrete implementation for `isSimilar`. The behavior for `isNotSimilar` gets inherited directly from the trait. - * - * A class uses the `extends` keyword to mixin a trait if it is the only relationship the class inherits: - */ + * + * Here is an example: + * + * {{{ + * trait Similarity { + * def isSimilar(x: Any): Boolean + * def isNotSimilar(x: Any): Boolean = !isSimilar(x) + * } + * }}} + * + * This trait consists of two methods `isSimilar` and `isNotSimilar`. While `isSimilar` does not provide a concrete method implementation (it is abstract in the terminology of Java), method `isNotSimilar` defines a concrete implementation. Consequently, classes that integrate this trait only have to provide a concrete implementation for `isSimilar`. The behavior for `isNotSimilar` gets inherited directly from the trait. + * + * A class uses the `extends` keyword to mixin a trait if it is the only relationship the class inherits: + */ def similarToInterfacesTraits(res0: String) { case class Event(name: String) @@ -31,19 +36,20 @@ object Traits extends FlatSpec with Matchers with org.scalaexercises.definitions class MyListener extends EventListener { def listen(event: Event): String = { event match { - case Event("Moose Stampede") ⇒ "An unfortunate moose stampede occurred" - case _ ⇒ "Nothing of importance occurred" + case Event("Moose Stampede") ⇒ + "An unfortunate moose stampede occurred" + case _ ⇒ "Nothing of importance occurred" } } } - val evt = Event("Moose Stampede") + val evt = Event("Moose Stampede") val myListener = new MyListener myListener.listen(evt) should be(res0) } /** A class can only extend from one class or trait, any subsequent extension should use the keyword `with`: - */ + */ def extendsFromOneTraits(res0: String) { case class Event(name: String) @@ -56,19 +62,20 @@ object Traits extends FlatSpec with Matchers with org.scalaexercises.definitions class MyListener extends OurListener with EventListener { def listen(event: Event): String = { event match { - case Event("Woodchuck Stampede") ⇒ "An unfortunate woodchuck stampede occurred" - case _ ⇒ "Nothing of importance occurred" + case Event("Woodchuck Stampede") ⇒ + "An unfortunate woodchuck stampede occurred" + case _ ⇒ "Nothing of importance occurred" } } } - val evt = Event("Woodchuck Stampede") + val evt = Event("Woodchuck Stampede") val myListener = new MyListener myListener.listen(evt) should be(res0) } /** 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) { case class Event(name: String) @@ -79,8 +86,9 @@ object Traits extends FlatSpec with Matchers with org.scalaexercises.definitions class MyListener extends EventListener { def listen(event: Event): String = { event match { - case Event("Moose Stampede") ⇒ "An unfortunate moose stampede occurred" - case _ ⇒ "Nothing of importance occurred" + case Event("Moose Stampede") ⇒ + "An unfortunate moose stampede occurred" + case _ ⇒ "Nothing of importance occurred" } } } diff --git a/src/main/scala/stdlib/Traversables.scala b/src/main/scala/stdlib/Traversables.scala index cb7cf9b5..f46d9ef5 100644 --- a/src/main/scala/stdlib/Traversables.scala +++ b/src/main/scala/stdlib/Traversables.scala @@ -1,3 +1,8 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalatest._ @@ -6,24 +11,24 @@ import scala.language.postfixOps import Stream.cons /** @param name traversables - */ + */ object Traversables extends FlatSpec with Matchers with org.scalaexercises.definitions.Section { /** At the top of the collection hierarchy is the trait `Traversable`. Its only abstract operation is `foreach`: - * - * {{{ - * def foreach[U](f: Elem => U) - * }}} - * - * Collection classes that implement `Traversable` just need to define this method; all other methods can be inherited from `Traversable`. - * - * The `foreach` method is meant to traverse all elements of the collection, and apply the given operation, `f`, to each element. The type of the operation is `Elem => U`, where `Elem` is the type of the collection's elements and `U` is an arbitrary result type. The invocation of `f` is done for its side effect only; in fact any function result of `f` is discarded by `foreach`. - * - * 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. - */ + * + * {{{ + * def foreach[U](f: Elem => U) + * }}} + * + * Collection classes that implement `Traversable` just need to define this method; all other methods can be inherited from `Traversable`. + * + * The `foreach` method is meant to traverse all elements of the collection, and apply the given operation, `f`, to each element. The type of the operation is `Elem => U`, where `Elem` is the type of the collection's elements and `U` is an arbitrary result type. The invocation of `f` is done for its side effect only; in fact any function result of `f` is discarded by `foreach`. + * + * 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. + */ def topOfCollectionTraversables(res0: Int, res1: Int) { - val set = Set(1, 9, 10, 22) - val list = List(3, 4, 5, 10) + val set = Set(1, 9, 10, 22) + val list = List(3, 4, 5, 10) val result = set ++ list result.size should be(res0) @@ -32,38 +37,38 @@ object Traversables extends FlatSpec with Matchers with org.scalaexercises.defin } /** `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]) { - val set = Set(1, 3, 4, 6) + val set = Set(1, 3, 4, 6) val result = set.map(_ * 4) result.lastOption should be(res0) } /** `flatten` will "pack" all child `Traversables` into a single `Traversable`: - */ + */ 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]) { - val list = List(List(1), List(2, 3, 4), List(5, 6, 7), List(8, 9, 10)) + 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) } /** `flatMap` of `Options` will filter out all `None`s but keep the `Some`s: - */ + */ def flatMapOfOptionsTraversables(res0: List[Int]) { - val list = List(1, 2, 3, 4, 5) + val list = List(1, 2, 3, 4, 5) 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]) { val list = List(4, 6, 7, 8, 9, 13, 14) val result = list.collect { @@ -73,7 +78,7 @@ object Traversables extends FlatSpec with Matchers with org.scalaexercises.defin } /** Two case fragments can be chained to create a more robust result: - */ + */ def collectFunctionIITraversables(res0: List[Int]) { val list = List(4, 6, 7, 8, 9, 13, 14) val partialFunction1: PartialFunction[Int, Int] = { @@ -87,7 +92,7 @@ object Traversables extends FlatSpec with Matchers with org.scalaexercises.defin } /** `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]) { val list = List(4, 6, 7, 8, 9, 13, 14) list.foreach(num ⇒ println(num * 4)) @@ -95,89 +100,89 @@ object Traversables extends FlatSpec with Matchers with org.scalaexercises.defin } /** `toArray` will convert any `Traversable` to an `Array`, which is a special wrapper around a primitive Java array: - */ + */ def toArrayFunctionTraversables(res0: Boolean) { - val set = Set(4, 6, 7, 8, 9, 13, 14) + val set = Set(4, 6, 7, 8, 9, 13, 14) val result = set.toArray result.isInstanceOf[Array[Int]] should be(res0) } /** `toList` will convert any `Traversable` to a `List`. - */ + */ def toListFunctionTraversables(res0: Boolean) { - val set = Set(4, 6, 7, 8, 9, 13, 14) + val set = Set(4, 6, 7, 8, 9, 13, 14) val result = set.toList result.isInstanceOf[List[_]] should be(res0) } /** `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) { - val list = List(5, 6, 7, 8, 9) + val list = List(5, 6, 7, 8, 9) val result = list.toList result eq list should be(res0) } /** `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) { - val set = Set(4, 6, 7, 8, 9, 13, 14) + val set = Set(4, 6, 7, 8, 9, 13, 14) val result = set.toIterable result.isInstanceOf[Iterable[_]] should be(res0) } /** `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) { - val set = Set(4, 6, 7, 8, 9, 13, 14) + val set = Set(4, 6, 7, 8, 9, 13, 14) val result = set.toSeq result.isInstanceOf[Seq[_]] should be(res0) } /** `toIndexedSeq` will convert any `Traversable` to an `IndexedSeq` which is an indexed sequence used in `Vectors` and `Strings`: - */ + */ def toIndexedSeqFunctionTraversables(res0: Boolean) { - val set = Set(4, 6, 7, 8, 9, 13, 14) + 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: - */ + */ def toStreamFunctionTraversables(res0: Boolean, res1: Stream[Int]) { - val list = List(4, 6, 7, 8, 9, 13, 14) + val list = List(4, 6, 7, 8, 9, 13, 14) val result = list.toStream result.isInstanceOf[Stream[_]] 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) { - val list = List(4, 6, 7, 8, 9, 13, 14) + val list = List(4, 6, 7, 8, 9, 13, 14) val result = list.toSet result.isInstanceOf[Set[_]] should be(res0) } /** `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") + 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") + 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") map.isEmpty should be(res0) @@ -187,7 +192,7 @@ object Traversables extends FlatSpec with Matchers with org.scalaexercises.defin } /** `nonEmpty` is pretty self-evident too: - */ + */ def nonEmptyFunctionTraversables(res0: Boolean, res1: Boolean) { val map = Map("Phoenix" → "Arizona", "Austin" → "Texas") map.nonEmpty should be(res0) @@ -197,14 +202,14 @@ object Traversables extends FlatSpec with Matchers with org.scalaexercises.defin } /** `size` provides the size of the traversable: - */ + */ 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`: - */ + */ def hasDefiniteSizeFunctionTraversables(res0: Boolean, res1: Boolean) { val map = Map("Phoenix" → "Arizona", "Austin" → "Texas") map.hasDefiniteSize should be(res0) @@ -214,14 +219,14 @@ object Traversables extends FlatSpec with Matchers with org.scalaexercises.defin } /** `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) { 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]) { val list = List(10, 19, 45, 1, 22) list.headOption should be(res0) @@ -231,14 +236,14 @@ object Traversables extends FlatSpec with Matchers with org.scalaexercises.defin } /** `last` will return the last element of an ordered collection, or some random element if order is not defined: - */ + */ 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]) { val list = List(10, 19, 45, 1, 22) list.lastOption should be(res0) @@ -248,7 +253,7 @@ object Traversables extends FlatSpec with Matchers with org.scalaexercises.defin } /** `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]) { val list = List(10, 19, 45, 1, 22) list.find(_ % 2 != 0) should be(res0) @@ -258,106 +263,106 @@ object Traversables extends FlatSpec with Matchers with org.scalaexercises.defin } /** `tail` will return the rest of the collection without the head: - */ + */ 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]) { 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]) { 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]) { 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`: - */ + */ def takeFunctionIITraversables(res0: List[Int]) { def streamer(v: Int): Stream[Int] = cons(v, streamer(v + 1)) - val a = streamer(2) + val a = streamer(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) + val a = streamer(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]) { 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]) { 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]) { 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]) { 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]) { - val array = Array(87, 44, 5, 4, 200, 10, 39, 100) + val array = Array(87, 44, 5, 4, 200, 10, 39, 100) val result = array splitAt 3 result._1 should be(res0) result._2 should be(res1) } /** `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]) { - val array = Array(87, 44, 5, 4, 200, 10, 39, 100) + val array = Array(87, 44, 5, 4, 200, 10, 39, 100) val result = array span (_ < 100) result._1 should be(res0) result._2 should be(res1) } /** `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]) { - val array = Array(87, 44, 5, 4, 200, 10, 39, 100) + val array = Array(87, 44, 5, 4, 200, 10, 39, 100) val result = array partition (_ < 100) result._1 should be(res0) result._2 should be(res1) } /** `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) { val array = Array(87, 44, 5, 4, 200, 10, 39, 100) @@ -394,42 +399,42 @@ object Traversables extends FlatSpec with Matchers with org.scalaexercises.defin } /** `forall` will determine if a predicate is valid for all members of a `Traversable`: - */ + */ def forallFunctionTraversables(res0: Boolean) { - val list = List(87, 44, 5, 4, 200, 10, 39, 100) + val list = List(87, 44, 5, 4, 200, 10, 39, 100) val result = list forall (_ < 100) result should be(res0) } /** `exists` will determine if a predicate is valid for some members of a `Traversable`: - */ + */ def existsFunctionTraversables(res0: Boolean) { - val list = List(87, 44, 5, 4, 200, 10, 39, 100) + val list = List(87, 44, 5, 4, 200, 10, 39, 100) val result = list exists (_ < 100) result should be(res0) } /** `count` will count the number of elements that satisfy a predicate in a `Traversable`: - */ + */ def countFunctionTraversables(res0: Int) { - val list = List(87, 44, 5, 4, 200, 10, 39, 100) + val list = List(87, 44, 5, 4, 200, 10, 39, 100) val result = list count (_ < 100) result should be(res0) } /** `/:` or `foldLeft` will combine an operation starting with a seed and combining from the left. `foldLeft` is defined as (seed /: list), where seed is the initial value. Once the fold is established, you provide a function that takes two arguments. The first argument is the running total of the operation, and the second element is the next element of the list. - * - * 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)` - */ + * + * 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, res3: Int, res4: Int) { val list = List(5, 4, 3, 2, 1) - val result = (0 /: list) { - (`running total`, `next element`) ⇒ `running total` - `next element` + val result = (0 /: list) { (`running total`, `next element`) ⇒ + `running total` - `next element` } result should be(res0) - val result2 = list.foldLeft(0) { - (`running total`, `next element`) ⇒ `running total` - `next element` + val result2 = list.foldLeft(0) { (`running total`, `next element`) ⇒ + `running total` - `next element` } result2 should be(res1) @@ -443,18 +448,18 @@ object Traversables extends FlatSpec with Matchers with org.scalaexercises.defin } /** `:\` or `foldRight` will combine an operation starting with a seed and combining from the right. Fold right is defined as (list :\ seed), where seed is the initial value. Once the fold is established, you provide a function that takes two elements. The first is the next element of the list, and the second element is the running total of the operation. - * - * 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)))` - */ + * + * 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, res3: Int, res4: Int) { val list = List(5, 4, 3, 2, 1) - val result = (list :\ 0) { - (`next element`, `running total`) ⇒ `next element` - `running total` + val result = (list :\ 0) { (`next element`, `running total`) ⇒ + `next element` - `running total` } result should be(res0) - val result2 = list.foldRight(0) { - (`next element`, `running total`) ⇒ `next element` - `running total` + val result2 = list.foldRight(0) { (`next element`, `running total`) ⇒ + `next element` - `running total` } result2 should be(res1) @@ -468,7 +473,7 @@ object Traversables extends FlatSpec with Matchers with org.scalaexercises.defin } /** `reduceLeft` is similar to `foldLeft`, except that the seed is the head value: - */ + */ def reduceLeftFunctionTraversables(res0: Int, res1: String) { val intList = List(5, 4, 3, 2, 1) intList.reduceLeft { @@ -482,7 +487,7 @@ object Traversables extends FlatSpec with Matchers with org.scalaexercises.defin } /** `reduceRight` is similar to `foldRight`, except that the seed is the last value: - */ + */ def reduceRightFunctionTraversables(res0: Int, res1: String) { val intList = List(5, 4, 3, 2, 1) intList.reduceRight { @@ -496,7 +501,7 @@ object Traversables extends FlatSpec with Matchers with org.scalaexercises.defin } /** 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) { val intList = List(5, 4, 3, 2, 1) intList.sum should be(res0) @@ -506,9 +511,9 @@ object Traversables extends FlatSpec with Matchers with org.scalaexercises.defin } /** You would choose `foldLeft`/`reduceLeft` or `foldRight`/`reduceRight` based on your mathematical goal. One other reason for deciding is performance - `foldLeft` generally has better performance since it uses tail recursion. This exercise will either work fine or you will receive a `StackOverflowError`: - */ + */ def performantTraversables(res0: Boolean) { - val MAX_SIZE = 1000000 + val MAX_SIZE = 1000000 val reduceLeftStartTime = new java.util.Date (1 to MAX_SIZE) reduceLeft (_ + _) val reduceLeftEndTime = new java.util.Date @@ -518,16 +523,21 @@ object Traversables extends FlatSpec with Matchers with org.scalaexercises.defin val reduceRightEndTime = new java.util.Date val totalReduceLeftTime = reduceLeftEndTime.getTime - reduceLeftStartTime.getTime - val totalReduceRightTime = reduceRightEndTime.getTime - reduceRightStartTime.getTime + val totalReduceRightTime = reduceRightEndTime.getTime - reduceRightStartTime + .getTime (totalReduceRightTime > totalReduceLeftTime) should be(res0) } /** `transpose` will take a traversable of traversables and group them by their position in it's own traversable, e.g.: - * `((x1, x2),(y1, y2)).transpose = (x1, y1), (x2, y2)` or - * `((x1, x2, x3),(y1, y2, y3),(z1, z2, z3)).transpose = ((x1, y1, z1), (x2, y2, z2), (x3, y3, z3))` - */ - def transposeFunctionTraversables(res0: List[Int], res1: List[Int], res2: List[Int], res3: List[Int]) { + * `((x1, x2),(y1, y2)).transpose = (x1, y1), (x2, y2)` or + * `((x1, x2, x3),(y1, y2, y3),(z1, z2, z3)).transpose = ((x1, y1, z1), (x2, y2, z2), (x3, y3, z3))` + */ + def transposeFunctionTraversables( + res0: List[Int], + res1: List[Int], + res2: 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)) @@ -536,24 +546,24 @@ object Traversables extends FlatSpec with Matchers with org.scalaexercises.defin } /** `mkString` will format a `Traversable` using a given string as the delimiter: - */ + */ 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) { 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) { val stringBuilder = new StringBuilder() - val list = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15) + 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, ",") stringBuilder.mkString should be(res0) diff --git a/src/main/scala/stdlib/Tuples.scala b/src/main/scala/stdlib/Tuples.scala index 75ba6875..ca5bd704 100644 --- a/src/main/scala/stdlib/Tuples.scala +++ b/src/main/scala/stdlib/Tuples.scala @@ -1,3 +1,8 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import java.util.Date @@ -5,26 +10,26 @@ import java.util.Date import org.scalatest._ /** @param name tuples - * - */ + * + */ object Tuples extends FlatSpec with Matchers with org.scalaexercises.definitions.Section { /** Scala tuple combines a fixed number of items together so that they can be passed around as a whole. They are one-indexed. Unlike an array or list, a tuple can hold objects with different types but they are also immutable. Here is an example of a tuple holding an integer, a string, and the console: - * - * {{{ - * val t = (1, "hello", Console) - * }}} - * - * Which is syntactic sugar (short cut) for the following: - * - * {{{ - * val t = new Tuple3(1, "hello", Console) - * }}} - * As you can see, tuples can be created easily: - */ + * + * {{{ + * val t = (1, "hello", Console) + * }}} + * + * Which is syntactic sugar (short cut) for the following: + * + * {{{ + * val t = new Tuple3(1, "hello", Console) + * }}} + * As you can see, tuples can be created easily: + */ def oneIndexedTuples(res0: String, res1: String) { - val tuple = ("apple", "dog") - val fruit = tuple._1 + val tuple = ("apple", "dog") + val fruit = tuple._1 val animal = tuple._2 fruit should be(res0) @@ -32,7 +37,7 @@ object Tuples extends FlatSpec with Matchers with org.scalaexercises.definitions } /** Tuples may be of mixed type: - */ + */ def mixedTypeTuples(res0: Int, res1: String) { val tuple5 = ("a", 1, 2.2, new Date(), "five") @@ -41,9 +46,9 @@ object Tuples extends FlatSpec with Matchers with org.scalaexercises.definitions } /** You can assign multiple variables at once using tuples: - */ + */ def assignVariablesTuples(res0: String, res1: Int, res2: Double) { - val student = ("Sean Rogers", 21, 3.5) + val student = ("Sean Rogers", 21, 3.5) val (name, age, gpa) = student name should be(res0) @@ -52,7 +57,7 @@ object Tuples extends FlatSpec with Matchers with org.scalaexercises.definitions } /** The `swap` method can be used to swap the elements of a Tuple2: - */ + */ def swappedTuples(res0: Int, res1: String) { val tuple = ("apple", 3).swap tuple._1 should be(res0) diff --git a/src/main/scala/stdlib/TypeSignatures.scala b/src/main/scala/stdlib/TypeSignatures.scala index f1673cfc..3e98f5e2 100644 --- a/src/main/scala/stdlib/TypeSignatures.scala +++ b/src/main/scala/stdlib/TypeSignatures.scala @@ -1,28 +1,33 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalatest._ /** @param name type_signatures - */ + */ object TypeSignatures extends FlatSpec with Matchers with org.scalaexercises.definitions.Section { /** A method's type signature comprises its name; the number, order, and types of its parameters, if any; and its result type. The type signature of a class, trait, or singleton object comprises its name, the type signatures of all of its members and constructors, and its declared inheritance and mixin relations. - * - * In Java you declare a generic type within a `<>`, in Scala `[]` is used: - * - * {{{ - * val z: List[String] = "Do" :: "Re" :: "Mi" :: "Fa" :: "So" :: "La" :: "Te" :: "Do" :: Nil - * }}} - * - * Most of the time, Scala will infer the type and `[]` are optional: - * - * {{{ - * val z = "Do" :: "Re" :: "Mi" :: "Fa" :: "So" :: "La" :: "Te" :: "Do" :: Nil //Infers that the list assigned to variable is of type List[String] - * }}} - * - * A trait can be declared containing a type, where a concrete implementer will satisfy the type: - * - */ + * + * In Java you declare a generic type within a `<>`, in Scala `[]` is used: + * + * {{{ + * val z: List[String] = "Do" :: "Re" :: "Mi" :: "Fa" :: "So" :: "La" :: "Te" :: "Do" :: Nil + * }}} + * + * Most of the time, Scala will infer the type and `[]` are optional: + * + * {{{ + * val z = "Do" :: "Re" :: "Mi" :: "Fa" :: "So" :: "La" :: "Te" :: "Do" :: Nil //Infers that the list assigned to variable is of type List[String] + * }}} + * + * A trait can be declared containing a type, where a concrete implementer will satisfy the type: + * + */ def typeSignatureTypeSignatures(res0: Boolean) { trait Randomizer[A] { def draw(): A @@ -40,14 +45,14 @@ object TypeSignatures extends FlatSpec with Matchers with org.scalaexercises.def } /** Class meta-information can be retrieved by class name by using `classOf[className]`: - */ + */ 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) { val zoom = "zoom" zoom.isInstanceOf[String] should be(res0) @@ -56,7 +61,7 @@ object TypeSignatures extends FlatSpec with Matchers with org.scalaexercises.def } /** `isInstanceOf[className]` is used to determine the if an object reference is an instance of given class: - */ + */ def isInstanceOfFunctionTypeSignatures(res0: Boolean) { trait Randomizer[A] { def draw(): A diff --git a/src/main/scala/stdlib/TypeVariance.scala b/src/main/scala/stdlib/TypeVariance.scala index 6f1b4dab..fe2ef968 100644 --- a/src/main/scala/stdlib/TypeVariance.scala +++ b/src/main/scala/stdlib/TypeVariance.scala @@ -1,20 +1,25 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import TypeVarianceHelper._ import org.scalatest._ /** @param name type_variance - */ + */ object TypeVariance extends FlatSpec with Matchers with org.scalaexercises.definitions.Section { /** A traditional objection to static typing is that it has much syntactic overhead. Scala alleviates this by providing type inference. - * - * The classic method for type inference in functional programming languages is Hindley-Milner, and it was first employed in ML. - * - * Scala's type inference system works a little differently, but it's similar in spirit: infer constraints, and attempt to unify a type. - * - * Using type inference the type that you instantiate will be the val or var reference type: - */ + * + * The classic method for type inference in functional programming languages is Hindley-Milner, and it was first employed in ML. + * + * Scala's type inference system works a little differently, but it's similar in spirit: infer constraints, and attempt to unify a type. + * + * Using type inference the type that you instantiate will be the val or var reference type: + */ def syntacticOverheadTypeVariance(res0: String) { class MyContainer[A](val a: A)(implicit manifest: scala.reflect.Manifest[A]) { def contents = manifest.runtimeClass.getSimpleName @@ -25,7 +30,7 @@ object TypeVariance extends FlatSpec with Matchers with org.scalaexercises.defin } /** You can explicitly declare the type variable of the object during instantiation: - */ + */ def typeVariableTypeVariance(res0: String) { class MyContainer[A](val a: A)(implicit manifest: scala.reflect.Manifest[A]) { def contents = manifest.runtimeClass.getSimpleName @@ -36,7 +41,7 @@ object TypeVariance extends FlatSpec with Matchers with org.scalaexercises.defin } /** You can coerce your object to a type: - */ + */ def coerceObjectTypeVariance(res0: String) { class MyContainer[A](val a: A)(implicit manifest: scala.reflect.Manifest[A]) { def contents = manifest.runtimeClass.getSimpleName @@ -47,33 +52,33 @@ object TypeVariance extends FlatSpec with Matchers with org.scalaexercises.defin } /** Scala's type system has to account for class hierarchies together with polymorphism. Class hierarchies allow the expression of subtype relationships. A central question that comes up when mixing OO with polymorphism is: if `T'` is a subclass of `T`, is `Container[T']` considered a subclass of `Container[T]`? Variance annotations allow you to express the following relationships between class hierarchies & polymorphic types: - * - * ==Covariant== - * - `C[T']` is a subclass of `C[T]` - * - Scala notation: `[+T]` - * - * ==Contravariant== - * - `C[T]` is a subclass of `C[T']` - * - Scala notation: `[-T]` - * - * ==Invariant== - * - `C[T]` and `C[T']` are not related - * - Scala notation: `[T]` - * - * - * That one probably blew your mind. Now if you assign a type to the instantiation that is different to the variable type, you'll have problems. You may want to take time after this koan to compare and contrast with the previous one. - * - * {{{ - * class MyContainer[A](val a: A)(implicit manifest: scala.reflect.Manifest[A]) { - * def contents = manifest.runtimeClass.getSimpleName - * } - * - * // Uncomment the following line - * // val fruitBasket:MyContainer[Fruit] = new MyContainer[Orange](new Orange()) - * }}} - * - * 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]`. - */ + * + * ==Covariant== + * - `C[T']` is a subclass of `C[T]` + * - Scala notation: `[+T]` + * + * ==Contravariant== + * - `C[T]` is a subclass of `C[T']` + * - Scala notation: `[-T]` + * + * ==Invariant== + * - `C[T]` and `C[T']` are not related + * - Scala notation: `[T]` + * + * + * That one probably blew your mind. Now if you assign a type to the instantiation that is different to the variable type, you'll have problems. You may want to take time after this koan to compare and contrast with the previous one. + * + * {{{ + * class MyContainer[A](val a: A)(implicit manifest: scala.reflect.Manifest[A]) { + * def contents = manifest.runtimeClass.getSimpleName + * } + * + * // Uncomment the following line + * // val fruitBasket:MyContainer[Fruit] = new MyContainer[Orange](new Orange()) + * }}} + * + * 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) { class MyContainer[+A](val a: A)(implicit manifest: scala.reflect.Manifest[A]) { def contents = manifest.runtimeClass.getSimpleName @@ -84,7 +89,7 @@ object TypeVariance extends FlatSpec with Matchers with org.scalaexercises.defin } /** 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) { class MyContainer[+A](val a: A)(implicit manifest: scala.reflect.Manifest[A]) { def contents = manifest.runtimeClass.getSimpleName @@ -99,18 +104,19 @@ object TypeVariance extends FlatSpec with Matchers with org.scalaexercises.defin } /** 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) { 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 + def contents = manifest.runtimeClass.getSimpleName } val citrusBasket: MyContainer[Citrus] = new MyContainer[Citrus](new Orange) citrusBasket.contents should be(res0) - val orangeBasket: MyContainer[Orange] = new MyContainer[Citrus](new Tangelo) + val orangeBasket: MyContainer[Orange] = + new MyContainer[Citrus](new Tangelo) orangeBasket.contents should be(res1) - val tangeloBasket: MyContainer[Tangelo] = new MyContainer[Citrus](new Orange) + val tangeloBasket: MyContainer[Tangelo] = + new MyContainer[Citrus](new Orange) tangeloBasket.contents should be(res2) val bananaBasket: MyContainer[Banana] = new MyContainer[Fruit](new Apple) bananaBasket.contents should be(res3) @@ -120,9 +126,9 @@ object TypeVariance extends FlatSpec with Matchers with org.scalaexercises.defin } /** Declaring neither `-` nor `+` indicates invariance. You cannot use a superclass variable reference (contravariant position) or a subclass variable reference (covariant position) of that type. In our example, this means that if you create a citrus basket you can only reference that citrus basket with a citrus variable only. - * - * Invariance means you need to specify the type exactly: - */ + * + * Invariance means you need to specify the type exactly: + */ 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/TypeVarianceHelper.scala b/src/main/scala/stdlib/TypeVarianceHelper.scala index 54304f49..90514888 100644 --- a/src/main/scala/stdlib/TypeVarianceHelper.scala +++ b/src/main/scala/stdlib/TypeVarianceHelper.scala @@ -1,12 +1,17 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib object TypeVarianceHelper { class Fruit abstract class Citrus extends Fruit - class Orange extends Citrus - class Tangelo extends Citrus - class Apple extends Fruit - class Banana extends Fruit + class Orange extends Citrus + class Tangelo extends Citrus + class Apple extends Fruit + class Banana extends Fruit } diff --git a/src/main/scala/stdlib/UniformAccessPrinciple.scala b/src/main/scala/stdlib/UniformAccessPrinciple.scala index 45da9a43..d843fe36 100644 --- a/src/main/scala/stdlib/UniformAccessPrinciple.scala +++ b/src/main/scala/stdlib/UniformAccessPrinciple.scala @@ -1,17 +1,25 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalatest._ /** @param name uniform_access_principle - * - */ -object UniformAccessPrinciple extends FlatSpec with Matchers with org.scalaexercises.definitions.Section { + * + */ +object UniformAccessPrinciple + extends FlatSpec + with Matchers + with org.scalaexercises.definitions.Section { /** The Scala language implements a programming concept known as the [[http://en.wikipedia.org/wiki/Uniform_access_principle Uniform Access Principle]], which was first put forth by Bertrand Meyer, the inventor of the Eiffel programming language. - * - * 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: - * - */ + * + * 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) { class Test1(val age: Int = 10) class Test2(_age: Int) { diff --git a/src/test/scala/stdlib/AssertsSpec.scala b/src/test/scala/stdlib/AssertsSpec.scala index 04eda2c1..1db5df39 100644 --- a/src/test/scala/stdlib/AssertsSpec.scala +++ b/src/test/scala/stdlib/AssertsSpec.scala @@ -1,3 +1,8 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalacheck.Shapeless._ @@ -7,15 +12,12 @@ import org.scalatest.prop.Checkers import shapeless.HNil class AssertsSpec extends Spec with Checkers { - def `scalatest asserts` = { + def `scalatest asserts` = check(Test.testSuccess(Asserts.scalaTestAsserts _, true :: HNil)) - } - def `boolean asserts` = { + def `boolean asserts` = check(Test.testSuccess(Asserts.booleanAsserts _, 4 :: HNil)) - } - def `values asserts` = { + def `values asserts` = check(Test.testSuccess(Asserts.valuesAsserts _, 2 :: HNil)) - } } diff --git a/src/test/scala/stdlib/ByNameParameterSpec.scala b/src/test/scala/stdlib/ByNameParameterSpec.scala index cb66fa1f..d61b1b12 100644 --- a/src/test/scala/stdlib/ByNameParameterSpec.scala +++ b/src/test/scala/stdlib/ByNameParameterSpec.scala @@ -1,3 +1,8 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalacheck.Shapeless._ diff --git a/src/test/scala/stdlib/CaseClassesSpec.scala b/src/test/scala/stdlib/CaseClassesSpec.scala index fb98477a..e7882419 100644 --- a/src/test/scala/stdlib/CaseClassesSpec.scala +++ b/src/test/scala/stdlib/CaseClassesSpec.scala @@ -1,3 +1,8 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalacheck.Shapeless._ diff --git a/src/test/scala/stdlib/ClassesSpec.scala b/src/test/scala/stdlib/ClassesSpec.scala index d370a211..d605971c 100644 --- a/src/test/scala/stdlib/ClassesSpec.scala +++ b/src/test/scala/stdlib/ClassesSpec.scala @@ -1,3 +1,8 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalacheck.Shapeless._ diff --git a/src/test/scala/stdlib/EmptyValuesSpec.scala b/src/test/scala/stdlib/EmptyValuesSpec.scala index c84b39b1..18ddc404 100644 --- a/src/test/scala/stdlib/EmptyValuesSpec.scala +++ b/src/test/scala/stdlib/EmptyValuesSpec.scala @@ -1,3 +1,8 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalacheck.Shapeless._ diff --git a/src/test/scala/stdlib/EnumerationsSpec.scala b/src/test/scala/stdlib/EnumerationsSpec.scala index b812d101..fecf5fb5 100644 --- a/src/test/scala/stdlib/EnumerationsSpec.scala +++ b/src/test/scala/stdlib/EnumerationsSpec.scala @@ -1,2 +1,6 @@ -package stdlib +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ +package stdlib diff --git a/src/test/scala/stdlib/ExtractorsSpec.scala b/src/test/scala/stdlib/ExtractorsSpec.scala index 4d3892d0..b7f08f82 100644 --- a/src/test/scala/stdlib/ExtractorsSpec.scala +++ b/src/test/scala/stdlib/ExtractorsSpec.scala @@ -1,3 +1,8 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalacheck.Shapeless._ diff --git a/src/test/scala/stdlib/ForExpressionsSpec.scala b/src/test/scala/stdlib/ForExpressionsSpec.scala index df41cf7f..502ef46e 100644 --- a/src/test/scala/stdlib/ForExpressionsSpec.scala +++ b/src/test/scala/stdlib/ForExpressionsSpec.scala @@ -1,3 +1,8 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalacheck.Shapeless._ diff --git a/src/test/scala/stdlib/FormattingSpec.scala b/src/test/scala/stdlib/FormattingSpec.scala index 2bfbf868..82580478 100644 --- a/src/test/scala/stdlib/FormattingSpec.scala +++ b/src/test/scala/stdlib/FormattingSpec.scala @@ -1,3 +1,8 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalacheck.Shapeless._ diff --git a/src/test/scala/stdlib/HigherOrderFunctionsSpec.scala b/src/test/scala/stdlib/HigherOrderFunctionsSpec.scala index 9d4e6714..0e52513c 100644 --- a/src/test/scala/stdlib/HigherOrderFunctionsSpec.scala +++ b/src/test/scala/stdlib/HigherOrderFunctionsSpec.scala @@ -1,3 +1,8 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalacheck.Shapeless._ @@ -72,10 +77,11 @@ class HigherOrderFunctionsSpec extends Spec with Checkers { def `function as a parameter` = { check( - Test.testSuccess( - HigherOrderFunctions.functionAsParameterHigherOrderFunctions _, - List("ABC", "XYZ", "123") :: List("abc", "xyz", "123") :: List(5, 6, 7) :: HNil - ) + Test + .testSuccess( + HigherOrderFunctions.functionAsParameterHigherOrderFunctions _, + List("ABC", "XYZ", "123") :: List("abc", "xyz", "123") :: List(5, 6, 7) :: HNil + ) ) } } diff --git a/src/test/scala/stdlib/ImplicitsSpec.scala b/src/test/scala/stdlib/ImplicitsSpec.scala index f1756394..0ff5a690 100644 --- a/src/test/scala/stdlib/ImplicitsSpec.scala +++ b/src/test/scala/stdlib/ImplicitsSpec.scala @@ -1,3 +1,8 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalacheck.Shapeless._ diff --git a/src/test/scala/stdlib/InfixPrefixAndPostfixOperatorsSpec.scala b/src/test/scala/stdlib/InfixPrefixAndPostfixOperatorsSpec.scala index 579b1241..bb88ec8b 100644 --- a/src/test/scala/stdlib/InfixPrefixAndPostfixOperatorsSpec.scala +++ b/src/test/scala/stdlib/InfixPrefixAndPostfixOperatorsSpec.scala @@ -1,3 +1,8 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalaexercises.Test diff --git a/src/test/scala/stdlib/InfixTypesSpec.scala b/src/test/scala/stdlib/InfixTypesSpec.scala index 3e42281f..26e7da3f 100644 --- a/src/test/scala/stdlib/InfixTypesSpec.scala +++ b/src/test/scala/stdlib/InfixTypesSpec.scala @@ -1,3 +1,8 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalacheck.Shapeless._ diff --git a/src/test/scala/stdlib/IterablesSpec.scala b/src/test/scala/stdlib/IterablesSpec.scala index d7299a6c..ac5343f5 100644 --- a/src/test/scala/stdlib/IterablesSpec.scala +++ b/src/test/scala/stdlib/IterablesSpec.scala @@ -1,3 +1,8 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalacheck.Shapeless._ diff --git a/src/test/scala/stdlib/ListsSpec.scala b/src/test/scala/stdlib/ListsSpec.scala index 7991ae19..3e9260e8 100644 --- a/src/test/scala/stdlib/ListsSpec.scala +++ b/src/test/scala/stdlib/ListsSpec.scala @@ -1,3 +1,8 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalacheck.Shapeless._ diff --git a/src/test/scala/stdlib/LiteralBooleansSpec.scala b/src/test/scala/stdlib/LiteralBooleansSpec.scala index af0f6368..1c108a41 100644 --- a/src/test/scala/stdlib/LiteralBooleansSpec.scala +++ b/src/test/scala/stdlib/LiteralBooleansSpec.scala @@ -1,3 +1,8 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalacheck.Shapeless._ diff --git a/src/test/scala/stdlib/LiteralNumbersSpec.scala b/src/test/scala/stdlib/LiteralNumbersSpec.scala index 7fb5b7c7..f05655be 100644 --- a/src/test/scala/stdlib/LiteralNumbersSpec.scala +++ b/src/test/scala/stdlib/LiteralNumbersSpec.scala @@ -1,3 +1,8 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalacheck.Shapeless._ diff --git a/src/test/scala/stdlib/LiteralStringsSpec.scala b/src/test/scala/stdlib/LiteralStringsSpec.scala index 20569317..14cb8cde 100644 --- a/src/test/scala/stdlib/LiteralStringsSpec.scala +++ b/src/test/scala/stdlib/LiteralStringsSpec.scala @@ -1,3 +1,8 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalacheck.Shapeless._ diff --git a/src/test/scala/stdlib/MapsSpec.scala b/src/test/scala/stdlib/MapsSpec.scala index 9e223322..c15970cd 100644 --- a/src/test/scala/stdlib/MapsSpec.scala +++ b/src/test/scala/stdlib/MapsSpec.scala @@ -1,3 +1,8 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalacheck.Shapeless._ diff --git a/src/test/scala/stdlib/NamedAndDefaultArgumentsSpec.scala b/src/test/scala/stdlib/NamedAndDefaultArgumentsSpec.scala index 90180e4d..92f0480d 100644 --- a/src/test/scala/stdlib/NamedAndDefaultArgumentsSpec.scala +++ b/src/test/scala/stdlib/NamedAndDefaultArgumentsSpec.scala @@ -1,3 +1,8 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalacheck.Shapeless._ diff --git a/src/test/scala/stdlib/ObjectsSpec.scala b/src/test/scala/stdlib/ObjectsSpec.scala index 7cb95621..e7b62229 100644 --- a/src/test/scala/stdlib/ObjectsSpec.scala +++ b/src/test/scala/stdlib/ObjectsSpec.scala @@ -1,3 +1,8 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalacheck.Shapeless._ diff --git a/src/test/scala/stdlib/OptionsSpec.scala b/src/test/scala/stdlib/OptionsSpec.scala index 5ae51a5e..4c389c04 100644 --- a/src/test/scala/stdlib/OptionsSpec.scala +++ b/src/test/scala/stdlib/OptionsSpec.scala @@ -1,3 +1,8 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalacheck.Shapeless._ diff --git a/src/test/scala/stdlib/ParentClassesSpec.scala b/src/test/scala/stdlib/ParentClassesSpec.scala index 6098d803..682746f4 100644 --- a/src/test/scala/stdlib/ParentClassesSpec.scala +++ b/src/test/scala/stdlib/ParentClassesSpec.scala @@ -1,3 +1,8 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalacheck.Shapeless._ diff --git a/src/test/scala/stdlib/PartialFunctionsSpec.scala b/src/test/scala/stdlib/PartialFunctionsSpec.scala index 2842cd08..ca0742c8 100644 --- a/src/test/scala/stdlib/PartialFunctionsSpec.scala +++ b/src/test/scala/stdlib/PartialFunctionsSpec.scala @@ -1,3 +1,8 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalacheck.Shapeless._ diff --git a/src/test/scala/stdlib/PartiallyAppliedFunctionsSpec.scala b/src/test/scala/stdlib/PartiallyAppliedFunctionsSpec.scala index ee6c290f..6cb3664b 100644 --- a/src/test/scala/stdlib/PartiallyAppliedFunctionsSpec.scala +++ b/src/test/scala/stdlib/PartiallyAppliedFunctionsSpec.scala @@ -1,3 +1,8 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalacheck.Shapeless._ diff --git a/src/test/scala/stdlib/PatternMatchingSpec.scala b/src/test/scala/stdlib/PatternMatchingSpec.scala index 3d880625..67ebab48 100644 --- a/src/test/scala/stdlib/PatternMatchingSpec.scala +++ b/src/test/scala/stdlib/PatternMatchingSpec.scala @@ -1,3 +1,8 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalacheck.Shapeless._ diff --git a/src/test/scala/stdlib/RangesSpec.scala b/src/test/scala/stdlib/RangesSpec.scala index 7977c616..744dea69 100644 --- a/src/test/scala/stdlib/RangesSpec.scala +++ b/src/test/scala/stdlib/RangesSpec.scala @@ -1,3 +1,8 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalacheck.Shapeless._ diff --git a/src/test/scala/stdlib/RepeatedParametersSpec.scala b/src/test/scala/stdlib/RepeatedParametersSpec.scala index 9d00beba..88b4fe5e 100644 --- a/src/test/scala/stdlib/RepeatedParametersSpec.scala +++ b/src/test/scala/stdlib/RepeatedParametersSpec.scala @@ -1,3 +1,8 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalacheck.Shapeless._ diff --git a/src/test/scala/stdlib/SequencesAndArraysSpec.scala b/src/test/scala/stdlib/SequencesAndArraysSpec.scala index 4832aa4f..68e46153 100644 --- a/src/test/scala/stdlib/SequencesAndArraysSpec.scala +++ b/src/test/scala/stdlib/SequencesAndArraysSpec.scala @@ -1,3 +1,8 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalacheck.Shapeless._ diff --git a/src/test/scala/stdlib/SetsSpec.scala b/src/test/scala/stdlib/SetsSpec.scala index 1b27e653..47d58fd2 100644 --- a/src/test/scala/stdlib/SetsSpec.scala +++ b/src/test/scala/stdlib/SetsSpec.scala @@ -1,3 +1,8 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalacheck.Shapeless._ diff --git a/src/test/scala/stdlib/TraitsSpec.scala b/src/test/scala/stdlib/TraitsSpec.scala index fe1c22a3..bca6a7c9 100644 --- a/src/test/scala/stdlib/TraitsSpec.scala +++ b/src/test/scala/stdlib/TraitsSpec.scala @@ -1,3 +1,8 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalacheck.Shapeless._ diff --git a/src/test/scala/stdlib/TraversablesSpec.scala b/src/test/scala/stdlib/TraversablesSpec.scala index f87149c6..3ebf8f51 100644 --- a/src/test/scala/stdlib/TraversablesSpec.scala +++ b/src/test/scala/stdlib/TraversablesSpec.scala @@ -1,3 +1,8 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalacheck.Shapeless._ diff --git a/src/test/scala/stdlib/TuplesSpec.scala b/src/test/scala/stdlib/TuplesSpec.scala index 692c9b5d..dd9aeae5 100644 --- a/src/test/scala/stdlib/TuplesSpec.scala +++ b/src/test/scala/stdlib/TuplesSpec.scala @@ -1,3 +1,8 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalacheck.Shapeless._ diff --git a/src/test/scala/stdlib/TypeSignaturesSpec.scala b/src/test/scala/stdlib/TypeSignaturesSpec.scala index 87af0269..c3d83d2e 100644 --- a/src/test/scala/stdlib/TypeSignaturesSpec.scala +++ b/src/test/scala/stdlib/TypeSignaturesSpec.scala @@ -1,3 +1,8 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalacheck.Shapeless._ diff --git a/src/test/scala/stdlib/TypeVarianceSpec.scala b/src/test/scala/stdlib/TypeVarianceSpec.scala index b28384f9..d5d3f98f 100644 --- a/src/test/scala/stdlib/TypeVarianceSpec.scala +++ b/src/test/scala/stdlib/TypeVarianceSpec.scala @@ -1,3 +1,8 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalacheck.Shapeless._ diff --git a/src/test/scala/stdlib/UniformAccessPrincipleSpec.scala b/src/test/scala/stdlib/UniformAccessPrincipleSpec.scala index e4346a15..25fc86b5 100644 --- a/src/test/scala/stdlib/UniformAccessPrincipleSpec.scala +++ b/src/test/scala/stdlib/UniformAccessPrincipleSpec.scala @@ -1,3 +1,8 @@ +/* + * scala-exercises - exercises-stdlib + * Copyright (C) 2015-2016 47 Degrees, LLC. + */ + package stdlib import org.scalacheck.Shapeless._ diff --git a/version.sbt b/version.sbt new file mode 100644 index 00000000..acfbdb67 --- /dev/null +++ b/version.sbt @@ -0,0 +1 @@ +version in ThisBuild := "0.4.0-SNAPSHOT"