Bob Green
Bob Green

Reputation: 111

How to use type variable in Haskell instance-where

I try to use type variable in the where-body of the type instance. But GHC don't use the type variable for the functions in the type instance.

I try to implement type class Bits for [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

GHC says:

Could not deduce (Num a) arising from the literal ‘0’

Expected:

That 0 is expected to be as type a, which is the type variable as defined in instance forall a. Bits a => Bits [a]

Upvotes: 1

Views: 130

Answers (1)

Li-yao Xia
Li-yao Xia

Reputation: 33389

There are different ways to write "zero" in different contexts.

You only have a constraint Bits a, then one way to write "zero" is zeroBits.

0 is the "zero" for types that have a Num a instance.

Upvotes: 7

Related Questions