Convert Figma logo to code with AI

scala-exercises logoscala-exercises

The easy way to learn Scala.

2,624
544
2,624
67

Top Related Projects

5,233

Lightweight, modular, and extensible library for functional programming.

1,926

Asynchronous, Reactive Programming for Scala and Scala.js.

2,483

Yet another JSON library for Scala

A testing tool for Scala and Java developers

4,670

Principled Functional Programming in Scala

Quick Overview

The scala-exercises/scala-exercises repository is a collection of interactive exercises and lessons for the Scala programming language. It aims to provide a comprehensive learning platform for both beginners and experienced Scala developers, covering a wide range of topics from the language's core features to advanced functional programming concepts.

Pros

  • Interactive Learning Experience: The project offers an interactive and engaging way to learn Scala, with exercises that provide immediate feedback and guidance.
  • Comprehensive Coverage: The exercises cover a broad spectrum of Scala topics, from basic syntax and data structures to more advanced concepts like functional programming and concurrency.
  • Collaborative Learning: The platform encourages community involvement, allowing users to contribute new exercises, report issues, and collaborate on improving the learning materials.
  • Multilingual Support: The exercises are available in multiple languages, making the learning resources accessible to a wider audience.

Cons

  • Limited Offline Availability: While the exercises can be accessed online, the lack of an offline mode may be a drawback for users with limited internet connectivity.
  • Potential Outdated Content: As the Scala language and ecosystem evolve, there is a risk that some of the content may become outdated over time, requiring regular maintenance and updates.
  • Dependency on External Resources: The project relies on external resources, such as the Scala documentation and community forums, which may not always be readily available or up-to-date.
  • Steep Learning Curve: For complete beginners, the depth and breadth of the Scala language covered in the exercises may present a steep learning curve, potentially overwhelming some users.

Code Examples

Here are a few code examples from the scala-exercises/scala-exercises repository:

  1. Basic Scala Syntax:
object HelloWorld extends App {
  println("Hello, World!")
}

This example demonstrates the basic syntax for defining an object and printing a message to the console.

  1. Functional Programming with Higher-Order Functions:
val numbers = List(1, 2, 3, 4, 5)
val doubledNumbers = numbers.map(x => x * 2)
println(doubledNumbers) // Output: List(2, 4, 6, 8, 10)

This example shows how to use the map higher-order function to transform a list of numbers by doubling each element.

  1. Pattern Matching:
def greet(person: Any): String = person match {
  case "Alice" => "Hello, Alice!"
  case "Bob" => "Hi, Bob!"
  case _ => "Hello, stranger!"
}

println(greet("Alice")) // Output: Hello, Alice!
println(greet("Bob")) // Output: Hi, Bob!
println(greet("Charlie")) // Output: Hello, stranger!

This example demonstrates the use of pattern matching to implement a simple greeting function based on the input value.

  1. Futures and Concurrency:
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global

val result: Future[Int] = Future {
  // Simulate a long-running computation
  Thread.sleep(2000)
  42
}

result.onComplete {
  case scala.util.Success(value) => println(s"Result: $value")
  case scala.util.Failure(exception) => println(s"Error: $exception")
}

This example demonstrates the use of Futures to handle asynchronous computations in Scala, simulating a long-running task and handling the result or any potential exceptions.

Getting Started

To get started with the scala-exercises/scala-exercises project, follow these steps:

  1. Ensure you have Scala and sbt (Scala Build Tool) installed on your system.
  2. Clone the repository:
    git clone https://github.com/scala-exercises/scala-exercises.git
    
  3. Navigate to the project directory:
    cd scala-exercises
    
  4. Start the sbt console:
    sbt
    
  5. Within the sbt console, run the following command to start the application:
    run
    
  6. The application will start, and you can access the interactive exercises by opening a web browser and navigating

Competitor Comparisons

5,233

Lightweight, modular, and extensible library for functional programming.

Pros of Cats

  • Cats is a widely-used and well-established functional programming library for Scala, providing a rich set of abstractions and type classes.
  • The library has a strong focus on modularity, allowing users to pick and choose the specific features they need.
  • Cats has a large and active community, with extensive documentation and a wealth of online resources.

Cons of Cats

  • The learning curve for Cats can be steep, especially for developers new to functional programming concepts.
  • The library can be more complex and verbose than some alternative solutions, which may be a drawback for certain use cases.
  • Cats has a relatively large dependency footprint, which may be a concern for some projects.

Code Comparison

Scala Exercises:

object HelloWorld extends App {
  println("Hello, world!")
}

Cats:

import cats.Monad
import cats.syntax.all._

object CatsExample {
  def program[F[_]: Monad](x: Int, y: Int): F[Int] =
    for {
      a <- x.pure[F]
      b <- y.pure[F]
    } yield a + b
}
1,926

Asynchronous, Reactive Programming for Scala and Scala.js.

