diff --git a/.gitignore b/.gitignore index 9c07d4a..349cac9 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,18 @@ *.class *.log + +# sbt specific +.cache/ +.history/ +.lib/ +dist/* +target/ +lib_managed/ +src_managed/ +project/boot/ +project/plugins/project/ + +# Scala-IDE specific +.scala_dependencies +.worksheet +.idea \ No newline at end of file diff --git a/build.sbt b/build.sbt new file mode 100644 index 0000000..d36719d --- /dev/null +++ b/build.sbt @@ -0,0 +1,15 @@ +name := "ScalaLabs" + +version := "1.0" + +scalaVersion := "2.12.8" + +libraryDependencies += "org.typelevel" %% "cats-effect" % "1.3.0" withSources() withJavadoc() + +scalacOptions ++= Seq( + "-feature", + "-deprecation", + "-unchecked", + "-language:postfixOps", + "-language:higherKinds", + "-Ypartial-unification") \ No newline at end of file diff --git a/project/build.properties b/project/build.properties new file mode 100644 index 0000000..f37b0aa --- /dev/null +++ b/project/build.properties @@ -0,0 +1 @@ +sbt.version = 1.3.10 \ No newline at end of file diff --git a/src/main/scala/CatsEffect.scala b/src/main/scala/CatsEffect.scala new file mode 100644 index 0000000..468e1a4 --- /dev/null +++ b/src/main/scala/CatsEffect.scala @@ -0,0 +1,39 @@ +import cats.CommutativeApply.ops.toAllCommutativeApplyOps +import cats.syntax.all._ +import cats.instances.list._ +import cats.effect._ +import cats.effect.concurrent.{MVar, Ref, Semaphore} +import scala.concurrent.duration._ +import scala.concurrent.ExecutionContext + + +object CatsEffect extends IOApp { + + def runPrinter(mVar: MVar[IO, String]): Resource[IO, Unit] = { + def rec: IO[Unit] = for { + value <- mVar.take + _ <- IO(println(value)) + _ <- rec + } yield () + + Resource.make(rec.start)(_.cancel.flatMap(_ => IO(println("Printer closed")))).void + } + + def runCounter(mVar: MVar[IO, String]): Resource[IO, Unit] = { + def rec(counter: Int): IO[Unit] = for { + _ <- mVar.put((counter).toString) + _ <- IO.sleep(1.seconds) + _ <- rec(counter + 1) + } yield () + + Resource.make(rec(0).start)(_.cancel.flatMap(_ => IO(println("Counter closed")))).void + } + + val runProgram: Resource[IO, Unit] = for { + mVar <- Resource.make(MVar.empty[IO, String])(_ => IO(print(""))) + _ <- runPrinter(mVar) + _ <- runCounter(mVar) + } yield() + + override def run(args: List[String]): IO[ExitCode] = runProgram.use(_ => IO.never) +}