在这种情况下如何使用地图

时间:2012-10-27 19:14:37

标签: haskell

我有创建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)

' trans_table'函数返回Map,其中一个Char映射到另一个映射。 我可以创建函数来获取一个Char并根据此Map返回另一个:

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

现在我想翻译'地图中的每个符号。像这样:

encode message key = map translate_char message

此代码不起作用,因为translate_function必须只有一个参数。我需要像全局变量这样的东西来存储Map并在我的map-function中查找它的值。但我不知道如何重写我的代码。

P.S。我想我可以添加' key'我的字符串中的每个字符,但我正在寻找常见的解决方案。

1 个答案:

答案 0 :(得分:1)

我不知道您的编码功能中有什么关键,但您可以使用类似

的内容
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

这里n确定您要旋转的字符数。我改变了参数的顺序以避免使用flip