【发布时间】:2020-10-19 13:26:45
【问题描述】:
我是 Haskell(和 CS)初学者。我正在通过haskellbook 工作。我正在为StateT 实现Applicative 实例,其中StateT 定义为:
newtype StateT s m a = StateT { runState :: s -> m (a, s) }
书中提到,要为StateT s m 创建一个Applicative 实例,我们需要对m 进行Monad 约束,而不是像人们所期望的那样使用Applicative 约束。对于书中引用的 SO 答案,我在阅读已接受的answer 时也得出了相同的结论。
但是,为了更好地理解,我尝试在m 上创建具有Applicative 约束的Applicative 实例,并成功编译。我还尝试了一些示例,它似乎工作正常。有人可以解释一下,这里有什么问题吗?
instance (Applicative m) => Applicative (StateT s m) where
pure a = StateT $ \s -> pure $ (a, s)
(<*>) :: (StateT s m (a -> b)) -> (StateT s m a) -> (StateT s m b)
(StateT smf) <*> (StateT sma) = StateT $ \s -> (f) <$> (smf s) <*> (sma s)
where
f :: (a -> b, s) -> (a, s) -> (b, s)
f (ff, s) = \(a, s) -> (ff a,s)
*StateT> s1 = StateT (\s -> return (4, s))
*StateT> s2 = map (+) s1
*StateT> s3 = StateT (\s -> return (20, s))
*StateT> runState (s2 <*> s3) * 10
(24,10)
*StateT>
编辑:正如@Koterpillar 建议我尝试使用状态也被修改的示例。我尝试使用this 示例。此外,here 是 Monad 约束版本,我认为它的行为也不尽如人意。我认为问题在于各州没有以某种方式联系在一起。如果有人能对这个话题有所了解,我将不胜感激。
【问题讨论】:
-
请用修改状态的
smf和sma试试这个。 -
请删除 png 并替换为格式化文本。
-
@Michael Litchard 现在可以了吗?抱歉,我应该先发布文本。
-
看起来不错。谢谢。 :)
标签: haskell functional-programming state monads applicative