Thursday, April 7, 2011

My First Haskell Program

Haskell has always been a bit difficult for me to understand, but thanks to this guide, I learned quite a bit. It took me about fifteen minutes, but I have my first Haskell program running!

import System.Random
import Text.Printf

parseAnswer :: String -> IO Bool
parseAnswer "y" = return True
parseAnswer a = return False



testLuck :: (RandomGen g) => g -> Bool -> Int -> IO Int
testLuck seed True x =
do let (addition, newseed) = randomR (-4, 4) seed
mainloop newseed (x + addition)
testLuck seed False x = return x

mainloop :: (RandomGen g) => g -> Int -> IO Int
mainloop seed x =
do printf "Would you like to roll? You currently have: %d\n" x
rolled <- getLine >>= parseAnswer
testLuck seed rolled x

main =
do putStrLn "Welcome to herpaderp."
seed <- newStdGen
mainloop seed 0 >>= printf "You ended up with: %d\n"
It's a pretty silly little thing that just asks you if you want to roll and returns some value. I learned quite a bit about monads with both this and the guide, too.

No comments: