Created
August 15, 2014 02:49
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ 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