vendredi 25 mars 2016

Repeat character a random number of times in Haskell

I'm trying to create a function for a silly IRC bot that will return a phrase where some of the letters are repeated a random number of times. The problem I'm having is that I can't find a way to use random numbers that ghc likes. It seems that even using this answer isn't being particularly helpful for getting my code to compile.

import System.Random


-- Write bad
baaad x y = "B" ++ (repeatA x) ++ "D " ++ (exclaim y)

-- StartHere    
randomBad :: String
randomBad = do
  x <- randomRIO(5,10) :: IO Int
  y <- randomRIO(0,6) :: IO Int
  return $ baaad x y


repeatA :: Int -> String
repeatA x = rptChr "A" x

exclaim :: Int -> String
exclaim x = rptChr "!" x

rptChr :: String -> Int -> String
rptChr x y = take y (cycle x)

Even with the trick of using a do block and passing the IO Ints to the function that way, I'm still getting compile errors that it found an IO Int when expecting Int.




Aucun commentaire:

Enregistrer un commentaire