[英]Differences between compiled code and ghci in Haskell
我有以下代碼:
-- 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 中輸入 my randomFoobar
function 時,它工作正常。
我是 Haskell 的新手,對此完全不知所措 - 有人知道這里發生了什么嗎? 為什么 ghci 與此處的編譯器不同?
GHCi 默認啟用 ExtendedDefaultRules 擴展,這會導致為某些不明確的類型選擇默認類型,而不是僅僅拋出錯誤。 為了讓你的代碼在任何地方都能工作,最好的解決辦法是添加一個類型注釋,使類型明確。 這種情況下的歧義在於數字文字是多態的。 5.5
可以是Float
、 Double
、 Rational
等。由於最后你只得到一個Bool
,類型推斷無法確定你想要哪個,因為任何一個都是有效的。 使用(5.5:: Double)
而不是僅僅5.5
就可以了,假設Double
是你想要的類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.