wvogel日記

自分用の技術備忘録が多めです.

caesar

シーザー暗号もどき

もう一度いいます。シーザー暗号もどきです(復号不可)。
確かシーザー暗号は、文字を数文字ずらすだけだったはずだけど、無駄に掛け算とかしてみた。
あと、残りの文字列長に依存させると面白いかも、と思ったり。

復号も、
そんなに難しい処理しているわけでは無いので復号できるはずだけど、面倒なので。
とりあえず、こんな感じに。

import Data.Maybe

clist = zip [0..] $ ['a'..'z']++['A'..'Z']++['0'..'9']

main = do print $ caesar toCaesar  "password"
          --print $ caesar fromCaesar   "password"

toCaesar :: String -> Int
toCaesar str = mod (2*length str+16) $ length clist
{-
fromCaesar :: String -> Int
fromCaesar str = --未完成
-}
caesar :: (String -> Int) -> String -> String
caesar _ [] = []
caesar f (c:cs) = case lookup_snd c clist of
                   Just n -> fromJust (lookup (f cs) clist)
                               : caesar f cs
                   Nothing-> "!! something is wrong"

lookup_snd :: Eq a => a -> [(b,a)] -> Maybe b
lookup_snd _ [] = Nothing
lookup_snd c (x:xs) = if snd x == c
                       then Just (fst x)
                       else lookup_snd c xs