Haskell错误 - 无法匹配预期类型

时间:2013-04-16 09:47:30

标签: function haskell types

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

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如此不同,我觉得自己已经学会了编码

1 个答案:

答案 0 :(得分:6)

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

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

读一本好书: - )