简体   繁体   English

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

[英]How to correctly qualify types for working with the random monads

I want to create a data structure that comprises of defined functions based on: fold, Boolean operations, numeric operations (arithmetic and comparisons), and basic string operations. 我想创建一个数据结构,该结构包含基于以下各项的定义函数:折叠,布尔运算,数字运算(算术和比较)以及基本字符串运算。 I'll be trying to evolve these class of functions. 我将尝试发展这些功能类别。 Here I am getting an error with MonadRandom. 在这里,我收到MonadRandom错误。

Here is my code: 这是我的代码:

-- 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

And the error I get: 我得到的错误是:

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.

How do I fix this? 我该如何解决?

Try: 尝试:

instance IsGenExp IntExp where
   randomGen = do
    r <- getRandomR (0, 100)
    return $ IntExp r

Note: 注意:

  • r is a number r是一个数字
  • IntExp r is an IntExp IntExp r是一个IntExp
  • return $ IntExp r is a m IntExp for the monad type m return $ IntExp rm IntExp单子类型m m IntExp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM