项目作者: ThoughtWorksInc

项目描述 :
A macro library that converts native imperative syntax to scalaz's monadic expressions
高级语言: Scala
项目地址: git://github.com/ThoughtWorksInc/each.git
创建时间: 2015-05-05T07:27:00Z
项目社区:https://github.com/ThoughtWorksInc/each

开源协议:Apache License 2.0

下载


ThoughtWorks Each

Join the chat at https://gitter.im/ThoughtWorksInc/each
Build Status
Latest version

ThoughtWorks Each is a macro library that converts native imperative syntax to Scalaz‘s monadic expression. See the object cats in Dsl.scala for the similar feature for Cats.

Motivation

There is a macro library Stateless Future that provides await for asynchronous programming.
await is a mechanism that transform synchronous-like code into asynchronous expressions. C# 5.0, ECMAScript 7 and Python 3.5 also support the mechanism.

The await mechanism in Stateless Future is implemented by an algorithm called CPS transform. When learning scalaz, we found that the same algorithm could be applied for any monadic expression, including Option monad, IO monad, and Future monad. So we started this project, Each.

Each is a superset of await syntax. Each supports multiple types of monads, while await only works with Future. When we perform a CPS transform for monadic expression with the Future monad, the use case looks almost the same as the await syntax in Stateless Future. Each is like F#’s Computation Expressions, except Each reuses the normal Scala syntax instead of reinventing new syntax.

For example:

  1. import com.thoughtworks.each.Monadic._
  2. import scalaz.std.scalaFuture._
  3. // Returns a Future of the sum of the length of each string in each parameter Future,
  4. // without blocking any thread.
  5. def concat(future1: Future[String], future2: Future[String]): Future[Int] = monadic[Future] {
  6. future1.each.length + future2.each.length
  7. }

The similar code works for monads other than Future:

  1. import com.thoughtworks.each.Monadic._
  2. import scalaz.std.option._
  3. def plusOne(intOption: Option[Int]) = monadic[Option] {
  4. intOption.each + 1
  5. }
  6. assert(plusOne(None) == None)
  7. assert(plusOne(Some(15)) == Some(16))
  1. import com.thoughtworks.each.Monadic._
  2. import scalaz.std.list._
  3. def plusOne(intSeq: List[Int]) = monadic[List] {
  4. intSeq.each + 1
  5. }
  6. assert(plusOne(Nil) == Nil)
  7. assert(plusOne(List(15)) == List(16))
  8. assert(plusOne(List(15, -2, 9)) == List(16, -1, 10))

Usage

Step 1: Add the following line in your build.sbt

  1. libraryDependencies += "com.thoughtworks.each" %% "each" % "latest.release"
  2. addCompilerPlugin("org.scalamacros" % "paradise" % "2.1.0" cross CrossVersion.full)

or %%% for Scala.js projects:

  1. libraryDependencies += "com.thoughtworks.each" %%% "each" % "latest.release"
  2. addCompilerPlugin("org.scalamacros" % "paradise" % "2.1.0" cross CrossVersion.full)

Note that ThoughtWorks Each requires Scalaz 7.2.x and does not compatible with Scala 7.1.x .

See https://repo1.maven.org/maven2/com/thoughtworks/each/ for a list of available versions.

Step 2: In your source file, import monadic and each method

  1. import com.thoughtworks.each.Monadic._

Step 3: Import implicit Monad instances

Scalaz has provided Option monad, so you just import it.

  1. import com.thoughtworks.each.Monadic._
  2. import scalaz.std.option._

Please import other monad instances if you need other monads.

Step 4: Use monadic[F] to create a monadic expression

  1. import com.thoughtworks.each.Monadic._
  2. import scalaz.std.option._
  3. val result: Option[String] = monadic[Option] {
  4. "Hello, Each!"
  5. }

Step 5: In the monadic block, use .each postfix to extract each element in a F

  1. import com.thoughtworks.each.Monadic._
  2. import scalaz.std.option._
  3. val name = Option("Each")
  4. val result: Option[String] = monadic[Option] {
  5. "Hello, " + name.each + "!"
  6. }

Exception handling

monadic blocks do not support try, catch and finally. If you want these expressions, use throwableMonadic or catchIoMonadic instead, for example:

  1. var count = 0
  2. val io = catchIoMonadic[IO] {
  3. count += 1 // Evaluates immediately
  4. val _ = IO(()).each // Pauses until io.unsafePerformIO()
  5. try {
  6. count += 1
  7. (null: Array[Int])(0) // Throws a NullPointerException
  8. } catch {
  9. case e: NullPointerException => {
  10. count += 1
  11. 100
  12. }
  13. } finally {
  14. count += 1
  15. }
  16. }
  17. assertEquals(1, count)
  18. assertEquals(100, io.unsafePerformIO())
  19. assertEquals(4, count)

Note that catchIoMonadic requires an implicit parameter scalaz.effect.MonadCatchIO[F] instead of Monad[F]. scalaz.effect.MonadCatchIO[F] is only provided for scalaz.effect.IO by default.

for loop

Each supports .each magic in a for loop on any instances that support Foldable type class. For example, you could import scalaz.std.list._ to enable the Foldable type class for List.

  1. import com.thoughtworks.each.Monadic._
  2. import scalaz.std.list._
  3. import scalaz.std.option._
  4. val n = Some(10)
  5. @monadic[Option] val result = {
  6. var count = 1
  7. for (i <- List(300, 20)) {
  8. count += i * n.each
  9. }
  10. count
  11. }
  12. Assert.assertEquals(Some(3201), result)

Note that you need to use @monadic[Option] annotation instead of monadic[Option] block to in order to enable the for loop syntax.

for comprehension

Each also supports .each magic in a for comprehension on any instances that support Traverse and MonadPlus type class.

  1. import com.thoughtworks.each.Monadic._
  2. import scalaz.std.list._
  3. val n = Some(4000)
  4. @monadic[Option] val result = {
  5. for {
  6. i <- List(300, 20)
  7. (j, k) <- List(50000 -> "1111", 600000 -> "yyy")
  8. if i > n.each - 3900
  9. a = i + j
  10. } yield {
  11. a + n.each * k.length
  12. }
  13. }
  14. Assert.assertEquals(Some(List(66300, 612300)), result)

Note that you need to use @monadic[Option] annotation instead of monadic[Option] block to in order to enable the for comprehension syntax.

Limitation

If a call-by-name parameter of a method call is a monadic expression, Each will transform the monadic expression before the method call. The behavior was discussed at #37.

  1. def innerFailureFuture = Future.failed(new Exception("foo"))
  2. val someValue = Some("value")
  3. val result = monadic[Future] {
  4. someValue.getOrElse(innerFailureFuture.each)
  5. }

result will be a future of failure because the above example equals to

  1. def innerFailureFuture = Future.failed(new Exception("foo"))
  2. val someValue = Some("value")
  3. val result = innerFailureFuture.map(someValue.getOrElse)

innerFailureFuture.each is evaluated before being passed to getOrElse method call, even if getOrElse accepts a call-by-name parameter.