helloWorld
helloWorld

Reputation: 37

How to create a random boolean generator in Haskell?

I'm new to Haskell and I am trying to write a random boolean generator. I was able to make a function that generates the random boolean and saves it into a list. I want to define a function that extracts the value of the list.

This is what I have done so far

import System.Random
import Control.Monad

makeBool:: Int -> IO [Bool]
makeBool n = replicateM n randomIO

extractBool:: IO [Bool] -> Bool 
extractBool x = x !! 0

However, I am getting this error, Please Help!!

* Couldn't match expected type `[Bool]'
              with actual type `IO [Bool]'
* In the first argument of `(!!)', namely `x'
  In the expression: x !! 0
  In an equation for `extractBool': extractBool x = x !! 0
Failed, modules loaded: none.

Upvotes: 2

Views: 1391

Answers (1)

Kenneth Lo
Kenneth Lo

Reputation: 11

You can just bound the result to a variable and feed to any other functions that require no I/O.

import System.Random
import Control.Monad

makeBool :: Int -> IO [Bool]
makeBool n = replicateM n randomIO

useBoolList :: [Bool] -> String
useBoolList [] = ""
useBoolList (x:xs) = (if x == True then "T" else "F") ++ useBoolList xs

printList = do
    l <- makeBool 10
    putStrLn $ useBoolList l

Upvotes: 1

Related Questions