4

我想编写一个用于构建随机数列表的函数,这是我编写的代码

buildlist :: Int -> Int -> [Int]
buildlist n m = do
    seed <- getStdGen
    let l = randomRs (0, m) seed
    let list = take n l
    return list

然后是错误

    Couldn't match expected type `[t0]' with actual type `IO StdGen'
In a stmt of a 'do' block: seed <- getStdGen
In the expression:
  do { seed <- getStdGen;
       let l = randomRs ... seed;
       let list = take n l;
       return list }
In an equation for `buildlist':
    buildlist n m
      = do { seed <- getStdGen;
             let l = ...;
             let list = ...;
             .... }

ps.haskell 与 c、java、ruby 如此不同,以至于我觉得我已经神经质地学习了编码

4

1 回答 1

6

因为您使用的是 IO ( getStdGen),所以整个函数必须在IOmonad 中。将返回类型更改为

buildList :: Int -> Int -> IO [Int]

一定要读一本好书:-)

于 2013-04-16T09:50:03.327 回答