Haskell解析错误,用于平均程序

时间:2013-02-21 19:09:33

标签: haskell

我需要获得平均值,因此输入会停止,直到用户输入负数,然后输出为平均值

  {
    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)
                                                         }

2 个答案:

答案 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)

顺便说一下,这不是最佳解决方案:

答案 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)