Hi i have the following code
import Data.Maybe
import Test.QuickCheck
import System.Random
rndExpr :: Gen Expr -> IO Expr
rndExpr gen = do
rnd <- newStdGen
return (generate 5 rnd gen)
But i get "not in scope "generate", why is this so?
Regards
Darren
Edit i am importing Test.QuickCheck but it still complaints about the "generate" is not in scope.
Edit 2
How would you write this function so that it would work with quickcheck version 2? I simple tried to put "unGen" where generate was with no succsess, i also installed quickcheck v 2 (cabal install QuickCheck-2.1.0.3)
I need a function with following properties stdGen->Gen Expr->Expr'
and unGen seem to give me that functionality, but as I said, my compiler cant find that function. Are there any other functions that I could use for this problem?
It seems like you are using generators from Test.QuickCheck, and generate is a function from version 1 of quickCheck. In version 2 of quickCheck things are a bit different so there is no such function. However, you atleast need to import Test.QuickCheck, and similar functionality can be gotten from unGen like this:
rundExpr gen = fmap (flip (unGen gen) 5) newStdGen
Please note that unGen is in Test.QuickCheck.Gen so you have to import that too.
generate isn't a function in System.Random. Perhaps you are looking for next?
EDIT:
Let me be clear: I don't know why you are using QuickCheck/Arbitrary for a task that Random/MonadRandom would seem to be more fitting. I'll assume you considered your options and move on.
Must you select your generator? Can't you use sample' :: Gen a -> IO a?
getVal :: IO a
getVal = sample' arbitrary
This should work for QC2.
OTOH, if you really want to use your own StdGen (or want to avoid IO) then try:
import System.Random
import Test.QuickCheck
import Test.QuickCheck.Gen
func :: StdGen -> Int
func g = unGen arbitrary g 0
This will use the StdGen named g and a count (0 here,) to generate your value. Because unGen doesn't step the generator, and the counter stepping doesn't give good randomness properties (it seems, you can try and see for yourself) you might end up wanting to wrap this with something that generates StdGens (yuck).
If you don't know what version package you are using then run:
$ ghc-pkg list | grep QuickCheck
(QuickCheck-2.1.1.1)
QuickCheck-1.2.0.1
In my setup (seen above) I have both 1 and 2, but 2 is hidden (the () means hidden) so when I use GHCi and import Test.QuickCheck it's version 1 that I get.
Related
Similar question (Is there a way to see the list of functions in a module, in GHCI?), though not the result that I seek.
Is there a way to get a list of what is exported by a module?
Of course in GHCi you can import it then type Some.Module., hit tab for auto-completion and it will show what I seek. But I want to capture that stuff. Roughly speaking, String -> [String].
Purpose? Suppose that I have a source file with a naked import Some.Module. Question: What belongs to Some.Module in that file? A simple way would be to output the list of what the module exports, feed that to grep and return the contenders, without the need to load that source file in GHCi (might be complicated or not possible). And everything becomes a lot clearer.
If there's a smarter approach to that, I'm listening. I heard of solutions involving GOA and lambdabot. No idea if applicable or how to make use of this.
As #HTNW mentioned in a comment, if you can run ghc on your actual file, you can use -ddump-minimal-imports. Otherwise, if you want to actually get the list of exports from another module, assuming that you're using GHC, the easiest way to do this is probably to look at the .hi interface files. ghc has some built-in support for printing human-readable representations of interface files once you know the path to one, but as the wiki page notes "This textual format is not particularly designed for machine parsing". You can also access the information you might want via the GHC API. A small example of doing something like that follows.
We start with a bunch of random imports for doing IO & from the GHC api:
import Control.Monad.IO.Class
import System.IO
import System.Environment
import GHC
import GHC.Paths (libdir)
import DynFlags
import Outputable
import Name
import Pretty (Mode(..))
With that bureaucracy out of the way, main starts by firing up the GHC Monad:
main :: IO ()
main = defaultErrorHandler defaultFatalMessager defaultFlushOut $ do
runGhc (Just libdir) $ do
We're not actually generating any code so we can set hscTarget = HscNothing during the DynFlags setup boilerplate:
dflags <- getSessionDynFlags
let dflags' = dflags { hscTarget = HscNothing }
setSessionDynFlags dflags'
With that out of the way we can find the module we want from the package database (using the first command-line argument as the name):
mn <- head <$> (liftIO $ getArgs)
m <- lookupModule (mkModuleName mn) Nothing
We can use getModuleInfo to get a module info structure:
mmi <- getModuleInfo m
case mmi of
Nothing -> liftIO $ putStrLn "Could not find module interface"
If we did find the interface, everything we need for this is in the modInfoExports. If we needed more, we could also get the actual ModIface:
Just mi -> mapM_ (printExport dflags') (modInfoExports mi)
Actually printing out an exported is a bit tedious, as it requires working with Names; a simple example printExport might just use the pretty-printing functions, but these are more intended for printing human-readable output than machine-readable:
printExport :: DynFlags -> Name -> Ghc ()
printExport dflags n =
liftIO $ printSDocLn PageMode dflags stdout (defaultUserStyle dflags)
$ pprNameUnqualified n
A particularly simple way for interactive use is :browse. Load up a ghci that has access to the appropriate package, then
> :browse Some.Module
class Some.Module.Foo a where
Some.Module.foo :: a -> a
{-# MINIMAL foo #-}
Some.Module.bar :: Int
All the qualification can get a bit much, especially if there are many functions that operate on types defined in the same module. To reduce the clutter, you can bring Some.Module into scope first:
> :m + Some.Module
> :browse Some.Module
class Foo a where
foo :: a -> a
{-# MINIMAL foo #-}
bar :: Int
In Haskell, I'd like to generate a random list of Ints and use it throughout my program. My current solution causes the array to be created randomly each time I access/use it.
How can I overcome this problem?
Here is a simple example (#luqui mentioned) you should be able to generalize to your need:
module Main where
import Control.Monad (replicateM)
import System.Random (randomRIO)
main :: IO ()
main = do
randomList <- randomInts 10 (1,6)
print randomList
let s = myFunUsingRandomList randomList
print s
myFunUsingRandomList :: [Int] -> Int
myFunUsingRandomList list = sum list
randomInts :: Int -> (Int,Int) -> IO [Int]
randomInts len bounds = replicateM len $ randomRIO bounds
remarks
randomInts is an IO-action that will produce you your random list of integers, you see it's use in the very first line of mains do-block. Once it is used there the list will stay the same.
myFunUsingRandomList is a very simple example (just summing it) of using such a list in a pure fashion - indeed it just expects a list of integers and I just happen to call it with the random list from main
Follow this example. Then, pass rs from main to whatever function needs it.
You can't have a global variable for this without using something like unsafePerformIO, which, as the name indicates, should not be used. The reason is that picking random numbers is an inherently non-deterministic operation, dependent on the outside IO state.
I want to provide a function that replaces each occurrence of # in a string with a different random number. In a non-pure language, it's trivial. However, how should it be designed in a pure language? I don't want to use unsafePerformIO, as it rather looks like a hack and not a proper design.
Should this function require a random generator as one of its parameters? And if so, would that generator have to be passed through the whole stack of invocations? Are there other possible approaches? Should I use the State monad, here? I would appreciate a toy example demonstrating a viable approach...
You would, in fact, use a variant of the state monad to pass the random generator around behind the scenes. The Rand type in Control.Monad.Random helps with this. The API is a bit confusing, but more because it's polymorphic over the type of random generator you use than because it has to be functional. This extra bit of scaffolding is useful, however, because you can easily reuse your existing code with different random generators which lets you test different algorithms as well as explicitly controlling whether the generator is deterministic (good for testing) or seeded with outside data (in IO).
Here's a simple example of Rand in action. The RandomGen g => in the type signature tells us that we can use any type of random generator for it. We have to explicitly annotate n as an Int because otherwise GHC only knows that it has to be some numeric type that can be generated and turned into a string, which can be one of multiple possible options (like Double).
randomReplace :: RandomGen g => String -> Rand g String
randomReplace = foldM go ""
where go str '#' = do
n :: Int <- getRandomR (0, 10)
return (str ++ show n)
go str chr = return $ str ++ [chr]
To run this, we need to get a random generator from somewhere and pass it into evalRand. The easiest way to do this is to get the global system generator which we can do in IO:
main :: IO ()
main = do gen <- getStdGen
print $ evalRand (randomReplace "ab#c#") gen
This is such a common pattern that the library provides an evalRandIO function which does it for you:
main :: IO ()
main = do res <- evalRandIO $ randomReplace "ab#c#"
print res
In the end, the code is a bit more explicit about having a random generator and passing it around, but it's still reasonably easy to follow. For more involved code, you could also use RandT, which allows you to extend other monads (like IO) with the ability to generate random values, letting you relegate all the plumbing and setup to one part of your code.
It's just a monadic mapping
import Control.Applicative
import Control.Monad.Random
import Data.Char
randomReplace :: RandomGen g => String -> Rand g String
randomReplace = mapM f where
f '#' = intToDigit <$> getRandomR (0, 10)
f c = return c
main = evalRandIO (randomReplace "#abc#def#") >>= print
I'm trying to use the UnionFind package because I need this structure for my exercise (clustering nodes, numbered 1 .. 500) (notwithstanding this blog post suggesting that it does not help) and to learn about ST.
My first problem is that the package does not seem to have a function for bulk loading initial data. I therefore created the following (based on the foldST example in http://www.haskell.org/haskellwiki/Monad/ST) to initialise the data structure, but I can't find a convincing way to call initialClustering and there is no easy way to see whether data structure was created.
import Control.Monad
import Control.Monad.ST
import qualified Data.UnionFind.ST as UF
type Start = Int
--Union-find: clusters of Nodes
type Cluster = UF.Point [Start]
main = do
let
-- next line is clearly wrong but can't find another way to run function
iCluster = initialClustering [1..500]
print $ UF.repr [5] -- i
print $ UF.repr (UF.Pt [5]) -- ii
return ()
initialClustering :: [t] -> ()
initialClustering xs = runST $ do
forM_ xs $ \x -> do
UF.fresh [x]
But I am doing something wrong as compilation fails with i)
Couldn't match expected type `UF.Point s0 a0'
with actual type `[t1]'
In the first argument of `UF.repr', namely `[5]'
and ii)
Not in scope: data constructor `UF.Point'
This reflects a more fundamental lack of understanding about ST and the newtype used to create the UnionFind.ST library.
I'm trying to spew out randomly generated dice for every roll that the user plays. The user has 3 rolls per turn and he gets to play 5 turns (I haven't implemented this part yet and I would appreciate suggestions).
I'm also wondering how I can display the colors randomly. I have the list of tuples in place, but I reckon I need some function that uses random and that list to match those colors. I'm struggling as to how.
module Main where
import System.IO
import System.Random
import Data.List
diceColor = [("Black",1),("Green",2),("Purple",3),("Red",4),("White",5),("Yellow",6)]
{-
randomList :: (RandomGen g) -> Int -> g -> [Integer]
random 0 _ = []
randomList n generator = r : randomList (n-1) newGenerator
where (r, newGenerator) = randomR (1, 6) generator
-}
rand :: Int -> [Int] -> IO ()
rand n rlst = do
num <- randomRIO (1::Int, 6)
if n == 0
then doSomething rlst
else rand (n-1) (num:rlst)
doSomething x = putStrLn (show (sort x))
main :: IO ()
main = do
--hSetBuffering stdin LineBuffering
putStrLn "roll, keep, score?"
cmd <- getLine
doYahtzee cmd
--rand (read cmd) []
doYahtzee :: String -> IO ()
doYahtzee cmd = do
if cmd == "roll"
then rand 5 []
else do print "You won"
There's really a lot of errors sprinkled throughout this code, which suggests to me that you tried to build the whole thing at once. This is a recipe for disaster; you should be building very small things and testing them often in ghci.
Lecture aside, you might find the following facts interesting (in order of the associated errors in your code):
List is deprecated; you should use Data.List instead.
No let is needed for top-level definitions.
Variable names must begin with a lower case letter.
Class prerequisites are separated from a type by =>.
The top-level module block should mainly have definitions; you should associate every where clause (especially the one near randomList) with a definition by either indenting it enough not to be a new line in the module block or keeping it on the same line as the definition you want it to be associated with.
do introduces a block; those things in the block should be indented equally and more than their context.
doYahtzee is declared and used as if it has three arguments, but seems to be defined as if it only has one.
The read function is used to parse a String. Unless you know what it does, using read to parse a String from another String is probably not what you want to do -- especially on user input.
putStrLn only takes one argument, not four, and that argument has to be a String. However, making a guess at what you wanted here, you might like the (!!) and print functions.
dieRoll doesn't seem to be defined anywhere.
It's possible that there are other errors, as well. Stylistically, I recommend that you check out replicateM, randomRs, and forever. You can use hoogle to search for their names and read more about them; in the future, you can also use it to search for functions you wish existed by their type.