Search code examples
functionhaskellxor

Haskell xor not work for mapping


I have a problem of using xor function in Data.Bits module like a code below

import Data.Bits

andFunc :: [Int] -> [Int] -> [Int]
andFunc xs ys = zipWith (\x y -> x .&. y) xs ys

xorFunc :: [Int] -> [Int] -> [Int]
xorFunc xs ys = zipWith (\x y -> x xor y) xs ys

When I try to apply andFunc with arguments of [1..10] and [2..11] (arguments are just arbitrary array)

it works. (Does not write here, but orFunc (.|.) also works)

but some reasons, xorFunc does not.... and says

<interactive>:74:1: error:
    ? Non type-variable argument
        in the constraint: Enum ((a -> a -> a) -> t -> c)
      (Use FlexibleContexts to permit this)
    ? When checking the inferred type
        it :: forall a t c.
              (Enum ((a -> a -> a) -> t -> c), Enum t,
               Num ((a -> a -> a) -> t -> c), Num t, Bits a) =>
              [c]

Do you know why?

Running Environment: GHC 8.2.1 with no flags Windows 10 64 bit


Solution

  • If you want to use functions in infix notation you have to use backtick syntax.

    xorFunc :: [Int] -> [Int] -> [Int]
    xorFunc xs ys = zipWith (\x y -> x `xor` y) xs ys
    

    but this can be solved a bit simpler by not writing this as a lambda expression

    xorFunc :: [Int] -> [Int] -> [Int]
    xorFunc xs ys = zipWith xor xs ys
    

    and applying eta reduce (twice), i.e. omitting parameters that are occurring in the last position and can be fully derived by the type checker.

    xorFunc :: [Int] -> [Int] -> [Int]
    xorFunc = zipWith xor