Skip to content

Instantly share code, notes, and snippets.

@ashaindlin
Created August 15, 2014 02:49
Show Gist options
  • Save ashaindlin/9164d8b79a724c590f7a to your computer and use it in GitHub Desktop.
Save ashaindlin/9164d8b79a724c590f7a to your computer and use it in GitHub Desktop.
Yet Another Haskell Tutorial Ch. 3 Exercise 10 - sum, product, and list of factorials
module Main
where
import System.IO
main = do
num <- getNums
putStrLn ("The sum is " ++ show (sum num))
putStrLn ("The product is " ++ show (product num))
putFactorials num
factorial 1 = 1
factorial n = n * factorial (n-1)
putFactorials (n:ns) = do
putStrLn ((show n) ++ " factorial is " ++ (show (factorial n)))
if null ns then do
return []
else
putFactorials ns
getNums = do
putStrLn "Give me a number (or 0 to stop):"
numStr <- getLine
let num = read numStr + 0 -- hack; should use types
if num == 0
then return []
else do
rest <- getNums
return (num:rest)
$ ghc --make ch3-10.hs
$ ./ch3-10
Give me a number (or 0 to stop):
5
Give me a number (or 0 to stop):
8
Give me a number (or 0 to stop):
2
Give me a number (or 0 to stop):
0
The sum is 15
The product is 80
5 factorial is 120
8 factorial is 40320
2 factorial is 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment