ceth
ceth

Reputation: 45295

How can I use map in this case

I have the code which create Data.Map:

import qualified Data.Map as Map

shift_string :: [Char] -> Int -> [Char]
shift_string s num = (drop num s) ++ (take num s)

ascii :: [Char]
ascii = ['a' .. 'z']

shifted_ascii :: Int -> [Char]
shifted_ascii n = shift_string ascii n

trans_table :: Int -> Map.Map Char Char
trans_table n = Map.fromList(zip ascii $ shifted_ascii n)

The 'trans_table' function returns the Map where one Char map to another map. I can create the function to get one Char and return another one based on this Map:

translate_char :: Char -> Int -> Maybe Char
translate_char c n = Map.lookup c $ trans_table n

Now I want to 'translate' each symbol in the map. Something like this:

encode message key = map translate_char message

This code doesn't work as translate_function must have only one parameter. I need something like global variable to store the Map in it and lookup values from it in my map-function. But I don't know how to rewrite my code.

p.s. I guess I can just add 'key' to each char in my string but I am searching common solution.

Upvotes: 0

Views: 175

Answers (1)

Satvik
Satvik

Reputation: 11208

I don't know whats key in your encode function but you can use something like

translate_char :: Int -> Char -> Maybe Char
translate_char n c = Map.lookup c $ trans_table n

encode :: Int -> String -> String
encode n s = catMaybes $ map (translate_char n) s

here n determines the number of characters you are rotating. I switched the order of parameters to avoid using flip.

Upvotes: 1

Related Questions