【发布时间】:2019-11-05 11:31:08
【问题描述】:
我正在 Haskell 中试验随机性,我想做一个函数,给定 Int n 返回 1 到 6 之间随机数状态的列表:
-- auxiliar function
rollDie :: State StdGen Int
rollDie = do generator <- get
let (value, newGenerator) = randomR (1,6) generator
put newGenerator
return value
rollNDice :: Int -> State StdGen [Int]
rollNDice n | n == 0 = [] :: State StdGen [Int]
| otherwise = (:) <$> rollDie <*> rollNDice (n-1)
但是当我尝试在 ghci 中运行它时,我得到:
Couldn't match type ‘[a0]’
with ‘StateT StdGen Data.Functor.Identity.Identity [Int]’
Expected type: State StdGen [Int]
Actual type: [a0]
• In the expression: [] :: State StdGen [Int]
In an equation for ‘rollNDice’:
rollNDice n
| n == 0 = [] :: State StdGen [Int]
| otherwise = (:) <$> rollDie <*> rollNDice (n - 1)
我不明白这个错误。有什么想法吗?
【问题讨论】:
-
你应该使用
return [],或者pure []。