drkcore

2010/01/23 17:57:47

Haskellで文字のローテーション

プログラム・プロムナードRubicキューブと置換の乗算を読んでいたら、文字のローテションをしたいときにcycleを使っているのを見つけた。

import List

shift n c xs = case elemIndex c xs of
                 Nothing -> c
                 Just i  -> cycle xs !! (i + n) 

こんな感じ。

*Main> shift 1 'y' ['a'.. 'z']
'z'
*Main> shift 1 'z' ['a'.. 'z']
'a'
*Main> shift 1 ' ' ['a'.. 'z']
' '

これを使えばプログラミングHaskellのシーザー暗号は次のように書ける

import List

chrs = ['a'..'z']

shift n c xs = case elemIndex c xs of
                 Nothing -> c
                 Just i  -> cycle xs !! (i + n)   

encode n xs = [shift n x chrs | x <- xs]

実行

*Main> encode 3 "haskell is fun"
"kdvnhoo lv ixq"

ProductName プログラミングHaskell
Graham Hutton
オーム社 / ¥ 2,940 ()
在庫あり。

Comments