Haskell&The Caesar Cipher

Overvier

例子来自Programming in Haskell(很好的一本书,简要明了), 主要是将list comprehension。仅仅短短几十行代码…充分体现了FP的concise…

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55

module FirstScript where
import Test.QuickCheck
import Test.HUnit
import Data.Char

let2int :: Char -> Int
let2int c = ord c - ord 'a'
int2let :: Int -> Char
int2let n = chr(ord 'a' + n)

shift :: Int -> Char -> Char
shift n c | isLower c = int2let((let2int c + n) `mod` 26)
| otherwise = c

encode :: Int -> String -> String
encode n xs = [shift n x | x <- xs]

percent :: Integer -> Integer -> Float
percent n m = (fromInteger n / fromInteger m)*100

count :: Char -> String -> Integer
count c string = sum[ 1 | x <- string, c == x ]

lowers :: String -> Integer
lowers xs = sum[ 1 | x <- xs, isLower x ]

freqs :: String -> [Float]
freqs xs = [percent (count x xs) n | x <- ['a'..'z']]
where n = lowers xs
table :: [Float ]
table = [8.2, 1.5, 2.8, 4.3, 12.7, 2.2, 2.0, 6.1, 7.0, 0.2, 0.8, 4.0, 2.4,
6.7, 7.5, 1.9, 0.1, 6.0, 6.3, 9.1, 2.8, 1.0, 2.4, 0.2, 2.0, 0.1]

chisqr :: [Float] -> [Float] -> Float
chisqr os es = sum[ (o-e)^2 | (o, e) <- zip os es]

rotate :: Int -> [a] -> [a]
rotate n xs = drop n xs ++ take n xs

positions :: Eq a => a -> [a] -> [Int]
positions x xs = [ i | (x', i) <- zip xs [0..n-1], x' == x] where
n = length xs

crack :: String -> String
crack xs = encode (-factor) xs where
factor = head (positions (minimum chitab) chitab)
chitab = [chisqr (rotate n table') table | n <- [0..25]]
table' = freqs xs

-- test data
-- crack (encode 3 "Haskell is fun and I love it!")
-- crack (encode 3 "Haskell is fun!")
-- crack (encode 3 "haskell is fun!")

ps:一开始看到用卡方值还一阵惊讶,我可能不是一个合格的玩统计的人…其实从前面开始讲词频的时候就该想到和分布有关,然后由于一般性,首先应该想到正态分布,进而就是”集成正态分布“的卡方分布了。

本文标题:Haskell&The Caesar Cipher

文章作者:不秩稚童

发布时间:2018年02月07日 - 21:04:24

最后更新:2018年02月07日 - 21:13:35

原始链接:http://datahonor.com/2018/02/07/Haskell-The-Caesar-Cipher/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

击蒙御寇