如何在Haskell实例中使用类型变量

Bob*_*een 1 haskell types instance

我尝试在类型实例的where-body中使用type变量.但是GHC不对类型实例中的函数使用类型变量.

我尝试实现类型类Bits[a].

instance forall a. Bits a => Bits [a] where
    xor = zipWith xor
    rotateL list dis = keeped .|. overlap
    where
        overlap = tail moved ++ [head moved] 
        (keeped, moved) = unzip $ map (\n -> let rot = rotate n dis in (rot.&.mask, rot.&.filter)) list
        mask = (complement 0) `shiftL` dis -- this line
        filter = complement mask
Run Code Online (Sandbox Code Playgroud)

GHC说:

Could not deduce (Num a) arising from the literal ‘0’
Run Code Online (Sandbox Code Playgroud)

预期:

0应该是类型a,它是在中定义的类型变量instance forall a. Bits a => Bits [a]

Li-*_*Xia 8

在不同的上下文中有不同的方法来写"零".

你只有一个约束Bits a,那么写一个"零"的方法就是zeroBits.

0是具有Num a实例的类型的"零" .

  • 对于具有类似错误消息的未来访问者:另一种解决方案是保持方法定义相同,但是将所需的约束添加到实例上下文,如`实例(Num a,Bits a)=> Bits [a]其中...... `.在这种情况下,这不是正确的解决方案,但在其他类似的情况下,它经常是. (3认同)