如何将随机数附加到列表中

时间:2014-11-01 14:17:05

标签: haskell

我写了一个函数来生成随机数:

drawFloat :: Float -> Float -> IO Float
drawFloat x y = getStdRandom (randomR (x,y))

现在我有一个列表[1,2,3]

如何将随机数附加到此列表?

我试过[1,2,3] ++ (drawFloat 2 10)它不起作用......

错误消息:

    Couldn't match expected type ‘[a]’ with actual type ‘IO a0’
    Relevant bindings include it :: [a] (bound at <interactive>:72:1)
    In the second argument of ‘(++)’, namely ‘(drawFloat 2 10)’
    In the expression: [1, 2, 3] ++ (drawFloat 2 10)

我也试过[1,2,3] ++ [(drawFloat 2 10)]。仍然没有工作..

2 个答案:

答案 0 :(得分:3)

因此,drawFloat的类型为Float -> Float -> IO Float。我们只能添加[Float]。尝试

 appendRand :: [Float] -> IO [Float]
 appendRand lis = (lis ++) . return <$> drawFloat 2 10

我们正在将函数(list ++) . return :: Float -> [Float]提升为IO Float -> IO [Float],这正是我们想要的。 (此处,return正在[] monad上运行,而不是IO

答案 1 :(得分:1)

因为drawFloat返回monadic类型,所以你必须潜入同一个monad才能追加:

import System.Random

drawFloat :: Float -> Float -> IO Float
drawFloat x y = getStdRandom (randomR (x,y))

appendRandom :: [Float] -> IO [Float]
appendRandom as = do
  val <- drawFloat 2 10
  return $ as ++ [val]

main = appendRandom [1, 2, 3] >>= print