gpt4 book ai didi

function - Haskell xor 不适用于映射

转载 作者:行者123 更新时间:2023-12-05 08:27:07 25 4
gpt4 key购买 nike

我在 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

但这可以通过不将其写为 lambda 表达式来更简单地解决

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

并应用 eta reduce(两次),即省略出现在最后位置且可由类型检查器完全导出的参数。

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

关于function - Haskell xor 不适用于映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46611489/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com