哈斯克尔XOR不是映射
问题描述:
工作,我必须使用xor
功能的问题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无标志 的Windows 10的64位
答
如果你想使用中缀表示法你必须使用反引号的语法功能。
xorFunc :: [Int] -> [Int] -> [Int]
xorFunc xs ys = zipWith (\x y -> x `xor` y) xs ys
但是这可以通过不写这作为λ表达式
xorFunc :: [Int] -> [Int] -> [Int]
xorFunc xs ys = zipWith xor xs ys
并施加ETA减少(两次),即省略了在最后的位置存在的参数,可以解决的一个简单一点由类型检查器完全派生。
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 (.&.)
;用括号括运营商使用它作为一个函数值。)
感谢你们回答我的愚蠢问题:$ –