我无法更改的函数返回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
答案 0 :(得分:2)
简短回答:您可以使用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