Haskell 哈斯克尔代码赢得';不编译

Haskell 哈斯克尔代码赢得';不编译,haskell,compiler-errors,Haskell,Compiler Errors,我正在努力学习哈斯克尔,所以我想我会马上跳进去尝试单子。请参阅下面我的Calc实现。这与状态monad类似,只是状态始终是一个用于缓存结果的映射。每个Calc都有自己的GUID(尚未实现),该GUID用作从映射中检索缓存值的键 import qualified Data.Map as Map import Control.Monad import Data.Dynamic type CalcId = Int type Ctx = Map.Map CalcId Dynamic data Ca

我正在努力学习哈斯克尔,所以我想我会马上跳进去尝试单子。请参阅下面我的Calc实现。这与状态monad类似,只是状态始终是一个用于缓存结果的映射。每个Calc都有自己的GUID(尚未实现),该GUID用作从映射中检索缓存值的键

import qualified Data.Map as Map
import Control.Monad
import Data.Dynamic

type CalcId = Int

type Ctx = Map.Map CalcId Dynamic

data Calc a = Calc { eval :: Ctx -> (a, Ctx),
                 guid :: CalcId }

instance Monad Calc where
    (>>=) :: Calc a -> (a -> Calc b) -> Calc b
    c1 >>= f = Calc {eval=c2Eval, guid=c2Id}
        where c2Id = 1 -- need a way of generating a GUID. add later.
              c2Eval = \ctx -> 
                    case (Map.lookup c2Id ctx >>= fromDynamic) :: Maybe b of
                        Just c2Val -> 
                            (c2Val, ctx)
                        Nothing ->
                            let (c1Val, ctx') = eval c1 ctx
                                c2 = f c1Val
                                (c2Val', _) = eval c2 ctx'
                                ctx'' = Map.insert c2Id (toDyn c2Val') ctx'
                            in (c2Val', ctx'')
这段代码可能有很多问题。但现在我真的很想把它编译出来。编译器错误如下

No instance for (Typeable b1) arising from a use of `fromDynamic'
Possible fix:
  add (Typeable b1) to the context of
    an expression type signature: Maybe b1
    or the type signature for >>= :: Calc a -> (a -> Calc b) -> Calc b
In the second argument of `(>>=)', namely `fromDynamic'
In the expression: (Map.lookup c2Id ctx >>= fromDynamic) :: Maybe b
In the expression:
  case (Map.lookup c2Id ctx >>= fromDynamic) :: Maybe b of {
    Just c2Val -> (c2Val, ctx)
    Nothing
      -> let
           (c1Val, ctx') = ...
           ....
         in (c2Val', ctx'') }

No instance for (Typeable b) arising from a use of `toDyn'
Possible fix:
  add (Typeable b) to the context of
    the type signature for >>= :: Calc a -> (a -> Calc b) -> Calc b
In the second argument of `Map.insert', namely `(toDyn c2Val')'
In the expression: Map.insert c2Id (toDyn c2Val') ctx'
In an equation for ctx'':
    ctx'' = Map.insert c2Id (toDyn c2Val') ctx'

问题是,对于动态值,需要将对象添加到可类型类的成员中。你的下一个问题是你的monad只能在typeable上工作。你的第三个问题是,你不能让它成为单子,因为单子必须能够包含任何东西。看一看。

问题是,对于动态值,需要输入可类型类的成员。你的下一个问题是你的monad只能在typeable上工作。你的第三个问题是,你不能让它成为单子,因为单子必须能够包含任何东西。看一看。

谢谢,我将通读以更好地理解可键入类和RMonadsLook up类型类以及类型签名约束。谢谢,我将通读以更好地理解可键入类和RMonadsLook up类型类以及类型签名约束。