[英]Haskell: Why is there no type mismatch (and why does this compile)?
我太困了,所以我寫了下面的代碼(修改只是為了顯示混亂):
fac s = take 10 [s, s `mod` 1 ..]
maxFactor x = if (s == [])
then x
else head <-- this should be 'head x' instead of just 'head'
where s = fac x
然而,這加載到 ghci(和編譯)就好了。 當我執行maxFactor 1
時,它會抱怨(當然):
<interactive>:0:1:
No instance for (Integral ([a0] -> a0))
arising from a use of `maxFactor'
Possible fix:
add an instance declaration for (Integral ([a0] -> a0))
In the expression: maxFactor 1
In an equation for `it': it = maxFactor 1
<interactive>:0:11:
No instance for (Num ([a0] -> a0))
arising from the literal `1'
Possible fix: add an instance declaration for (Num ([a0] -> a0))
In the first argument of `maxFactor', namely `1'
In the expression: maxFactor 1
In an equation for `it': it = maxFactor 1
但是,我不明白這種行為:
fac
的類型是:
fac :: Integral a => a -> [a]
而maxFactor
的類型是:
maxFactor :: Integral ([a] -> a) => ([a] -> a) -> [a] -> a
這不是意味着以下內容:
fac
的第一個輸入必須是Integral
類型(例如fac 10
);maxFactor
的定義中,有fac x
, x 也必須是類型類Integral
,因此, maxFactor
的類型將以maxFactor:: (Integral a) => a ->
... 然后是其他東西開頭? 但是,如果是這種情況,那么為什么這段代碼可以編譯,因為maxFactor
的返回可以是x
或head
,當遵循這條推理線時,它們沒有相同的類型?我在這里錯過了什么?
感謝您提前輸入!
正如您正確注意到的那樣,在 maxFactor 中使用maxFactor
fac
會在x
的類型上添加Integral a
約束。 所以x
需要是Integral a => a
類型。
此外,編譯器發現maxFactor
要么返回類型為[a]->a
head
,要么返回x
。 因此x
必須具有更具體的類型Integral ([a]->a) => ([a]->a)
,因此maxFactor
具有類型
maxFactor :: Integral ([a] -> a) => ([a] -> a) -> ([a] -> a)
這正是你得到的。 到目前為止,這個定義沒有任何“錯誤”。 如果您設法編寫了Integral
類型([a]->a)
的實例,則可以毫無問題地調用maxFactor
。 (顯然maxFactor
不會按預期工作。)
在maxFactor
中,編譯器推斷 function 參數x
必須具有與head
相同的類型(在您的if
子句中)。 由於您還在x
上調用fac
(它又調用mod
),它推斷x
也是某種Integral
class 類型。 因此,編譯器推斷類型
maxFactor :: Integral ([a] -> a) => ([a] -> a) -> [a] -> a
這需要一些類似head
和類似整數的參數......這不太可能是真實的。
我認為您可以將該代碼加載到 GHCi 中這一事實更像是解釋器的一個怪癖。
如果你只是編譯上面的代碼,它會失敗。
編輯:我想問題在於類型檢查器可以理解您的代碼,但是可能沒有任何明智的方法來使用它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.