簡體   English   中英

Haskell:為什么沒有類型不匹配(為什么會編譯)?

[英]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

這不是意味着以下內容:

  1. fac的第一個輸入必須是Integral類型(例如fac 10 );
  2. 因為在maxFactor的定義中,有fac x , x 也必須是類型類Integral ,因此, maxFactor的類型將以maxFactor:: (Integral a) => a -> ... 然后是其他東西開頭? 但是,如果是這種情況,那么為什么這段代碼可以編譯,因為maxFactor的返回可以是xhead ,當遵循這條推理線時,它們沒有相同的類型?

我在這里錯過了什么?

感謝您提前輸入!

正如您正確注意到的那樣,在 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM