Giter VIP home page Giter VIP logo

exercises-cats'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-cats's People

Contributors

47erbot avatar aeons avatar alejandrohdezma avatar angoglez avatar augustjune avatar benfradet avatar cb372 avatar davesmith00047 avatar dominv avatar doub1ejack avatar fedefernandez avatar github-actions[bot] avatar juanpedromoreno avatar kiroco12 avatar kobenko avatar lloydmeta avatar mergify[bot] avatar mttkay avatar paualarco avatar raulraja avatar rawtoast avatar richardmiller avatar samehadar avatar scala-steward avatar sergiohgz avatar sloshy avatar thangiee avatar tobiasroland avatar tr4rex avatar yilinwei 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

exercises-cats's Issues

Sintax typo in the applicative section

There is a typo in one line of code in the section of Applicative in the library of Cats.

Applicative[List] compose Applicative[Option]).pure(1) should be(List(Some(1)))

Here we need to open the the parenthesis before of Applicative ...

I am checking the code and seems that it has solved. Is it possible that this changed it has not been deployed ?

First example in Semigroups does not work on current web-site

Hi all I've found inconsistency in first exercise of exercises-cats. More precisely code on server is using modified example where https://github.com/scala-exercises/exercises-cats/blob/master/src/main/scala/catslib/Semigroup.scala#L48 was split to two. But text on the website is still using the old one. What is the update process of the web-site? Should I file an issue?
To put it simply, first exercise in https://www.scala-exercises.org/cats/semigroup does not work.

Steps to reproduce:

Go to web site https://www.scala-exercises.org/cats/semigroup and fill the first example, you will get the error. By me it looks like:

import cats.implicits._

Semigroup[Int].combine(1, 2) should be( 3 )
Semigroup[List[Int]].combine(List(1, 2, 3), List(4, 5, 6)) should be( List(1,2,3,4,5,6) )
Semigroup[Option[Int]].combine(Option(1), Option(2)) should be( Some(3) )
Semigroup[Option[Int]].combine(Option(1), None) should be( Some(1) )
Semigroup[Int ⇒ Int]
  .combine({ (x: Int) ⇒
    x + 1
  }, { (x: Int) ⇒
    x * 10
  })
  .apply(6) should be( 67 )

Click run, you will get:

Evaluation failed : Compilation Error ; ERROR -> too many arguments for method semigroupCombine: (res0: Int, res1:
IMHO the site is just obsolete, that all.

Cats version used in examples is outdated

The exercises are 3 major versions behind cats at the time I write this (they use 0.4.x where 0.7.x is the latest release.) Some exercise code does not compile anymore, e.g. due to the removal of the cats.std package. I tried updating cats to 0.7 and fixed all the compilation errors (they were mostly due to implicit conversions having moved to cats.implicits._) but ran into a chain of binary incompatibilities with the dependencies when executing the tests. I gave up at this point:

  libraryDependencies ++= Seq(
    "org.typelevel" %% "cats-core" % "0.7.0",
    "com.chuusai" %% "shapeless" % "2.3.2",
    "org.scalatest" %% "scalatest" % "2.2.6",
    "org.scala-exercises" %% "exercise-compiler" % version.value,
    "org.scala-exercises" %% "definitions" % version.value,
    "org.scalacheck" %% "scalacheck" % "1.13.2",
    "com.github.alexarchambault" %% "scalacheck-shapeless_1.13" % "1.1.1",
    compilerPlugin("org.spire-math" %% "kind-projector" % "0.7.1")
  )

I bumped shapeless (minor), scalatest (patch), scalacheck (minor) and scalacheck-shapeless (minor)

Something is still wrong though, as the test runner cannot find a class it's expecting:

An exception or error caused a run to abort: Implementing class 
java.lang.IncompatibleClassChangeError: Implementing class
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:760)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:467)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:73)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:368)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:362)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:361)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at catslib.MonoidSpec.<init>(MonoidSpec.scala:9)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
    at java.lang.Class.newInstance(Class.java:442)
    at org.scalatest.tools.Runner$.genSuiteConfig(Runner.scala:2644)
    at org.scalatest.tools.Runner$$anonfun$37.apply(Runner.scala:2461)
    at org.scalatest.tools.Runner$$anonfun$37.apply(Runner.scala:2460)
    at scala.collection.immutable.List.map(List.scala:273)
    at org.scalatest.tools.Runner$.doRunRunRunDaDoRunRun(Runner.scala:2460)
    at org.scalatest.tools.Runner$$anonfun$runOptionallyWithPassFailReporter$2.apply(Runner.scala:1044)
    at org.scalatest.tools.Runner$$anonfun$runOptionallyWithPassFailReporter$2.apply(Runner.scala:1043)
    at org.scalatest.tools.Runner$.withClassLoaderAndDispatchReporter(Runner.scala:2722)
    at org.scalatest.tools.Runner$.runOptionallyWithPassFailReporter(Runner.scala:1043)
    at org.scalatest.tools.Runner$.run(Runner.scala:883)
    at org.scalatest.tools.Runner.run(Runner.scala)
    at org.jetbrains.plugins.scala.testingSupport.scalaTest.ScalaTestRunner.runScalaTest2(ScalaTestRunner.java:138)
    at org.jetbrains.plugins.scala.testingSupport.scalaTest.ScalaTestRunner.main(ScalaTestRunner.java:28)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

