如何正确限定类型以使用随机 monad

How to correctly qualify types for working with the random monads

我想创建一个数据结构,其中包含基于以下定义的函数:折叠、布尔运算、数字运算(算术和比较)和基本字符串运算。我将尝试改进这些 class 函数。在这里,我遇到了 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 是 monad 类型 m
  • m IntExp