Coder Social home page Coder Social logo

exercises-stdlib's Introduction

Join the conversation on Gitter

Scala Exercises


How it works

"Scala Exercises" brings exercises for the Stdlib, Cats, Shapeless, and many other great libraries for Scala to your browser. This includes hundreds of solvable exercises organized into several categories covering the basics of the Scala language and its most important libraries.

  • LEARN: Each category includes an explanation of the basics. Learn the concepts through simple code samples.

  • SOLVE: Each exercise is a unit test that must pass successfully—complete the exercise by filling in the blanks. Receive instant feedback as your answers are validated in real-time.

  • SHARE: The system will consider the category complete when all its exercises are successfully done. Don't forget to share your progress on social networks before moving on to the next category!

  • EDIT: After completing a category, you'll be able to go back and edit it. Add new exercises or improve existing ones by sending a pull request.

Getting Started

Online

Scala Exercises is available at scala-exercises.org.

Local development

Prerequisites

Installing the app locally

Get the repository

First of all, either clone the repository via git

$ git clone https://github.com/scala-exercises/scala-exercises

or download it

$ wget https://github.com/scala-exercises/scala-exercises/archive/master.zip
Configure the database

You'll need a working PostgreSQL 9.4 database and user for running the app. Once the database is running,

  • Create a user called scalaexercises_dev_user
$ sudo -u postgres psql -c "CREATE USER scalaexercises_dev_user WITH PASSWORD 'a_password';"
  • Create a db called scalaexercises_dev and grant all privileges on it to scalaexercises_dev_user
$ sudo -u postgres createdb scalaexercises_dev
$ sudo -u postgres psql -c "GRANT ALL PRIVILEGES ON DATABASE scalaexercises_dev TO scalaexercises_dev_user;"

Alternatively, you can also use Docker to run the database. The following command creates a database container and exposes it:

$ docker run --name scala-exercises-db -e POSTGRES_DB=scalaexercises_dev -e POSTGRES_PASSWORD=scalaexercises_pass -e POSTGRES_USER=scalaexercises_dev_user -p 5432:5432 -d postgres:9.4
Configure the application

Edit the server/conf/application.dev.conf configuration file with your database information.

Running the app

Go into the project's root directory, run sbt server/run with -mem option to increase the memory.

$ sbt -mem 1500 server/run

After compilation, the application will be running, listening in the 9000 port. Point your browser to localhost:9000 and start having fun!

Running the tests

To run the tests (for the server project), you need to add a test database and a test user.

  • Create a user called scalaexercises_user
$ sudo -u postgres psql -c "CREATE USER scalaexercises_user WITH PASSWORD 'scalaexercises_pass';"
  • Create a db called scalaexercises_test and grant all privileges on it to scalaexercises_user
$ sudo -u postgres createdb scalaexercises_test
$ sudo -u postgres psql -c "GRANT ALL PRIVILEGES ON DATABASE scalaexercises_test TO scalaexercises_user;"

Adding more exercises

Currently, scala-exercises includes exercises for the Scala Standard Library, Cats, and Shapeless. However, more exercises are available, like for Doobie, Functional Programming in Scala, and ScalaCheck. See the scala-exercises on github, or you can include exercises from other parties or create your own (see Contributing section).

To add additional exercises to your locally running server:

  • clone the exercises repository to a local folder
  • 'cd' into the local repository folder.
  • run sbt compile publishLocal to create a jar in your local ivy repository.
    !Note: The compile task is mandatory here otherwise the exercises will not show up in the application.
  • add a dependency to the exersises jar in the server project in the build.sbt file (~L118).

Now run sbt server/run and the application index will also display the added exercises.

Troubleshooting

Additional exercises do not show up in the application

See the Adding more exercises section. Note that, currently, the compile step is required before publishLocal for the application to be able to pickup the exercises.

Ensime

If you use ensime and you have configured the sbt-ensime plugin in your sbt user global settings, it's likely you might have this issue running the application locally:

java.lang.NoClassDefFoundError: scalariform/formatter/preferences/SpacesAroundMultiImports$

In that case, you could solve this issue setting up your /.sbt/0.13/plugins/plugins.sbt file as follows:

addSbtPlugin("org.ensime" % "ensime-sbt" % "0.5.1")

dependencyOverrides in ThisBuild += "org.scalariform" %% "scalariform" % "0.1.8"