It appears there is some binary incompatibility between the dependencies somewhere. I also tried replacing ScalaTest with the latest major release 3, but that failed with other obscure errors.

Could this be related to the exercise-compiler? What does it do and where can one look at it? Any advice or someone else looking into this?

Monad & Foldable exercises feedback

I'm opening this issue just to give some feedback on these two exercises.

  • So in Monad exercise OptionT is introduced. You can deduce some of its meaning from the text on the exercise but I've had to expand it with this article. Seems right but can't know it it the same thing. Also, in the article there are some nice examples to understand in what cases you'd use OptionT.
  • In Foldable exercise MonoidK is referred out from nowhere before having explained it. Also had to go to the sources to expand on this.

It would be nice to explain why OptionT[F, A] & MonoidK[F, A] instead of OptionK[F, A] & MonoidK[F, A] or OptionT[F, A] & MonoidT[F, A]. Don't both suffixes mean the same thing?

  • In Foldable, why, oh, why does this hold true?
Foldable[List].foldK(List(None, Option("two"), Option("three"))) should be(Some("two"))

Can not do the Eval exercises

Hi,

On Cats | Eval, we can not do the exercises, the fields we have to fill are already filed with text (apparently scala types) instead of having html inputs elements.

The related code is this one, however upon looking at it and other files to compare them, I couldn't pin-point the problem, no missing includes and the class is inheriting from the needed ones as in the other exercises.

Traverse lesson, running examples with cats 1.0.0-MF

Hello people :).

I am trying to run the following code on a scala worksheet scala 2.12.4, sbt 1.0.3, cats 1.0.0-MF:

import cats.Semigroup
import cats.data.{NonEmptyList, OneAnd, Validated, ValidatedNel}
import cats.implicits._

implicit def nelSemigroup[A]: Semigroup[NonEmptyList[A]] =
  OneAnd.oneAndSemigroupK[List].algebra[A]

def parseIntEither(s: String): Either[NumberFormatException, Int] =
  Either.catchOnly[NumberFormatException](s.toInt)

def parseIntValidated(s: String): ValidatedNel[NumberFormatException, Int] =
  Validated.catchOnly[NumberFormatException](s.toInt).toValidatedNel

List("1", "2", "3").traverseU(parseIntEither)
List("1", "abc", "3").traverseU(parseIntEither)

But OneAnd apparently does not have oneAndSemigroupK, and I was also not able to find this in the scaladoc for cats. Maybe it is obvious, but I don't now how to implement the implicit so my List will have traverseU

Error is:

Error:(6, 11) value oneAndSemigroupK is not a member of object cats.data.OneAnd
  OneAnd.oneAndSemigroupK[List].algebra[A]
         ^

No information on which test is failing

In the first cats exercice on Semigroup, there are four slots to fill.

However if a single slot is wrong, then all answers are underlined in red. It's difficult for a beginner to figure out which answer was wrong, especially because each example is testing a corner case (combining list, combining option with None).

I had to look up the answer in the repo
https://github.com/scala-exercises/exercises-cats/blob/master/src/test/scala/catslib/SemigroupSpec.scala

I would suggest to underline only the failing tests, or split the test into 4.

