[英]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.