Scalaz Reader to ReaderT

时间:2016-06-05 12:17:56

标签: scala scalaz scalaz7

我无法更改的函数返回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

1 个答案:

答案 0 :(得分:2)

简短回答:您可以使用mapK

Reader[A]ReaderT[Id, A]的类型别名,ReaderTKleisli的别名。 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