2017-10-06 77 views
1

工作,我必須使用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位

+0

感謝你們回答我的愚蠢問題:$ –

回答

5

如果你想使用中綴表示法你必須使用反引號的語法功能。

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 
3

綴功能拼寫與標點,並且可以由前綴括號;例如x + y也可以拼寫(+) x y。從另一個方向來看,前綴函數拼寫爲字母,可以用反引號加上;例如zip xs ys也可以拼寫爲xs `zip` ys

將其應用於您的案例,這意味着您應該寫xor x yx `xor` y之一,而不是x xor y

3

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 (.&.);用括號括運營商使用它作爲一個函數值。)