[英]Why does Haskell interpret my Num type as an Enum?
我正在嘗試在Haskell中編譯以下函數,以模仿在數值列表中指定常量的多項式的區分:
diff :: (Num a) => [a] -> [a]
diff [] = error "Polynomial unspecified"
diff coeff = zipWith (*) (tail coeff) [0..]
Haskell拒絕編譯它,給出了以下原因:
Could not deduce (Enum a) from the context (Num a)
arising from the arithmetic sequence `0 .. ' at fp1.hs:7:38-42
Possible fix:
add (Enum a) to the context of the type signature for `diff'
In the third argument of `zipWith', namely `[0 .. ]'
In the expression: zipWith (*) (tail coeff) ([0 .. ])
In the definition of `diff':
diff coeff = zipWith (*) (tail coeff) ([0 .. ])
為什么Haskell將[0..]
列表視為Enum類型,我該如何解決這個問題。 請記住,我想利用這里的懶惰評估,因此無限列表。
[0..]
是enumFrom 0
語法糖,在Enum
類中定義。 因為要生成的列表a
以s [0..]
編譯器需要a
要在類Enum
。
您可以將Enum a
添加到函數的類型簽名中,也可以通過生成[0..] :: [Integer]
並使用fromInteger
(在類Num
定義)從中獲取[a]
來解決該問題。 :
diff :: (Num a) => [a] -> [a]
diff [] = error "Polynomial unspecified"
diff coeff = zipWith (*) (tail coeff) (map fromInteger [0..])
必須有正確的diff
類型
diff :: (Num a, Enum a) => [a] -> [a]
因為[x..]
要求類型實例化Enum
。
[0..]
是enumFrom 0
縮寫, 請參見此處
以下是編譯器在查看此函數時看到的內容的快速摘要:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.