天道酬勤,学无止境

monads

Implementation of flatMap() for State transition

问题 练习 6.8,Chiusano 和 Bjarnason, Scala 中的函数式编程,p。 87 询问如何为以下特征实现 flatMap(): trait RNG { def nextInt: (Int, RNG) } type Rand[+A] = RNG => (A, RNG) 答案键给出了以下解决方案: def flatMap[A,B](f: Rand[A])(g: A => Rand[B]): Rand[B] = rng => { val (a, r1) = f(rng) g(a)(r1) // We pass the new state along } Stackoverflow 为 flatMap()/monad 问题提供了许多答案,但对我来说,没有一个回答我关于倒数第二行代码的问题。 我不明白该行的语法 g(a)(r1) (1) 我不明白 g(a)(r1) 如何评估。 (r1) 提供什么句法功能? 我不相信该行没有例示柯里化,因为 g 只接受一个参数:A。 (2) 如果 g(a) 已经返回类型 Rand[B],那么为什么该行不在这里结束? (3) g(a) 返回的 Rand[B] 与第二组括号 (r1) 之间的关系是什么? (4) 如果flatMap()的这个实现的返回类型是Rand[B],等于RNG => (A, RNG),那么箭头右边的圆括号是怎么产生的?

2022-05-17 03:27:20    分类:技术分享    scala   functional-programming   monads   state-monad   flatmap

Maybe monad construction

问题 我目前正在努力解决 Haskell 的一个新元素:Monads。 因此,我通过创建(>>=)运算符的示例介绍了这一点,该运算符仅在不等于Nothing时才在Maybe类型上执行函数(将其实际整数值作为参数),否则返回Nothing : (>>=) :: Maybe a -> (a -> Maybe b) -> Maybe b Nothing >>= _ = Nothing (Just x) >>= f = f x 但是,我不太确定它的以下用法如何工作: eval (Val n) = Just n eval (Div x y) = eval x >>= (\n -> eval y >>= (\m -> safediv n m)) 在我看来, (>>=)运算符只需要一个Maybe值和一个返回 1 的函数,但是在此示例使用代码中,它似乎需要 2 倍Maybe值和一次函数。 但是有人告诉我,它评估x ,将结果放入n ,然后评估y ,将结果放入y ,然后在两者上执行safediv函数。 虽然我看不到(>>=)运算符如何在这里发挥作用; 这是如何运作的? 回答1 你可以这样读: eval (Div x y) = eval x >>= (\n -> eval y >>= (\m -> safediv n m)) 当你想做eval (Div xy)然后 第一个eval x : 如果Just

2022-05-09 07:28:05    分类:技术分享    haskell   monads   maybe

Lift a function and its argument to a different monadic context

问题 我不确定如何科学准确地表述这个问题,所以我只是给你看一个例子。 我在StateT变压器中使用状态。 底层是IO 。 在StateT IO操作中,我需要使用alloca 。 但是,我无法将alloca提升到StateT IO ,因为它需要类型为(Ptr a -> IO a)的参数,而我要求它使用(Ptr a -> StateT IO MyState a)的参数。 (但是,这是一个关于 monad 转换器的通用问题,而不是特定于IO 、 StateT或alloca的问题。) 我想出了以下可行的解决方案: -- for reference -- alloca :: (Storable a) => (Ptr a -> IO b) -> IO b allocaS :: (Storable a) => (Ptr a -> StateT s IO b) -> StateT s IO b allocaS f = do state <- get (res, st) <- liftIO $ alloca $ \ptr -> (runStateT (f ptr) state) put st return res 但是,在我看来,我应该对StateT操作进行解构和重构以便将其与alloca一起使用,这似乎是错误的。 此外,我不止一次地在某些变体中看到过这种模式

2022-05-08 11:58:08    分类:技术分享    haskell   monads

What can the Reader monad do that applicative functions cannot?

Having read http://learnyouahaskell.com/functors-applicative-functors-and-monoids#applicative-functors , I can provide an example of the use of functions as applicative functors: Let's say res is a function of 4 arguments and fa, fb, fc, fd are all functions that take a single argument. Then, if I'm not mistaken, this applicaive expression: f <$> fa <*> fb <*> fc <*> fd $ x Means the same as this non-fancy expression: f (fa x) (fb x) (fc x) (fd x) Ugh. Took me quite a bit of time to understand why this is the case, but - with the help of a sheet of paper with my notes - I should be able to

2022-05-01 15:42:32    分类:问答    haskell   monads   applicative   reader-monad

Question about the Writer monad as taught in LYAH. (How did the appending to the log take place?)

I'm learning Haskell from the "Learn you a Haskell for Great Good" tutorial and I've got to the part on writer monads. Here's the example that I can't figure out. import Control.Monad.Writer logNumber :: Int -> Writer [String] Int logNumber x = writer (x, ["Got number: " ++ show x]) multWithLog :: Writer [String] Int multWithLog = do a <- logNumber 3 b <- logNumber 5 return (a*b) -- shouldn't return (3*5) result in (15,[]) ? ghci> runWriter $ multWithLog (15,["Got number: 3","Got number: 5"]) -- how did that happen? I am trying understand how the monoidic value w in the Writer w a monad

2022-04-30 17:11:38    分类:问答    haskell   monads   monoids   do-notation   writer-monad

Does the function monad really offer something more than the function applicative functor? If so, what?

For the function monad I find that (<*>) and (>>=)/(=<<) have two strikingly similar types. In particular, (=<<) makes the similarity more apparent: (<*>) :: (r -> a -> b) -> (r -> a) -> (r -> b) (=<<) :: (a -> r -> b) -> (r -> a) -> (r -> b) So it's like both (<*>) and (>>=)/(=<<) take a binary function and a unary function, and constrain one of the two arguments of the former to be determined from the other one, via the latter. After all, we know that for the function applicative/monad, f <*> g = \x -> f x (g x) f =<< g = \x -> f (g x) x And they look so strikingly similar (or symmetric, if

2022-04-30 16:04:57    分类:问答    haskell   functional-programming   monads   applicative   combinatory-logic

Writer monad and unsequence

问题 我正在使用Writer monad 来跟踪任意值(例如Int )上的错误(“冲突”)标志。 一旦设置了标志,它就是“粘性的”,并将其自身附加到作为标记的任何操作的结果产生的所有值上。 有时碰撞标志与单个值相关联,有时我想与组合结构(例如列表)相关联。 当然,一旦为整个列表设置了冲突标志,假设它是为单个元素设置的也是有意义的。 所以对于作家 monad m我需要以下两个操作: sequence :: [m a] -> m [a] unsequence :: m [a] -> [m a] 第一个在 Prelude 中定义,而第二个必须定义。 这是关于如何使用comonads定义它的一个很好的讨论。 本机comonad 实现不保留状态。 这是一个例子: {-# LANGUAGE FlexibleInstances #-} module Foo where import Control.Monad.Writer import Control.Comonad unsequence :: (Comonad w, Monad m) => w [a] -> [m a] unsequence = map return . extract instance Monoid Bool where mempty = False mappend = (||) type CM = Writer Bool

2022-04-30 15:00:17    分类:技术分享    haskell   monads   comonad   writer-monad

Reduce nestedness when using successive Either/Maybe

This is probably a very basic Haskell question, but let's assume the following function signatures -- helper functions getWeatherInfo :: Day -> IO (Either WeatherException WeatherInfo) craftQuery :: WeatherInfo -> Either QueryException ModelQuery makePrediction :: ModelQuery -> IO (Either ModelException ModelResult) The naive way of chaining all the above into one predict day function could be: predict :: Day -> IO (Maybe Prediction) predict day = do weather <- getWeatherInfo day pure $ case weather of Left ex -> do log "could not get weather: " <> msg ex Nothing Right wi -> do let query =

2022-04-30 07:27:22    分类:问答    haskell   monads   flatten   maybe   either

Haskell: Common pattern to deal with Failure inside IO :: IO (Either String Int) [duplicate]

This question already has answers here: How do I deal with many levels of indentation? (3 answers) Closed 3 years ago. Trying to understand the pattern used to deal with possible failures inside IO. If its just one cases like below, its probably acceptable, but if the nesting goes on for a bunch of nested IO (Either String Int)s is there a common pattern to handle such types. For instance, if b in functionDoSomething is again a (Either a b) and fetching value on success and doing something with it again will be another such case. Is there a higher order function that I can use? I'm not

2022-04-30 04:32:15    分类:问答    haskell   monads

Reader monad - how does it conform to Monad interface?

问题 我正在学习范畴论。 我理解 reader monad 的概念,它甚至很容易实现: case class Reader[DEP, A](g: DEP => A) { def apply(dep: DEP): A = g(dep) def map[B](f: A => B): Reader[DEP, B] = Reader(dep => f(apply(dep))) def flatMap[B](f: A => Reader[DEP, B]): Reader[DEP, B] = Reader(dep => f(apply(dep)) apply dep) } 但是,我在限制某些通用 Monad 接口的情况下实现它时遇到问题,即 trait Monad[A] { def pure(a: A): Monad[A] def map[B](f: A => B): Monad[B] def flatMap[B](f: A => Monad[B]): Monad[B] } 让我们暂时忘记有一个应用程序或函子,让我们把这 3 个方法放在这里。 现在,有了这个接口,我在实现 ReaderMonad 时遇到了问题。 map 方法非常简单,但是 pure 和 flatMap 呢? 纯阅读器意味着什么? 要实现 flatMap,我需要一个从 A 到 Reader[DEP, B] 的函数,但是我有 A

2022-04-30 03:28:15    分类:技术分享    scala   monads   category-theory   reader-monad