Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Haskell 如何编写状态Monad的实例_Haskell_State Monad - Fatal编程技术网

Haskell 如何编写状态Monad的实例

Haskell 如何编写状态Monad的实例,haskell,state-monad,Haskell,State Monad,我对哈斯凯尔的monads非常陌生,我正试图通过monads ny开发我的知识,创建一些实例,但我真的很困惑这一点,我遇到了一些错误,并且已经尝试了一段时间,因为我仍然不确定是否需要任何帮助和解释,这是我迄今为止所拥有的,你知道我哪里出错了吗 newtype ST b = S (Int -> (b, Int)) runState :: ST b -> Int -> (b, Int) runState (S b) st = b st instance Monad ST wh

我对哈斯凯尔的monads非常陌生,我正试图通过monads ny开发我的知识,创建一些实例,但我真的很困惑这一点,我遇到了一些错误,并且已经尝试了一段时间,因为我仍然不确定是否需要任何帮助和解释,这是我迄今为止所拥有的,你知道我哪里出错了吗

newtype ST b = S (Int -> (b, Int))
runState :: ST b  -> Int -> (b, Int)
runState (S b) st = b st 

instance Monad ST where 
return :: b -> ST b
return x = S (\st -> (x, st))       the new state with a b 

(>>=) :: ST b -> (b -> ST c) -> ST c
c >>= c' = S (\st1 ->
                let (b, st2) = runState c st1
                    (c, st3) = runState (c' b) st2
                in  (c, st3))

您可能还必须给出Applicational和Functor的实现:

导入控件。应用程序
进口管制。Monad(liftM,ap)
新类型ST b=S(Int->(b,Int))
运行状态::stb->Int->(b,Int)
运行状态(SB)st=b st
实例Monad ST where
--return::b->stb
return x=S(\st->(x,st))--接受当前状态并返回带有b的新状态
--(>>=)::stb->(b->stc)->stc
c>>=c'=S(\st1->
设(b,st2)=运行状态c st1
(c'',st3)=运行状态(c'b)st2
在(c',st3)中)
实例应用程序stwhere
纯=返回
()=ap
实例函子ST where
fmap=liftM

我发现。

在同一个声明中,不应该对不同的变量使用相同的变量名:
c>=…
(c,st3)=…
@md2perpe哦,等等,这是因为我在绑定函数中使用了c,所以在下一行我应该使用其他东西是吗<代码>(>>=)::ST b->(b->ST c)->ST c行中的
c
(>>=)::ST b->(b->ST c)->ST c与
c>=…
中的
c
不冲突,因为在第一种情况下它是一个类型变量,而在后一种情况下它是一个普通(值)变量。我提到的是,在
>=
的左边有一个
c
,然后在
(c,st3)=……
中引入另一个
c
。将后一个重命名为
t'
Monad
,其他可以是:
newtype ST b=S(Int->(b,Int))通过状态Int派生(Functor,Applicative,Monad,MonadFix)