![](/img/trans.png)
[英]How can I convert a String of ascii values back to their String/Character values?
[英]How can I convert a String into ASCII and then back in Haskell?
我是Haskell的初学者(今天上午开始),并且试图通过将字符串转换为ASCII,将指定的整数添加到ASCII,然后再转换回String的方式来实现对字符串进行加密的功能。 我想我已经为单个字符正确地做到了这一点,但是在完整的String方面我却陷入了困境:
import Data.Char
encodeChar :: Char -> Int -> Char
encodeChar 'x' y = chr ((ord 'x') + y)
encode :: String -> Int -> String
encode (x : xs) y = chr ((ord (x : xs)) + y)
要对字符串进行编码,一个选项是递归进行。 首先,我们选择如何对空列表[]
进行编码。 然后,假设encode xs y
完成工作,我们定义应为encode (x:xs) y
。
经过一番反思,我们可以看到encode (x:xs) y
应该是一个字符串,其第一个字符是使用y
对x
进行编码,即encodeChar xy
,而字符串的其余部分(尾部)是使用y
对xs
进行编码。 ,即递归调用的结果。
然后,我们获得:
encode :: String -> Int -> String
encode [] y = []
encode (x : xs) y = encodeChar x y : encode xs y
这种递归是如此普遍,以至于有一个库函数map
可以为我们执行它。
map f [x1, .., xn]
返回[f x1, .., f xn]
。 因此,我们可以在整个字符串上映射encodeChar
函数。
encode :: String -> Int -> String
encode xs y = map (\x -> encodeChar x y) xs
-- or, using more advanced functions
encode xs y = map (flip encodeChar y) xs
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.