天道酬勤,学无止境

monad-transformers

Scala Free Monads with Coproduct and monad transformer

问题 我正在尝试在我的项目中开始使用免费的 monad,我正在努力让它变得优雅。 假设我有两个上下文(实际上我有更多) - Receipt和User - 都对数据库进行操作,我希望将他们的解释器分开并在最后一刻组合它们。 为此,我需要为每个操作定义不同的操作,并使用Coproduct将它们组合成一种类型。 这是我经过几天的谷歌搜索和阅读后得到的: // Receipts sealed trait ReceiptOp[A] case class GetReceipt(id: String) extends ReceiptOp[Either[Error, ReceiptEntity]] class ReceiptOps[F[_]](implicit I: Inject[ReceiptOp, F]) { def getReceipt(id: String): Free[F, Either[Error, ReceiptEntity]] = Free.inject[ReceiptOp, F](GetReceipt(id)) } object ReceiptOps { implicit def receiptOps[F[_]](implicit I: Inject[ReceiptOp, F]): ReceiptOps[F] = new ReceiptOps[F] } // Users

2022-05-16 16:31:16    分类:技术分享    scala   monad-transformers   scala-cats   free-monad

Is there a library or typeclass for getting the transformer version of a monad?

问题 在我目前的项目中,我遇到了将各种 monad 变成它们的变压器对应物的需要,例如 stateT :: Monad m => State s a -> StateT s m a stateT stf = StateT $ return . runState stf 为我需要的 monad 编写这些实用函数很简单,但我想知道是否已经存在一个包含标准 monad 的此功能的库,也许还有一个抽象这种转换的类型类。 就像是 class (Monad f, MonadTrans t) => LiftTrans f t | f -> t where liftT :: Monad m => f a -> t m a (“提升”在这里可能是错误的术语,但我不知道还能叫什么。) 回答1 从 mmorph 包中查看函数hoist 。 它的签名是 hoist :: Monad m => (forall a. m a -> n a) -> t m b -> t n b 这意味着它可以改变变压器底层的基本单子。 现在,在trasformers包中,许多“基本” monad 被实现为应用于Identity monad 的转换器,如下所示: type State s = StateT s Identity 因此,我们可以定义以下函数(取自mmorph文档的 Generalizing base monads

2022-05-06 17:45:11    分类:技术分享    haskell   monad-transformers

Scala Free Monads with Coproduct and monad transformer

I'm trying to start using free monads in my project and I'm struggling to make it elegant. Let's say I have two contexts (in reality I have more) - Receipt and User - both have operations on a database and I would like to keep their interpreters separate and compose them at the last moment. For this I need to define different operations for each and combine them into one type using Coproduct. This is what I have after days of googling and reading: // Receipts sealed trait ReceiptOp[A] case class GetReceipt(id: String) extends ReceiptOp[Either[Error, ReceiptEntity]] class ReceiptOps[F[_]]

2022-05-02 06:00:55    分类:问答    scala   monad-transformers   scala-cats   free-monad

Is there a library or typeclass for getting the transformer version of a monad?

In my current project I've run into the need to turn various monads into their transformer counterparts e.g. stateT :: Monad m => State s a -> StateT s m a stateT stf = StateT $ return . runState stf It's trivial to write these utility functions for the monads I need, but I was wondering if there already exists a library that contains this functionality for the standard monads and maybe a typeclass that abstracts this sort of transformation. Something like class (Monad f, MonadTrans t) => LiftTrans f t | f -> t where liftT :: Monad m => f a -> t m a ("lift" is probably the wrong term to use

2022-04-29 19:20:24    分类:问答    haskell   monad-transformers

State and IO Monads

问题 我一直在尝试围绕单子的概念进行思考,并且一直在尝试以下示例: 我有一个Editor数据类型,它表示文本文档的状态和一些在它上面工作的函数。 data Editor = Editor { lines :: [Line], -- editor contents are kept line by line lineCount :: Int, -- holds length lines at all times caret :: Caret -- the current caret position -- ... some more definitions } deriving (Show) -- get the line at the given position (first line is at 0) lineAt :: Editor -> Int -> Line lineAt ed n = ls !! n where ls = lines ed -- get the line that the caret is currently on currentLine :: Editor -> Line currentLine ed = lineAt ed $ currentY ed -- move the caret horizontally by the specified

2022-04-26 20:25:21    分类:技术分享    haskell   monads   monad-transformers   state-monad

scalaz List[StateT].sequence - could not find implicit value for parameter n: scalaz.Applicative

I'm trying to figure out how to use StateT to combine two State state transformers based on a comment on my Scalaz state monad examples answer. It seems I'm very close but I got an issue when trying to apply sequence. import scalaz._ import Scalaz._ import java.util.Random val die = state[Random, Int](r => (r, r.nextInt(6) + 1)) val twoDice = for (d1 <- die; d2 <- die) yield (d1, d2) def freqSum(dice: (Int, Int)) = state[Map[Int,Int], Int]{ freq => val s = dice._1 + dice._2 val tuple = s -> (freq.getOrElse(s, 0) + 1) (freq + tuple, s) } type StateMap[x] = State[Map[Int,Int], x] val

2022-04-26 14:33:21    分类:问答    scala   scalaz   monad-transformers   state-monad

bind a monadic value (m2 a) inside some other monad m1

问题 今天在编码道场工作我尝试了以下 example :: IO () example = do input <- getLine parsed <- parseOnly parser input ... where parseOnly :: Parser a -> Either String a (来自attoparsec )当然编译器抱怨说Either ..不是IO ..本质上告诉我我正在混合 monad。 当然可以通过以下方式解决 case parseOnly parser input of .. -> .. 我认为这有点不雅。 另外我的猜测是其他人早些时候遇到了这个问题,我认为解决方案与单子变压器有关,但最后一点我无法拼凑起来。 它也让我想起了liftIO - 但这是我认为的另一种方式,它解决了在一些周围的 monad(更准确地说MonadIO - 例如当一个人想要在获取时将某些内容打印到stdout时在Snap一些http)。 更一般地说,这个问题似乎是针对Monad m1和(不同的) Monad m2我该怎么做 example = do a <- m1Action b <- m2Action .. 回答1 一般来说,你不能。 整个 do 块必须是一个特定的 monad(因为example需要有一些特定的类型)。 如果您可以在 do 块内绑定任意其他 monad

2022-04-24 02:37:47    分类:技术分享    haskell   monads   monad-transformers

Stateful computation with different types of short-circuit (Maybe, Either)

问题 我试图找到将以下有状态命令式代码转换为纯函数表示的最优雅的方法(最好在 Haskell 中使用其 Monad 实现提供的抽象)。 但是我还不擅长使用变压器等组合不同的单子。 在我看来,分析他人对此类任务的看法对自己学习如何做最有帮助。 命令式代码: while (true) { while (x = get()) { // Think of this as returning Maybe something put1(x) // may exit and present some failure representation } put2() // may exit and present some success representation } 当get返回Nothing我们需要执行以继续put2 ,当get返回Just x我们希望x传递给put1并且仅当put1失败或循环时才短路。 基本上put1和put2可能会终止整个事情或移动到以下语句以某种方式改变底层状态。 get可以成功并调用put1并循环,也可以失败并继续put2 。 我的想法是: forever $ do forever (get >>= put1) put2 为什么我要寻找类似的东西是因为(get >>= put1)可以简单地短路,只要get没有任何返回或put1终止。 同样put2终止外循环。 但是

2022-04-22 05:58:21    分类:技术分享    haskell   functional-programming   monad-transformers   state-monad   imperative-programming

Using servant with ReaderT IO a

问题 我正在为我的servant API 使用服务库。 我需要一些帮助才能使ServerT MyAPI (ReaderT a IO) monad 堆栈正常工作。 这是一个使用ReaderT的示例,但没有将其与服务人员集成: -- this code works type TestAPI = "a" :> Get '[JSON] String :<|> "b" :> Get '[JSON] String test2 :: EitherT ServantErr IO String test2 = return "asdf" testServer :: Int -> Server TestAPI testServer code = test :<|> test2 where test :: EitherT ServantErr IO String test = liftIO $ runReaderT (giveMeAMessage) code -- this is contrived. In my real application I want to use a Reader for the database connection. giveMeAMessage :: ReaderT Int IO String giveMeAMessage = do code <- ask name <

2022-04-21 10:25:16    分类:技术分享    haskell   monads   monad-transformers