Guilherme Lima
Guilherme Lima

Reputation: 55

How can I shift just the letters and not the symbols/whitespaces?

I successfully implemented the vigenére cipher in Haskell but it is shifting the whitespaces too. How can I shift only the letters (lower case)?

As an example, lets say I want to encrypt "hello rita" with "abc" as the key. It is printing out "hfnlpprjva" instead of "hfnlp rjva".

Here's the main method:

vigenere_encrypt :: String -> String -> String
vigenere_encrypt key plaintext = ints2text n
  where n = map (`mod` 26) (zipWith (+)  keyCycle intPlainText)
        keyCycle = (cycle(text2ints key))
        intPlainText = text2ints plaintext

And here are the auxiliary functions:

--lowercase letter to int conversion
let2int :: Char -> Int
let2int c = ord c - ord 'a'

--int to lowercase letter conversion
int2let :: Int -> Char
int2let n = chr(ord 'a' + n)

text2ints :: String -> [Int]
text2ints xs = map (let2int) xs

ints2text :: [Int] -> String
ints2text xs = map (int2let) xs

Any suggestions?

Upvotes: 1

Views: 106

Answers (1)

Christophe
Christophe

Reputation: 2012

The script below yields the expected result:

import Data.Char (ord, chr)

--lowercase letter to int conversion
let2int :: Char -> Int
let2int c = ord c - ord 'a'

--int to lowercase letter conversion
int2let :: Int -> Char
int2let n = chr(ord 'a' + n)

text2ints :: String -> [Int]
text2ints xs = map (let2int) xs

ints2text :: [Int] -> String
ints2text xs = map (int2let) xs

vigenere_encrypt :: String -> String -> String
vigenere_encrypt key plaintext = zipWith merge plaintext (ints2text n)
  where n = map (`mod` 26) (zipWith (+)  keyCycle intPlainText)
        keyCycle = (cycle(text2ints key))
        intPlainText = text2ints plaintext
        merge a b = case a of
          ' ' -> ' '
          otherwise -> b

main = do
  print $ vigenere_encrypt "abc" "hello rita"

Note: the code does not skip white spaces but only overwrites them... so practically speaking it means that the the number of spaces will have an impact on the encrypted string. Otherwise the program would be slightly more complex.

Upvotes: 1

Related Questions