Pros of monix/monix

  • Monix provides a rich set of abstractions and utilities for concurrent and asynchronous programming, including Task, Observable, and Scheduler.
  • The library is highly performant and optimized for use in production environments.
  • Monix has a large and active community, with extensive documentation and a wide range of third-party integrations.

Cons of monix/monix

  • The learning curve for Monix can be steeper than that of Scala Exercises, as it requires a deeper understanding of functional programming concepts.
  • Monix may be overkill for simpler projects that don't require the full range of its features.

Code Comparison

Scala Exercises:

object HelloWorld extends App {
  println("Hello, world!")
}

Monix:

import monix.eval.Task
import monix.execution.Scheduler.Implicits.global

object HelloWorld extends App {
  Task.eval(println("Hello, world!")).runSyncUnsafe()
}

The Monix version uses the Task abstraction to represent a potentially asynchronous computation, which can be executed using the runSyncUnsafe() method. This provides more control and flexibility compared to the simple println statement in the Scala Exercises example.

2,483

Yet another JSON library for Scala

Pros of circe/circe

  • Circe is a widely-used, high-performance JSON library for Scala, with a focus on type-safety and ease of use.
  • It provides a comprehensive set of features, including support for encoding, decoding, and transforming JSON data.
  • Circe has a large and active community, with a wealth of documentation, examples, and third-party integrations available.

Cons of circe/circe

  • Scala-exercises is a more comprehensive learning platform, covering a wider range of Scala topics beyond just JSON handling.
  • The Scala-exercises project may be more suitable for beginners or those looking to learn Scala from the ground up, while Circe is more focused on a specific use case.
  • Scala-exercises may have a larger learning curve for users who are primarily interested in JSON processing.

Code Comparison

Scala-exercises (scala-exercises/scala-exercises):

object JsonExercises extends FlatSpec with Matchers {
  "JSON Exercises" should "parse a simple JSON object" in {
    val json = """{"name":"John","age":30,"city":"New York"}"""
    val result = parse(json)
    result.isRight shouldBe true
    result.right.get shouldBe JObject(
      JField("name", JString("John")),
      JField("age", JNumber(30)),
      JField("city", JString("New York"))
    )
  }
}

Circe (circe/circe):

import io.circe._, io.circe.generic.auto._, io.circe.parser._

val json = """{"name":"John","age":30,"city":"New York"}"""
val result = decode[Person](json)

case class Person(name: String, age: Int, city: String)

result match {
  case Right(person) => println(person)
  case Left(error) => println(s"Decoding failed: $error")
}

A testing tool for Scala and Java developers

Pros of scalatest/scalatest

  • Widely adopted and well-established testing framework for Scala
  • Provides a rich set of features and utilities for writing comprehensive tests
  • Supports a variety of testing styles, including BDD, TDD, and more

Cons of scalatest/scalatest

  • Steeper learning curve compared to scala-exercises/scala-exercises
  • May require more boilerplate code to set up and configure tests

Code Comparison

scalatest/scalatest:

import org.scalatest.funsuite.AnyFunSuite

class MyTest extends AnyFunSuite {
  test("addition should work") {
    assert(1 + 1 === 2)
  }
}

scala-exercises/scala-exercises:

import org.scalatest.funsuite.AnyFunSuite
import org.scalatest.Matchers

class MyTest extends AnyFunSuite with Matchers {
  test("addition should work") {
    (1 + 1) shouldBe 2
  }
}

The main difference in the code is the assertion syntax. scalatest/scalatest uses the assert function, while scala-exercises/scala-exercises uses the shouldBe matcher from the Matchers trait.

4,670

Principled Functional Programming in Scala

Pros of scalaz/scalaz

  • Scalaz provides a rich set of functional programming abstractions and utilities, which can be highly useful for complex Scala projects.
  • The library has a strong focus on type-level programming, which can lead to more robust and expressive code.
  • Scalaz has a large and active community, with a wealth of resources and support available.

Cons of scalaz/scalaz

  • The learning curve for Scalaz can be steep, especially for developers new to functional programming or type-level programming.
  • The library can be opinionated and may not align with the preferences of all Scala developers.
  • Scalaz can sometimes be perceived as overly complex or difficult to integrate with other libraries or frameworks.

Code Comparison

Scala-exercises/scala-exercises:

object FunctionsExercises extends FunctionsModule with FlatSpec with Matchers {
  "Functions" should "return the square of a number" in {
    def square(x: Int): Int = x * x
    square(5) shouldBe 25
  }

  it should "return the absolute value of a number" in {
    def abs(x: Int): Int = if (x < 0) -x else x
    abs(-5) shouldBe 5
  }
}

scalaz/scalaz:

import scalaz._
import Scalaz._

object FunctionsExample {
  def square(x: Int): Int = x * x
  def abs(x: Int): Int = if (x < 0) -x else x

  def main(args: Array[String]): Unit = {
    println(square(5))   // 25
    println(abs(-5))     // 5
  }
}

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

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.