0

我需要得到平均值,所以输入停止,直到用户输入一个负数,然后输出是平均值

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

2 回答 2

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)

顺便说一句,这不是最好的解决方案:

于 2013-02-21T19:28:05.687 回答
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)
于 2013-02-21T19:28:22.423 回答