如何处理`Reader` monad和`Try`?

时间:2014-09-20 14:05:39

标签: scala dependency-injection monads scalaz

我正在读这篇关于dependency injection in scala with Reader monad的精彩文章。

原始示例运行良好,但我对UserRepository.get/find的返回类型做了一些改动。它是User,但我将其更改为Try[User]

然后代码将不会编译,我尝试了很多次,但仍然没有幸运。

import scala.util.Try
import scalaz.Reader

case class User(email: String, supervisorId: Int, firstName: String, lastName: String)

trait UserRepository {
  def get(id: Int): Try[User]

  def find(username: String): Try[User]
}

trait Users {

  def getUser(id: Int) = Reader((userRepository: UserRepository) =>
    userRepository.get(id)
  )

  def findUser(username: String) = Reader((userRepository: UserRepository) =>
    userRepository.find(username)
  )
}

object UserInfo extends Users {

  def userEmail(id: Int) = {
    getUser(id) map (ut => ut.map(_.email))
  }

  def userInfo(username: String) =
    for {
      userTry <- findUser(username)
      user <- userTry     // !!!!!!!! compilation error
      bossTry <- getUser(user.supervisorId)
      boss <- bossTry     // !!!!!!!! compilation error
    } yield Map(
      "fullName" -> s"${user.firstName} ${user.lastName}",
      "email" -> s"${user.email}",
      "boss" -> s"${boss.firstName} ${boss.lastName}"
    )
}

编译错误是:

Error:(34, 12) type mismatch;
 found   : scala.util.Try[Nothing]
 required: scalaz.Kleisli[scalaz.Id.Id,?,?]
      user <- userTry
           ^

Error:(36, 12) type mismatch;
 found   : scala.util.Try[scala.collection.immutable.Map[String,String]]
 required: scalaz.Kleisli[scalaz.Id.Id,?,?]
      boss <- bossTry
           ^

我阅读了Kleisli.flatMap的文档(返回类型为findUsergetUserKleisli),它要求参数类型为:

B => Kleisli[M, A, C]

由于Try不是Kleisli,因此存在此类错误。

我不确定如何处理它。我可以在这里使用scala.util.Try吗?如何将其转换为KLeisli类型?我怎样才能使这个例子有效?

1 个答案:

答案 0 :(得分:20)

你可以使用ReaderT monad变换器将Reader monad和Try monad组成一个monad,你可以使用for - 理解等等

ReaderT只是Kleisli的类型别名,您可以使用Kleisli.kleisli代替Reader.apply来构建Reader - y计算。请注意,Try的monad实例需要scalaz-contrib(或者您可以编写自己的实例 - 它非常简单。)

import scala.util.Try
import scalaz._, Scalaz._
import scalaz.contrib.std.utilTry._

case class User(
  email: String,
  supervisorId: Int,
  firstName: String,
  lastName: String
)

trait UserRepository {
  def get(id: Int): Try[User]

  def find(username: String): Try[User]
}

trait Users {
  def getUser(id: Int): ReaderT[Try, UserRepository, User] =
    Kleisli.kleisli(_.get(id))

  def findUser(username: String): ReaderT[Try, UserRepository, User] =
    Kleisli.kleisli(_.find(username))
}

现在已经完成了,UserInfo更加简单(现在也可以编译!):

object UserInfo extends Users {
  def userEmail(id: Int) = getUser(id).map(_.email)

  def userInfo(
    username: String
  ): ReaderT[Try, UserRepository, Map[String, String]] =
    for {
      user <- findUser(username)
      boss <- getUser(user.supervisorId)
    } yield Map(
      "fullName" -> s"${user.firstName} ${user.lastName}",
      "email" -> s"${user.email}",
      "boss" -> s"${boss.firstName} ${boss.lastName}"
    )
}

我们可以证明它有效:

import scala.util.{ Failure, Success }

val repo = new UserRepository {
  val bar = User("bar@mcfoo.com", 0, "Bar", "McFoo")
  val foo = User("foo@mcbar.com", 0, "Foo", "McBar")

  def get(id: Int) = id match {
    case 0 => Success(bar)
    case 1 => Success(foo)
    case i => Failure(new Exception(s"No user with id $i"))
  }

  def find(username: String) = username match {
    case "bar" => Success(bar)
    case "foo" => Success(foo)
    case other => Failure(new Exception(s"No user with name $other"))
  }
}

然后:

UserInfo.userInfo("foo").run(repo).foreach(println)
Map(fullName -> Foo McBar, email -> foo@mcbar.com, boss -> Bar McFoo)

与运行Reader的方式完全相同,但最后会得到Try