我一些數學函數試驗,並已拿出了以下內容:哈斯克爾混淆(位的)推斷的錯誤類型
import Data.Bits
mulGF2n a b g = divModGF2n (mulGF2 a b) g
where
mulGF2 a b
| a == zeroBits = zeroBits
| otherwise = xor (if testBit a 0 then b else zeroBits) (mulGF2 (shiftR a 1) (shiftL b 1))
divModGF2n a b = go a zeroBits
where
n = log2 b
log2 a = let x = shiftR a 1 in if x == zeroBits then 0 else 1 + log2 x
go a q
| r < 0 = (q, a)
| otherwise = go (xor a (shiftL b r)) (q .|. bit r)
where
r = log2 a - n
他們迦羅華域的計算,但他們做了什麼都沒有重要。注意我省略了類型簽名。
GHCI告訴我下面講的推斷類型:
*Main> :t divModGF2n
divModGF2n :: (Bits t1, Bits t) => t -> t -> (t1, t)
*Main> :t mulGF2n
mulGF2n :: (Bits a, Bits t1, Bits t) => a -> t -> t -> (t1, t)
到目前爲止好。我嘗試修改mulGF2n
函數,以便不返回類型爲(t1, t)
的元組,而是僅返回類型爲t
的第二個元素。
mulGF2n a b g = divModGF2n (mulGF2 a b) g
到:我從修改函數的第一行
mulGF2n a b g = snd $ divModGF2n (mulGF2 a b) g
現在,GHCI給了我這個錯誤:如果我改用mulGF2n a b g = let (q, r) = divModGF2n (mulGF2 a b) g in r
Could not deduce (Bits a0) arising from a use of ‘divModGF2n’
from the context (Bits a, Bits b)
bound by the inferred type of
mulGF2n :: (Bits a, Bits b) => a -> b -> b -> b
at polydiv.hs:(12,1)-(16,100)
The type variable ‘a0’ is ambiguous
Note: there are several potential instances:
instance Bits Bool -- Defined in ‘Data.Bits’
instance Bits Int -- Defined in ‘Data.Bits’
instance Bits Integer -- Defined in ‘Data.Bits’
...plus one other
In the first argument of ‘snd’, namely
‘(divModGF2n (mulGF2 a b) g)’
In the expression: snd (divModGF2n (mulGF2 a b) g)
In an equation for ‘mulGF2n’:
mulGF2n a b g
= snd (divModGF2n (mulGF2 a b) g)
where
mulGF2 a b
| a == zeroBits = zeroBits
| otherwise
= xor
(if testBit a 0 then b else zeroBits)
(mulGF2 (shiftR a 1) (shiftL b 1))
同樣的事情發生。什麼原因可以返回元組而不是元組的第二個元素?如果我知道錯誤中提及的類型a0
,但它只會抱怨類型,但不會告訴我它指的是哪一種。
FYI所有的位相關的功能在'Data.Bits'定義:https://downloads.haskell.org/~ghc/latest/docs/html/libraries/base/Data-Bits.html – Ana 2014-12-13 18:18:47