我无法更改的函数返回Scalaz Reader
,
type Action[A] = Reader[Session, A]
def findAccount(s: String): Action[Account] =
Reader((session: Session) => Account(s))
我想创建一个基于
findAccount(...)
的新函数以返回ReaderT[Option, Session, A]
,如type ActionT[A] = ReaderT[Option, Session, A]
def findAccountT(s: String): ActionT[Account] = findAccount(s).map(Option(_))
因为最终我想这样做
def findAccBalT(accountNumber: String) = for {
acc <- findAccountT(accountNumber)
bal <- findBalanceT(acc)
} yield bal
如何进行?是否有意义?谢谢
全面披露,
import scalaz._
import Scalaz._
trait Session {
def doSomething(): Unit
}
case class Account(number: String) extends AnyVal
case class Amount(value: Int, currency: String)
case class DBSession() extends Session {
override def doSomething = println("writing to db")
}
type Action[A] = Reader[Session, A]
type ActionT[A] = ReaderT[Option, Session, A]
def findAccount(s: String): Action[Account] =
Reader((session: Session) => Account(s))
def findBalance(account: Account): Action[Amount] =
Reader((session: Session) => Amount(333, "S$"))
// failed
def findAccountT(s: String): ActionT[Account] = findAccount(s).map(Option(_))
// failed
def findBalanceT(account: Account): ActionT[Amount] = findBalance(account).map(Option(_))
// failed
def findAccBalT(accountNumber: String) = for {
acc <- findAccountT(accountNumber)
bal <- findBalanceT(acc)
} yield bal
最佳答案
简短答案:您可以使用mapK
。
Reader[A]
是ReaderT[Id, A]
的类型别名,ReaderT
是Kleisli
的别名。 Id[A]
与A
相同。
在Kleisli
ScalaDoc中,我们找到 mapK
:
def mapK[N[_], C](f: (M[B]) => N[C]): Kleisli[N, A, C]
由于我们知道
Reader[Session, A]
与Kleisli[Id, Session, A]
相同,因此我们可以使用mapK
转到Kleisli[Option, Session, A]
:import scalaz._, Scalaz._
type Session = String
type Action[A] = Reader[Session, A]
type ActionT[A] = ReaderT[Option, Session, A]
val action: Action[String] = Reader(s => s)
val actionT: ActionT[String] = action mapK Option.apply