Reputation: 58
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
Upvotes: 2
Views: 787
Reputation: 530823
xor
is a regular function name, not an operator. You need to enclose it in backquotes to use as an infix operator.
xorFunc xs ys = zipWith (\x y -> x `xor` y) xs ys
That said, your lambda expressions aren't necessary; just use xor
as argument to zip
:
xorFunc xs ys = zipWith xor xs ys
or simply
xorFunc = zipWith xor
(Likewise, andFunc = zipWith (.&.)
; enclose the operator in parentheses to use it as a function value.)
Upvotes: 3
Reputation: 152682
Infix functions are spelled with punctuation and can be made prefix with parentheses; e.g. x + y
can also be spelled (+) x y
. Going the other direction, prefix functions are spelled with letters and can be made infix with backticks; e.g. zip xs ys
can also be spelled xs `zip` ys
.
Applying that to your case, this means you should write one of xor x y
or x `xor` y
instead of x xor y
.
Upvotes: 3
Reputation: 15967
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
Upvotes: 6