我有如下代码:
-- defined externally in a module that compiles just fine
-- normal :: (RandomGen g, Random r, Floating r, Ord r) => r -> r -> g -> (r, g)
-- poisson :: (RandomGen g, Random r, Floating r, Ord r) => r -> g -> (Integer, g)
-- binomial :: (RandomGen g, Random r, Floating r, Ord r) => r -> g -> (Bool, g)
data Foobar = Foobar { n :: Double, p :: Integer, b :: Bool } deriving (Show)
randomFoobar :: (RandomGen g) => g -> (Foobar, g)
randomFoobar g0 = let (n, g1) = normal 10.0 1.0 g0
(p, g2) = poisson 5.5 g1
(b, g3) = binomial 0.5 g2
in (Foobar n p b, g3)
当我尝试编译这段代码时,出现了一系列错误,其中第一个是:
Foobar.hs:8:33: error:
• Could not deduce (Random r0) arising from a use of ‘poisson’
from the context: RandomGen g
bound by the type signature for:
randomFoobar :: forall g. RandomGen g => g -> (Foobar, g)
at Foobar.hs:6:1-49
The type variable ‘r0’ is ambiguous
These potential instances exist:
instance Random Integer -- Defined in ‘System.Random’
instance Random Bool -- Defined in ‘System.Random’
instance Random Char -- Defined in ‘System.Random’
...plus four others
...plus 29 instances involving out-of-scope types
(use -fprint-potential-instances to see them all)
• In the expression: poisson 5.5 g1
In a pattern binding: (p, g2) = poisson 5.5 g1
In the expression:
let
(n, g1) = normal 10.0 1.0 g0
(p, g2) = poisson 5.5 g1
(b, g3) = binomial 0.5 g2
in (Foobar n p b, g3)
当我在ghci中直接输入
randomFoobar
函数时,它可以正常工作。我对Haskell非常陌生,并被这个问题搞得一脸懵逼 - 有人知道这里发生了什么吗?为什么ghci和编译器不一样?