【发布时间】:2015-11-24 08:50:22
【问题描述】:
我必须弄清楚如何编写一个 Haskell 程序来执行以下操作:
- 向用户询问容器的长度、宽度和高度
- 询问最大允许质量
- 计算并显示最大允许密度
在玩弄了一些代码并花了几个小时学习 LearnYouAHaskell 之后,我得出了这个结论:
main = do
getLength
isNumber :: String -> Bool
isNumber line = if (null $ filter (`notElem` ['0'..'9'] ++ ['.']) line)
then True
else False
getInput :: IO Double
getInput = do
line <- getLine
if isNumber line
then return (read line :: Double)
else do
putStrLn "This value is not a number, please try again!"
getInput
getLength :: IO ()
getLength = do
putStrLn "-----------------------"
putStrLn "DensityCalc v1.0"
putStrLn "-----------------------"
putStrLn ""
putStrLn "Please enter the container length to begin."
putStrLn "Entering 0 will end the program."
length <- getInput
if length == 0
then putStrLn "Goodbye!"
else do
putStrLn $ "Length: " ++ show length
putStrLn "Now enter container width (0 to quit): "
getWidth length
getWidth :: Double -> IO ()
getWidth length = do
width <- getInput
if width == 0
then putStrLn "Goodbye!"
else do
putStrLn $ "Width: " ++ show width
putStrLn "Now enter container height (0 to quit): "
getHeight length width
getHeight :: Double -> Double -> IO ()
getHeight length width = do
height <- getInput
if height == 0
then putStrLn "Goodbye!"
else do
putStrLn $ "Height: " ++ show height
putStrLn "Finally, enter maximum allowed mass (0 to quit): "
getMass length width height
getMass :: Double -> Double -> Double -> IO ()
getMass length width height = do
mass <- getInput
if mass == 0
then putStrLn "Goodbye!"
else do
putStrLn $ "Maximum mass: " ++ show mass
putStrLn "Calculating density..."
getDensity length width height mass
getDensity :: Double -> Double -> Double -> Double -> IO ()
getDensity length width height mass = do
let density = mass * 100.0 / length * width * height
let roundedDensity = round (density :: Double)
let shownDensity = (fromIntegral roundedDensity) / 100.0
putStrLn $ "Maximum allowed freight density: " ++ show shownDensity
putStrLn "Thank you for using my tool! Goodbye!"
我的第一个问题是:编译时,它在第 65 行给了我一个“输入 =" 解析错误 -
density = mass * 100.0 / length * width * height
其次,如果我完全取出密度函数,它会编译 - 但主函数什么都不做(返回我输入的内容,没有别的) - screenshot
我应该在哪里查找错误?
[编辑]
第一个问题解决了,改了代码。第二个仍然存在。
[编辑2]
看来,为了开始,我需要在主窗口中手动输入“getLength”。我可以让它立即调用该函数吗?
【问题讨论】:
-
在代码中。除了玩笑,我建议您将代码粘贴到此处,而不是链接到其中的一部分。
-
请不要编辑你原来代码的错误,这会让问题和答案之间的关联非常混乱。