我需要获得平均值,因此输入会停止,直到用户输入负数,然后输出为平均值
{
getFloat :: IO Float
getFloat = do line <- getLine
return (read line:: Float)
average :: IO Float
average = helper summ n
where
helper :: Float->Float->IO Float
helper summ n = do val<-getFloat
if (val<0)
then (return average)
else ( do summ = summ + val
n = n+1
average= summ/n
average)
}
答案 0 :(得分:2)
最好将纯净和不纯的计算分开。即,average
可能只是[a] -> b
而没有IO效果。
main = print =<< average `fmap` go []
where
go :: [Int] -> IO [Int]
go xs = do
x <- (read :: String -> Int) `fmap` getLine
if x < 0 then return (x : xs) else go (x : xs)
average :: [Int] -> Float
average xs = (fromIntegral $ sum xs) / (fromIntegral $ length xs)
顺便说一下,这不是最佳解决方案:
readLn :: Read a => IO a
List
两次答案 1 :(得分:0)
尝试这样的事情:
main = do (s,n) <- getnums
putStrLn $ show $ s / (fromIntegral n)
getnums :: IO (Float, Int)
getnums = go 0.0 0
where go s n = do line <- getLine
let f = read line :: Float
if f < 0 then return (s,n)
else go (s+f) (n+1)