Why can't I run main interactively?

Viewed 77

The program (Main.hs, found on SO) looks like this

import Control.Monad.Random

main :: IO ()
main = do
    gen <- getStdGen
    let values = evalRand diceSums gen
    print . take 10 $ values

-- Generate sums from rolling two dice
diceSums :: RandomGen g => Rand g [Int]
diceSums = do
    xs <- dieRolls
    ys <- dieRolls
    return $ zipWith (+) xs ys

-- Single die roll function.
dieRolls :: RandomGen g => Rand g [Int]
dieRolls = getRandomRs (1, 6)

I then run

stack ghci
Prelude> :l Main.hs
[1 of 1] Compiling Main             ( Main.hs, interpreted )
Ok, one module loaded.
*Main> main
<interactive>:2:1: error:
    * Variable not in scope: main
    * Perhaps you meant `min' (imported from Prelude)
*Main> :t dieRolls
<interactive>:1:1: error: Variable not in scope: dieRolls

If I try and compile I get

ghc Main.hs
[1 of 1] Compiling Main             ( Main.hs, Main.o )

Main.hs:1:1: error:
The IO action `main' is not defined in module `Main'

What am I doing wrong?

2 Answers

Might it be that stack is insisting on you adding the module declaration at the top of the module,

module Main where

(this seems related, though according to it, without the declaration, main should still be available -- though dieRolls indeed shouldn't.)

Not sure why main doesn't work, but the correct way to run main function from GHCi is :main. This way you can pass arguments to your program.

Related