Showing posts with label Haskell. Show all posts
Showing posts with label Haskell. Show all posts

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.

Wednesday, April 30, 2008

fibo.hs

My first Haskell program! The recursive functions and induction from CSE321 inspired me to write a simple Fibonacci sequence generator:

fibo.hs

import System.Environment

-- The almighty Fibonacci generator!
fibo :: Integer -> Integer
fibo 0 = 1
fibo 1 = 1
fibo n | n > 1 = fibo(n - 2) + fibo(n - 1)


-- Generates a list of the appropriate numbers
fibosequence :: Integer -> [Integer]
fibosequence 0 = [1]
fibosequence n | n > 0 = fibosequence(n - 1) ++ [fibo(n)]


str2int :: String -> Integer
str2int = read


-- For generating a single number per argument
fibolist :: [String] -> String
fibolist [] = ""
fibolist (x:xs) = x ++ ": " ++ show(fibo(str2int(x))) ++ "\n" ++ fibolist(xs)


-- For generating a list per argument
fiboslist :: [String] -> String
fiboslist [] = ""
fiboslist (x:xs) = x ++ ": " ++ show(fibosequence(str2int(x))) ++ "\n" ++ fiboslist(xs)




main = do x <- getArgs
putStr(fiboslist(x))
% ./fibo 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
0: [1]
1: [1,1]
2: [1,1,2]
3: [1,1,2,3]
4: [1,1,2,3,5]
5: [1,1,2,3,5,8]
6: [1,1,2,3,5,8,13]
7: [1,1,2,3,5,8,13,21]
8: [1,1,2,3,5,8,13,21,34]
9: [1,1,2,3,5,8,13,21,34,55]
10: [1,1,2,3,5,8,13,21,34,55,89]
11: [1,1,2,3,5,8,13,21,34,55,89,144]
12: [1,1,2,3,5,8,13,21,34,55,89,144,233]
13: [1,1,2,3,5,8,13,21,34,55,89,144,233,377]
14: [1,1,2,3,5,8,13,21,34,55,89,144,233,377,610]
15: [1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987]