Foldable[T].traverse_ exercises accepts wrong answer as correct

On the exercise of Foldable traverse, it accepts a wrong answer as proper:

import cats.implicits._

def parseInt(s: String): Option[Int] =
  Either.catchOnly[NumberFormatException](s.toInt).toOption

Foldable[List].traverse_(List("1", "2", "3"))(parseInt) should be(Some(42))

Since traverse_ returns G[Unit], correct answer should be Some(()). But it is accepting Some of anything. Maybe it is even a bug on scalatest since on a workspace:

Foldable[List].traverse_(List("1", "2"))(parseInt) == Some(())
Foldable[List].traverse_(List("1", "2"))(parseInt) == Some(42)

Outputs:

true
false

image

Show better errors, i.e. line numbers

It would be a huge improvement if the quizzes would give a position (which line was the failed assertion?). I appreciate, that in this way, we are not getting the answers, but maybe as an easy fix, split each line into it's own box to make locating your mistakes much easier.

java.lang.NoClassDefFoundError: cats/free/Inject$ building master

I was going to see if I could debug why the Applicative composition exercise doesn't display correctly and in trying to build exercises-cats, I ran into the NoClassDefFoundError above.

I checked on another computer and then tried the hseeberger/scala-sbt docker image to make sure I was starting clean. I got the same result all three times.

Steps to reproduce with hseeberger/scala-sbt docker image:

  1. sudo docker run -it --rm hseeberger/scala-sbt
  2. git clone https://github.com/scala-exercises/exercises-cats.git
  3. cd exercises-cats/
  4. sbt compile publishLocal

These steps should yield this stack trace:

java.lang.NoClassDefFoundError: cats/free/Inject$
	at github4s.Github.repos$lzycompute(Github.scala:40)
	at github4s.Github.repos(Github.scala:40)
	at org.scalaexercises.compiler.Compiler.org$scalaexercises$compiler$Compiler$$fetchContributions$1(Compiler.scala:163)

As a quick attempt to fix this, I added cats-free to the build.sbt file, and this yielded another stack trace.

java.lang.NoSuchMethodError: cats.free.Free.foldMap(Lcats/arrow/FunctionK;Lcats/Monad;)Ljava/lang/Object;
	at github4s.Github$GithubIOSyntaxEither.execK(Github.scala:58)
	at github4s.Github$GithubIOSyntaxEither.exec(Github.scala:64)
	at org.scalaexercises.compiler.Compiler.org$scalaexercises$compiler$Compiler$$fetchContributions$1(Compiler.scala:167)

It looks like I need another version of cats-free, but I'm not sure which one.

Monad last exercise doesn't compile

The following code doesn't compile:

implicit def optionTMonad[F[_]](implicit F: Monad[F]) = {
  new Monad[OptionT[F, ?]] {
    def pure[A](a: A): OptionT[F, A] = OptionT(F.pure(Some(a)))
    def flatMap[A, B](fa: OptionT[F, A])(f: A => OptionT[F, B]): OptionT[F, B] =
      OptionT {
        F.flatMap(fa.value) {
          case None => F.pure(None)
          case Some(a) => f(a).value
        }
      }
  }
}

Running this code gives this error messages:

<console>:37: error: not found: type ?
         new Monad[OptionT[F, ?]] {
                              ^
<console>:37: error: OptionT[F,<error>] takes no type parameters, expected: one
         new Monad[OptionT[F, ?]] {

I'm running this in the REPL launched with sbt console and this build.sbt file:

name := "Scala Playground"

version := "1.0"

scalaVersion := "2.11.1"

libraryDependencies += "org.typelevel" %% "cats" % "0.6.1"

PS: Also, it's not very clear what's the point of this last exercise nor the result it should give... Maybe some extra explanation would make it easier to understand, especially about the type parameters' meanings in OptionT and optionTMonad...

First example in Semigroups does not work on current web-site

Hi all I've found inconsistency in first exercise of exercises-cats. More precisely code on server is using modified example where https://github.com/scala-exercises/exercises-cats/blob/master/src/main/scala/catslib/Semigroup.scala#L48 was split to two. But text on the website is still using the old one. What is the update process of the web-site? Should I file an issue?
To put it simply, first exercise in https://www.scala-exercises.org/cats/semigroup does not work.

Steps to reproduce:

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.