문제

I have written the following function to xor two strings but feel it should be possible to write simpler:

import Data.Bits (xor)
import Data.Char (ord, chr)

-- xors strings of equal length
stringXor :: String -> String -> String
stringXor s t = map chr $ zipWith xor (f s) (f t) where
    f = map ord

It seems like you should be able not to have at least the first map but I couldn't get zipping with the composition chr . xor to work.

Does there exist some useful identitites/formulas involving zipWith and map ?

I am new to Haskell so if there is a simplification without too much pointfree magic, it would be nice to see :)

도움이 되었습니까?

해결책

Well, you could simplify your version using on and fmap:

import Data.Function (on)

stringXor :: String -> String -> String
stringXor = zipWith (fmap chr . xor) `on` map ord

also fmap chr . could be (chr.) . but I find the first one more convenient to type.

EDIT

You can even simplify it to:

stringXor = zipWith (fmap chr . xor `on` ord)

and now we've eliminated the two maps.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top