gpt4 book ai didi

Scalaz Reader 到 ReaderT

转载 作者:行者123 更新时间:2023-12-02 01:25:02 24 4
gpt4 key购买 nike

我无法更改的函数返回 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] 的类型别名,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

关于Scalaz Reader 到 ReaderT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37641796/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com