Haskell xor 不适用于映射
Haskell xor not work for mapping
我在 Data.Bits
模块中使用 xor
函数时遇到问题
就像下面的代码
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
当我尝试使用 [1..10]
和 [2..11]
参数应用 andFunc
时(参数只是任意数组)
有效。 (这里就不写了,不过orFunc (.|.)
也行)
但由于某些原因,xorFunc
没有....并说
<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]
你知道为什么吗?
运行环境:
没有标志的 GHC 8.2.1
Windows10 个 64 位
如果您想在中缀表示法中使用函数,则必须使用反引号语法。
xorFunc :: [Int] -> [Int] -> [Int]
xorFunc xs ys = zipWith (\x y -> x `xor` y) xs ys
但这可以通过不将其写为 lambda 表达式来更简单地解决
xorFunc :: [Int] -> [Int] -> [Int]
xorFunc xs ys = zipWith xor xs ys
并应用 eta reduce(两次),即省略出现在最后位置且可由类型检查器完全导出的参数。
xorFunc :: [Int] -> [Int] -> [Int]
xorFunc = zipWith xor
中缀函数用标点拼写,可以用括号做前缀;例如x + y
也可以拼写为 (+) x y
。换个方向,前缀函数用字母拼写,可以用反引号做中缀;例如zip xs ys
也可以拼写为 xs `zip` ys
.
将其应用于您的情况,这意味着您应该写 xor x y
或 x `xor` y
之一,而不是 x xor y
.
xor
是常规函数名称,不是运算符。您需要将其括在反引号中以用作中缀运算符。
xorFunc xs ys = zipWith (\x y -> x `xor` y) xs ys
也就是说,您的 lambda 表达式不是必需的;只需使用 xor
作为 zip
:
的参数
xorFunc xs ys = zipWith xor xs ys
或干脆
xorFunc = zipWith xor
(同样,andFunc = zipWith (.&.)
;将运算符括在括号中以将其用作函数值。)
我在 Data.Bits
模块中使用 xor
函数时遇到问题
就像下面的代码
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
当我尝试使用 [1..10]
和 [2..11]
参数应用 andFunc
时(参数只是任意数组)
有效。 (这里就不写了,不过orFunc (.|.)
也行)
但由于某些原因,xorFunc
没有....并说
<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]
你知道为什么吗?
运行环境: 没有标志的 GHC 8.2.1 Windows10 个 64 位
如果您想在中缀表示法中使用函数,则必须使用反引号语法。
xorFunc :: [Int] -> [Int] -> [Int]
xorFunc xs ys = zipWith (\x y -> x `xor` y) xs ys
但这可以通过不将其写为 lambda 表达式来更简单地解决
xorFunc :: [Int] -> [Int] -> [Int]
xorFunc xs ys = zipWith xor xs ys
并应用 eta reduce(两次),即省略出现在最后位置且可由类型检查器完全导出的参数。
xorFunc :: [Int] -> [Int] -> [Int]
xorFunc = zipWith xor
中缀函数用标点拼写,可以用括号做前缀;例如x + y
也可以拼写为 (+) x y
。换个方向,前缀函数用字母拼写,可以用反引号做中缀;例如zip xs ys
也可以拼写为 xs `zip` ys
.
将其应用于您的情况,这意味着您应该写 xor x y
或 x `xor` y
之一,而不是 x xor y
.
xor
是常规函数名称,不是运算符。您需要将其括在反引号中以用作中缀运算符。
xorFunc xs ys = zipWith (\x y -> x `xor` y) xs ys
也就是说,您的 lambda 表达式不是必需的;只需使用 xor
作为 zip
:
xorFunc xs ys = zipWith xor xs ys
或干脆
xorFunc = zipWith xor
(同样,andFunc = zipWith (.&.)
;将运算符括在括号中以将其用作函数值。)