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]

No comments: