You need to enable JavaScript to run this app. 如何在Haskell中编写自定义Int状态ST的State Monad实例?报错求解
优惠活动
大模型
产品
解决方案
定价
更多

如何在Haskell中编写自定义Int状态ST的State Monad实例?报错求解

代码中的具体错误点
  • 行注释语法错误:return x = S (\st -> (x, st)) the new state with a b 这行后面的说明文本没有加Haskell的行注释标记--,编译器会直接把这串英文当成非法语法,在代码解析阶段就抛错。
  • 变量遮蔽导致的类型混乱:在(>>=)的实现里,外层第一个参数叫c,类型是ST b(也就是本身是一个状态计算函数),但在后续的let绑定中,你把运行c' b得到的结果值也命名为c,直接把外层的c变量遮蔽了。最后返回元组时的c会被编译器识别为和预期类型不匹配的内容,无法正常通过类型检查。
  • 类型类的继承约束缺失:从GHC 7.10版本开始,Monad类型类是Applicative的子类,而Applicative又继承自Functor,跳过前两个类型类的实现直接写Monad实例,会触发“没有满足父类约束”的编译报错。
修正后的可编译实现
newtype ST b = S (Int -> (b, Int))

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

instance Functor ST where
  fmap f stateFn = S $ \s ->
    let (res, s') = runState stateFn s
    in (f res, s')

instance Applicative ST where
  pure x = S (\s -> (x, s))
  (<*>) stateFn stateVal = S $ \s ->
    let (fn, s1) = runState stateFn s
        (val, s2) = runState stateVal s1
    in (fn val, s2)

instance Monad ST where
  return x = S (\st -> (x, st))

  (>>=) calc nextCalc = S (\st1 ->
    let (res, st2) = runState calc st1
        (finalRes, st3) = runState (nextCalc res) st2
    in (finalRes, st3))

你原本对ST Monad的逻辑实现思路是正确的,上述修正只是解决了语法、命名和类型类约束层面的问题,没有改动核心计算逻辑。

内容的提问来源于stack exchange,提问作者program.exe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.27 23:54:01