gpt4 book ai didi

haskell - Haskell代码无法编译

转载 作者:行者123 更新时间:2023-12-02 10:49:23 24 4
gpt4 key购买 nike

我正在尝试学习Haskell,所以我想我会立即潜入并尝试一个monad。请参阅下面的Calc实现。这类似于State monad,除了state始终是用于缓存结果的Map。每个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仅适用于可打字。您的第三个问题是,您不能将其设置为monad,因为monad必须能够包含任何内容。看看restricted monads

关于haskell - Haskell代码无法编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23032366/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com