请问一道Yet Another Haskell Tutorial的习题
alexband
2009-02-06
大家好。由于一定的需要,要在短时间内对Haskell进行一个扫盲。今天晚上在网上搜索了一下,发现Yet Another Haskell Tutorial是一个很好的开始。在看到第三章的时候,有个习题想不出来,特此请教一下;
问题是 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 ReadNum where import IO fibonacci 1 = 1 fibonacci 2 = 1 fibonacci n = fibonacci (n-2) + fibonacci (n-1) readnum = do hSetBuffering stdin LineBuffering putStrLn "Give me a number (or 0 to stop) :" num <- getLine let value = read num if value == 0 then do return [] else do rest <- readnum return ( value : rest ) result = do list <- readnum let fib = map fibonacci list putStrLn ("The sum is " ++ show(foldr (+) 0 list)) putStrLn ("The product is " ++ show(foldr (*) 1 list)) putStrLn (show(head list) ++ " factorial is " ++ show(head fib)) 结果是 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 5 这一行 5 factorial is 5 也是错的 后面不知道怎么办是好。不知道如何遍历一个List还能“递归”地打印出来 |
|
glacjay
2009-02-18
首先,你的 fibonacci 是干嘛的,不是要求 factorial 的嘛。
其次,最后一行只取了 head,当然也只有一个结果啦,可以用 mapM_ 。 |
|
freizl
2011-04-28
Here comes my toy..
module Main where main :: IO () main = do xs <- sgetline mapM_ (\s -> putStrLn s) ([showSum xs , showProduct xs] ++ (map showFactorial xs)) where showSum x = "The sum is: " ++ (show . sum) x showProduct x = "The product is: " ++ (show . product) x showFactorial x = (show x) ++ " factorial is: " ++ (show . factorial) x sgetline :: IO [Int] sgetline = do putStrLn "Give me a number (or 0 to stop) :" x <- getLine if x `elem` ["", "0"] then -- isStringEmpty?? do return [] else do xs <- sgetline return ((read x):xs) factorial n = product [1..n] |
相关讨论
相关资源推荐
- 中小企业组建网络详细配置
- 随便贴两个漏洞,如 Apache JServ协议服务
- tomcat集群--整合Apache服务器,采用mod_JK连接模式
- Apache Jserv protocol
- apache服务器支持jsp,网管必读:Apache服务器之JSP架构篇
- Apache Module加载问题解决方案
- Apache JServ protocol服务 怎么关闭?
- Apache模块索引
- Apache Tomcat JServ漏洞验证测试(CNVD-2020-10487 CVE-2020-1938)
- apache tomcat漏洞扫描Apache JServ protocol service