我是Haskell的初学者(今天早上开始),并且试图通过将字符串转换为ASCII,将指定的整数添加到ASCII,然后再转换回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
应该是一个字符串,其第一个字符是x
using的编码y
,即encodeChar x y
,而字符串的其余部分(尾部)是xs
using的编码y
,即递归调用的结果。
然后我们得到:
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句