2009-12-19 81 views
0

对于项目欧拉59,我想出了这个返回包含该decyphered字符串元组的列表,并使用的密钥(是的,我知道Data.Bits):返回一个decyphered字符串作为元组的一部分,在Haskell

module XOR where 
import Data.List 
import Data.Char 
decToBin :: Integer -> [Integer] 
decToBin x = reverse $ decToBin' x 
    where 
     decToBin' 0 = [] 
     decToBin' y = let (a,b) = quotRem y 2 in [b] ++ decToBin' a 
binToDec :: [Integer] -> Integer 
binToDec xs = foldl (+) 0 $ map (\(x,y) -> x*(2^y)) $reverse $ zip (reverse xs) [0..] 

bitwise f x y = zipWith f x y 

lenBin :: Integer -> Integer 
lenBin x= length$ decToBin x 

xor :: Integer -> Integer -> Bool 
xor x y | x == y = 0 
     | x /= y = 1 
     | otherwise = error "Impossible" 

bitwiseXOR :: Integer -> Integer -> Integer  
bitwiseXOR a b | (lenBin a) > (lenBin b) = binToDec $ bitwise xor ((replicate ((lenBin a) - (lenBin b)) 0)++(decToBin b)) (decToBin a) 
       | (lenBin a) < (lenBin b) = binToDec $ bitwise xor ((replicate ((lenBin b) - (lenBin a)) 0)++(decToBin a)) (decToBin b) 
       | otherwise =binToDec $ bitwise xor (decToBin b) (decToBin a) 

decyph :: [char] -> [char] 
decyph key = map chr $ map (\(x,y)-> bitwiseXOR x (ord y)) $ zip numbers $ cycle key 

brute :: [([Char],[Char])] 
brute = [(n,k)|k<- (sequence $ replicate 3 ['a'..'z']) ,n <- decyph k, "the" `isInfixOf` n] 

numbers :: [Integer] 
numbers = [79,59,12,2,79,35,8...] 

问题是,当我不能运行decyph,因为它生成的元组只包含第一部分中的一个字符和第二部分中的密钥,而不是使用所用密钥的整个解密文本。我怎样才能解决这个问题?

PS:假设文本中包含字符串“the”是否合理?

+1

为了清晰起见,您可以添加函数的类型吗? – 2009-12-19 13:52:18

回答

2

decyph key将解密后的文本作为[Char]返回。随着语法

n <- decyph k 
在列表理解

nChar类型和分配的解密文本的单个字符,但你想要的这里是它被赋予的decyph全部结果,以便使它

let n = decyph k 

最后,检查elem类型:

> :t elem 
elem :: (Eq a) => a -> [a] -> Bool 

与类型n[Char],第一个参数必须是Char,但是你有另一个字符串。如果你想与elems工作,你可以在口头上分裂的破译文字:

"the" `elem` words n 

这将编译在这里呢。

PS:假设 文本将包含字符串“the”是否合理?

这肯定是一个常见的英文单词,但文字也可能会被全部大写或the只可能在一个句子的开头显示为The

相关问题