- 论坛徽章:
- 0
|
只看了头三章
花了好长时间才写的这段代码
贴出来大家批评
- yaht exercise 3.10:
- Write a program that will repeatedly ask the user for numbers until she
- types in zero, at which point it will tell her the sum of all the numbers, the product of
- all the numbers, and, for each number, its factorial. For instance, a session might look
- like:
- 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
复制代码
module Main where
import IO
factorial 0 = 1
factorial n = n * factorial (n - 1)
toNum s = read s + 0
toLine s = s ++ " factorial is " ++ show (factorial (read s))
getList = do
putStrLn "Give me a number (or 0 to stop):"
word <- getLine
if word == "0"
then return []
else do
rest <- getList
return (word : rest)
showFacLines (f:r) = do
if r == []
then do
putStrLn f
else do
putStrLn f
showFacLines r
main = do
list <- getList
if list == []
then do
putStrLn "You enter nothing!"
else do
putStrLn ("The sum is " ++ show (foldl (+) 0 (map toNum list)))
putStrLn ("The product is " ++ show (foldl (*) 1 (map toNum list)))
showFacLines (map toLine list) |
|
|