Haskell:如何打印纯函数结果的多个指标

时间:2015-11-07 17:41:51

标签: haskell io

我想打印出“纯”函数调用产生的值列表的平均值和长度。我已经对此进行了一些研究,并且正要把头伸进墙里。以下代码有效:

[... a bunch of other stuff like "doParallelTrades" ...]

simulate :: Int -> Int -> [Double]
simulate numbuyers groupsize =
    let buyers = initTraders numbuyers minimum_price maximum_price
        sellers = initTraders numbuyers minimum_price maximum_price
    in doParallelTrades sellers buyers groupsize


{--
MAIN
--}

getNum :: IO Int
getNum = readLn

main :: IO ()
main = do
  let prices n = simulate n 0
  putStr "How many buyers?"
  n <- getNum
  start <- getCurrentTime
  print "average price = "
  print $ average $ prices n
  end <- getCurrentTime
  print "number of trades:"
  print $ length $ prices n
  print "Wall Time:"
  print (diffUTCTime end start)

然而,这会两次评估“价格n”,这显然是我不想为大n做的。我只想评估一次,然后计算并打印平均值,然后打印长度。我尝试将主要功能更改为:

main = do
  let prices n = simulate n 0
  putStr "How many buyers?"
  n <- getNum
  start <- getCurrentTime
  p <- prices n  -- ***********New Code*********
  print "average price = "
  print $ average $ p   -- ***********New Code**********
  end <- getCurrentTime
  print "number of trades:"
  print $ length $ p  -- **********New Code***********
  print "Wall Time:"
  print (diffUTCTime end start)

即,将“price n”绑定到“p”然后用p进行处理。但是翻译给了我错误

zitraders-threaded.hs:162:8:
    Couldn't match expected type ‘IO [Integer]’
                with actual type ‘[Double]’
    In a stmt of a 'do' block: p <- prices n

我研究了各种在线资源,但它们太简单(只在IO monad中工作)或太复杂。那么我该怎么做:

  1. 从用户那里获得一些意见。
  2. 对该输入运行一些“纯”计算(只需一次)并存储结果。
  3. 告诉用户该结果的多个属性。

1 个答案:

答案 0 :(得分:4)

您不能将p与价格n绑定在&#39;&lt; - &#39;运算符,改为使用let:

这应该可以解决问题:

main = do
  ...
  start <- getCurrentTime
  let p = prices n  -- ***********New Code*********
  print "average price = "
  ...