我正在阅读 LYAH,在第 9 章中,我发现了一个奇怪的问题。作者提供了一个实现“randoms”功能的例子:
randoms' :: (RandomGen g, Random a) => g -> [a]
randoms' gen = let (value, newGen) = random gen in value:randoms' newGen
好吧,这编译得很好。但是,如果我将第二行更改为:
randoms' gen = (fst (random gen)) : (randoms' (snd (random gen)))
此文件在加载时报告错误:
IOlesson.hs:4:52:
Ambiguous type variable `a' in the constraint:
`Random a' arising from a use of `random' at IOlesson.hs:4:52-61
Probable fix: add a type signature that fixes these type variable(s)
Failed, modules loaded: none.
如果我将此行更改为:
randoms' gen = (fst (random gen)) : (randoms' gen)
然后这会很好,并且正如预期的那样,这将返回所有相同元素的列表。
我不解:米兰的版本和我的版本有什么不同?
感谢您的任何想法!