我必须弄清楚如何编写一个执行以下操作的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!"
我的第一个问题是:在编译时,它会在输入中给出一个&#34;解析错误=&#34;在第65行 -
density = mass * 100.0 / length * width * height
其次,如果我完全取出密度函数,它会编译 - 但主函数什么都不做(返回我输入的内容,而不是其他内容) - screenshot
我应该在哪里寻找错误?
[编辑]
第一个问题解决了,改了代码。第二个仍然存在。
[EDIT2]
似乎,为了开始,我需要手动输入&#34; getLength&#34;在主窗口中。我可以立即调用它吗?
答案 0 :(得分:3)
您需要let
在do
内定义新的绑定。
答案 1 :(得分:0)
想出我在使用程序调用函数时需要手动编写“getLength”,然后一切正常。
问题是 - 如果在“main = do”子句中明确提到了getLength,为什么还要这样做呢?