[英]How to correctly qualify types for working with the (transformed) ST and random monads
[英]How to correctly qualify types for working with the random monads
我想创建一个数据结构,该结构包含基于以下各项的定义函数:折叠,布尔运算,数字运算(算术和比较)以及基本字符串运算。 我将尝试发展这些功能类别。 在这里,我收到MonadRandom错误。
这是我的代码:
-- The following language extensions need to be enabled:
-- DeriveDataTypeable, FlexibleInstances, MultiParamTypeClasses
{-# LANGUAGE FlexibleContexts, DeriveDataTypeable, FlexibleInstances, MultiParamTypeClasses, StandaloneDeriving, ExistentialQuantification , GADTs #-}
{-# LANGUAGE RankNTypes #-}
import GenProg
import GenProg.GenExpr
import GenProg.GenExpr.Data
import Data.Generics
import Control.Monad
import Control.Monad.Random
import Data.Fixed
import Data.Typeable
import Data.Data
class IsGenExp t where
mutate :: (MonadRandom m) => t -> m t
crossOver :: (MonadRandom m) => t -> t -> m t
randomGen :: (MonadRandom m) => m t
data GenExp = forall t . IsGenExp t => GenExp t
data IntExp = IntExp Int
data FloatExp = FloatExp Float
data ListExp = ListExp [GenExp]
data ArithExp = Add GenExp GenExp | Sub GenExp GenExp | Mul GenExp GenExp
data CompExp = Eq GenExp GenExp | Lt GenExp GenExp | Gt GenExp GenExp
instance IsGenExp IntExp where
-- randomGen = (getRandomR (IntExp 1,IntExp 3))
randomGen = do
r <- getRandomR (0, 100)
return r
我得到的错误是:
GADT.hs:33:10:
Could not deduce (Random IntExp) arising from a use of `getRandomR'
from the context (MonadRandom m)
bound by the type signature for
randomGen :: MonadRandom m => m IntExp
at GADT.hs:32:4-12
In a stmt of a 'do' block: r <- getRandomR (0, 100)
In the expression:
do { r <- getRandomR (0, 100);
return r }
In an equation for `randomGen':
randomGen
= do { r <- getRandomR (0, 100);
return r }
GADT.hs:33:22:
Could not deduce (Num IntExp) arising from the literal `0'
from the context (MonadRandom m)
bound by the type signature for
randomGen :: MonadRandom m => m IntExp
at GADT.hs:32:4-12
In the expression: 0
In the first argument of `getRandomR', namely `(0, 100)'
In a stmt of a 'do' block: r <- getRandomR (0, 100)
Failed, modules loaded: none.
我该如何解决?
尝试:
instance IsGenExp IntExp where
randomGen = do
r <- getRandomR (0, 100)
return $ IntExp r
注意:
r
是一个数字 IntExp r
是一个IntExp
return $ IntExp r
是m IntExp
单子类型m
m IntExp
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.