In order to avoid the error related to Github API rate limit exceeded during compilation of exercises, we recommend setting a local environment variable called GITHUB_TOKEN with a personal token that you can create here.

While creating the PostgreSQL database, you may run into problems following the previous instructions if developing on a MacOS X environment. In that case, we recommend using the following alternatives:

  • Create a user called scalaexercises_dev_user. Note that, if you installed PostgreSQL using Homebrew, your superuser may be different than postgres:
$ psql -U your_postgres_user -c "CREATE USER scalaexercises_dev_user WITH PASSWORD 'a_password';"
  • Create a db called scalaexercises_dev and grant all privileges on it to scalaexercises_dev_user:
$ createdb scalaexercises_dev
$ psql -U your_postgres_user -c "GRANT ALL PRIVILEGES ON DATABASE scalaexercises_dev TO scalaexercises_dev_user;"

Project structure

The project is split between a few directories, namely:

  • server, which contains the server code written using Play,
  • client, which contains ScalaJS code for a frontend part of the application,
  • shared, where code shared between the server and the client exists,
  • definitions, containing definitions used by other parts of the application and libraries containing exercises,
  • sbt-exercise is a sbt plugin that locates exercise libraries and processes their source code,
  • compiler for compiling exercises,
  • runtime for runtime evaluation of exercises.

The compiler and runtime directories allow exercises to be defined using regular Scala, which is compiled into an exercise library.

The site, client, and shared directories contain the website. These items depend on components in compiler and runtime.

At the moment, those subprojects are coupled tightly. Once this project is a bit more stable, the exercise compiler plugin will be published, and it will be easy to create new exercises for existing Scala libraries.

exercises-stdlib's People

Contributors

47erbot avatar alejandrohdezma avatar andyscott avatar angoglez avatar aseigneurin avatar benfradet avatar czajnikowski avatar dominv avatar etrain avatar fedefernandez avatar frosner avatar hellrich avatar idarlington avatar jakzal avatar joelittlejohn avatar jonboiser avatar josephpconley avatar juanpedromoreno avatar kevingreene avatar kiroco12 avatar kjhoerr avatar laverboy avatar mergify[bot] avatar raulraja avatar samehadar avatar scala-steward avatar sloshy avatar textpreferred avatar xhudik avatar yaskier avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

exercises-stdlib's Issues

Bug in Traversables exercise

val list = List(List(1, 2, 3), List(4, 5, 6), List(7, 8, 9))
list.transpose should be(List(
List(1,4,7), 
List(2,5,8), 
List(3,6,9)))

val list2 = List(List(1), List(4))
list2.transpose should be(List(List(1),List(4)))
Evaluation failed : Compilation Error ; ERROR -> too many arguments for method transposeFunctionTraversables: (res0: List[Int], res1: List[Int], res2: List[Int], res3: List[Int])Unit at [284, 284, 284]

Stream take returns new stream

In Traversable exercises the 15th is buggy.

Title:
toStream will convert any Traversable to a Stream which is a lazy list where elements are evaluated as they are needed.

It expects a List instead of a Stream after take

Bug in Traversables exercies.

There seems to be a bug in the Traversables exercises:

image

Also this assertion seems to be non-deterministic: (totalReduceRightTime > totalReduceLeftTime) should be()
Locally I have tried to run this multiple times and I have varied results. Something to consider when updating this exercise.

Type Variance Exercise

The original AboutTypeVariance koan defined the following class hierarchy:

  class Fruit
  abstract class Citrus extends Fruit
  class Orange extends Citrus
  class Tangelo extends Citrus
  class Apple extends Fruit
  class Banana extends Fruit

I feel, adding this information to the type variance exercise would help readers fully understand the examples. Namely, in the following contravariance example, it is important to know that Citrus is a superclass of both Orange and Tangelo.

val orangeBasket: MyContainer[Orange] =  new MyContainer[Citrus](new Tangelo)

Options section error

Hi,

def matchOptions(res0: Float, res1: Float) {
    val someValue: Option[Double] = Some(20.0)
    val value = someValue match {
      case Some(v)  v
      case None     0.0
    }
    value should be(res0)
    val noValue: Option[Double] = None
    val value1 = noValue match {
      case Some(v)  v
      case None     0.0
    }
    value1 should be(res1)
  }

The above test in the options exercise throws an error because the test is comparing a Float to a Double value1 should be(res1) and most persons input their answers as Double.

I could put in a pull request.

Edit page links doesnt work

