使用State Monad实施存储库(一起使用IO和State)

时间:2019-03-18 19:43:06

标签: scala functional-programming monads scala-cats

我有这个存储库:

trait TrainRepository {
  def get(trainId: TrainId): IO[Option[Train]]
  def getAll: IO[List[Train]]
  def save(train: Train): IO[Train]
}

我想提供一个使用State Monad的内存实现。 但是我被困住了:

  • 如果我扩展特征,我将受制于IO[...]类型,因此我相信我将无法使用State Monad。
  • 我需要使用自然变换吗?
  • 我需要使用免费的Monad吗? (我宁愿不这样做)

你会怎么做?

编辑以提供更多上下文:

trait TrainRepository[F[_]] {
  def get(trainId: TrainId): F[Option[Train]]
  def save(train: Train): F[Train]
}

class TrainService[F[_]](repository: TrainRepository[F])(implicit monad: Monad[F]) {
  def reservation(id: TrainId): F[Train] =
    for{
      train <- repository.get(id)
      updatedTrain <- train match {
        case None => monad.pure("test") // return error here
        case Some(train) => monad.pure(train.bookSeat) 
      }
      _ <- repository.save(updatedTrain)
    } yield updatedTrain
}


type TrainStateRepository[A] = State[Map[TrainId, Train], A]

val inMemoryTrainRepository = new TrainRepository[TrainStateRepository] {
  override def get(trainId: TrainId): TrainStateRepository[Option[Train]] = ???

  override def save(train: Train): TrainStateRepository[Train] = ???
}


val postgresTrainRepository = new TrainRepository[IO] {
  override def get(trainId: TrainId): IO[Option[Train]] = ???

  override def save(train: Train): IO[Train] = ???
}


val testTrainService = new TrainService[IO](inMemoryTrainRepository)
// The error is here ^^^^
// I cannot mix IO and State

val prodTrainService = new TrainService[IO](postgresTrainRepository)

1 个答案:

答案 0 :(得分:1)

您可以引入类型参数以抽象您的monad:

process.env.REACT_APP_BACKEND_BASEURL

然后您使用状态monad的实现看起来像

trait TrainRepository[F[_]] {
  def get(trainId: TrainId): F[Option[Train]]
  def getAll: F[List[Train]]
  def save(train: Train): F[Train]
}