Я экспериментировал с некоторыми математическими функциями и придумал следующее:Haskell путаница (биты а) inferenced типа ошибка
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 дает мне эту ошибку:
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))
То же самое происходит, если я использую вместо mulGF2n a b g = let (q, r) = divModGF2n (mulGF2 a b) g in r
. В чем причина того, что я верю кортеж, но не второй элемент кортежа? Это могло бы помочь, если бы я знал, что относится к типу a0
, но он только жалуется на тип, но не говорит мне, к какому из них относится.
FYI все функции, связанные с разрядными определены в 'Data.Bits': https://downloads.haskell.org/~ghc/latest/docs/html/libraries/base/Data-Bits.html – Ana