Very page(e.g. https://www.scala-exercises.org/std_lib/partial_functions ) at the bottom has Edit Exercisepage link:
image

This link doenst work:

#it points to
https://github.com/scala-exercises/exercises-stdlib/edit/master/src/main/scala/stdlib/PatternMatching.scala
#it should points to instead
https://github.com/scala-exercises/exercises-stdlib/edit/main/src/main/scala/stdlib/PatternMatching.scala

(replace main with master)

I'd create a pull request just didnt find where the link actually is located :)

type of implicit definition needs to be given explicitly

In Scala 3.2.2 REPL get this error in examples with implicits.

|implicit def thisMethodNameIsIrrelevant(value: Int) =
|             ^
|           result type of implicit definition needs to be given explicitly
implicit val hourlyRate = BigDecimal(34)
              ^
              type of implicit definition needs to be given explicitly

Lists exercise expects String Type instead of List

def reuseTailsLists(res0: Int, res1: Int, res2: Int, res3: String, res4: String, res5: String) {
    val d = Nil
    val c = 3 :: d
    val b = 2 :: c
    val a = 1 :: b

    a should be(List(res0, res1, res2))
    a.tail should be(res3)
    b.tail should be(res4)
    c.tail should be(res5)
  }

The above function in the List Section should be refactored to expect

a.tail should be List(2, 3)
b.tail should be List(3)
c.tail should be List[Int]()

and the argument type should be List[Int]

Contravariance exercises

From scala-exercises/scala-exercises#353

We have removed the contravariance related exercises because they were originally expressed with mutability. The exercises need to be reworked to demonstrate how contravariance works in a more principled way than using mutability.

Bug in last exercise of Partially Applied Functions

It says "There was a problem evaluating your answer, please try again later." in the last exercise in Partially Applied Functions even when I can run it successfully in local Scala console.

It seems the operator "=>" was converted to a character '⇒' exceptionally.

I have submitted a PR #131 to fix it. Please check and merge it.

Higher Order Functions should come before Options

The Options exercises makes reference to higher order functions, with very little explanation, which can be confusing for beginners. It should come before Options. The explanations should be buffed up too.

I'm willing to fork it and make the necessary changes if no one objects.

"For Expressions" section needs a few simple examples to start off with

The section jumps right into advanced examples (multiple generators and filters) without explaining the for syntax, generators or filters. It would be nice to start off with a few easier examples:

  • Simple Java-style for loop:
for (i <- 1 to 15) { ... }
  • Simple Java-style 'foreach" loop:
for (element: Int <- someIntArray) { ... }
  • A loop with a single generator and filter:
for (element: Int <- someIntArray if element % 2 == 0) { ... }

Issue in Prefix Postfix Infix assignment

I am unable to test the basic Infix , see the bold error message below

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.

val g: Int = 3
(g + 4) should be(
g.+(4)
) // + is an infix operator
g.+(4) should be(
g + 4
)
Evaluation failed : Compilation Error ; ERROR -> not found: value g at [308, 308, 308]

Misrepresented question

In the Lists exercise, the question is this :

a.filter(_ % 2 != 0) should equal(List(  ? , ?  ))

but the code has this and the test is suited to it.

  a.filter {
      _ % 2 == 0
    } should equal(List(res3))

Another case of Float

Hi, so I noticed another case of the exercise expecting a Float instead of a Double

Tuple Section

def assignVariablesTuples(res0: String, res1: Int, res2: Float) {
    val student = ("Sean Rogers", 21, 3.5)
    val (name, age, gpa) = student

    name should be(res0)
    age should be(res1)
    gpa should be(res2)
  }

If the expected user input should be Floats, then it should probably be specified in the readme or in each exercise.

Second to last exercise in extractors

I don't really get how the code is setup well enough in order to fix this, though I tried.

Any REPL, either Scala's or sbt's returns the same answer, in 2.11 or 2.12. I suspect the issue is with the res2, Option[String] = "None." but no answer satisfies the interpreter.

Last Exercise in Iterators

It looks like there is a warning with a note in the Github repository about sets with less than 5 elements, however this is not showing up on the scala-exerices.org site. This makes for a confusing exercise.

Octal scapes literals are unssuported

I have tried to run this code

val c = 'a' //unicode for a
val d = '\141' //octal for a
val e = '"'
val f = '\'

But pops up an error when it tries to declare d variable

octal escape literals are unsupported: use \u0061 instead
val d = '\141' //octal for a

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.