Drkcore

23 01 2010 Haskell Tweet

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 ()
在庫あり。

About

  • もう5年目(wishlistありマス♡)
  • 最近はPythonとDeepLearning
  • 日本酒自粛中
  • ドラムンベースからミニマルまで
  • ポケモンGOゆるめ

Tag

Python Deep Learning javascript chemoinformatics Emacs sake and more...

Ad

© kzfm 2003-2021