简单的行转置密码
对于 Lisp 课程,我们被布置了一个简单的行转置密码作业,我也尝试在 Haskell 中解决该作业。基本上,只需将字符串拆分为长度为 n 的行,然后转置结果。所得到的字符列表的串联就是加密的字符串。解码有点困难,因为输入的最后一行中可能缺少元素(结果中的不完整列),必须注意这一点。
这是我在 Haskell 中的解决方案:
import Data.List
import Data.Ratio
import Data.List.Split
encode :: String -> Int -> String
encode s n = concat . transpose $ chunk n s
decode :: String -> Int -> String
decode s n = take len $ encode s' rows
where s' = foldr (insertAt " ") s idxs
rows = ceiling (len % n)
idxs = take (n-filled) [n*rows-1,(n-1)*rows-1..]
filled = len - n * (rows - 1)
len = length s
insertAt :: [a] -> Int -> [a] -> [a]
insertAt xs i ys = pre ++ xs ++ post
where (pre,post) = splitAt i ys
它可以完成工作,但我不确定这是否被认为是惯用的 Haskell,因为我对索引的摆弄并没有感觉太声明性。这是否可以改进?如果可以,如何改进?
顺便问一下:Haskell 98 中有类似 insertAt
的东西吗?即,将给定索引处的元素或列表插入到列表中的函数。
注意:这不是作业的一部分,无论如何,作业都是今天到期的。
For a Lisp class, we were given a simple row transposition cipher homework, which I tried to solve in Haskell, too. Basically, one just splits a string into rows of length n
, and then transposes the result. The concatenation of the resulting list of lists of chars is the encrypted string. Decoding is a little harder, since there may be missing elements in the last row of input (incomplete columns in the result), which have to be taken care of.
This is my solution in Haskell:
import Data.List
import Data.Ratio
import Data.List.Split
encode :: String -> Int -> String
encode s n = concat . transpose $ chunk n s
decode :: String -> Int -> String
decode s n = take len $ encode s' rows
where s' = foldr (insertAt " ") s idxs
rows = ceiling (len % n)
idxs = take (n-filled) [n*rows-1,(n-1)*rows-1..]
filled = len - n * (rows - 1)
len = length s
insertAt :: [a] -> Int -> [a] -> [a]
insertAt xs i ys = pre ++ xs ++ post
where (pre,post) = splitAt i ys
It does the job, but I am not sure, whether this would be considered idiomatic Haskell, since my fiddling with the indices does not feel too declarative. Could this be improved, and if yes, how?
By the way: Is there something akin to insertAt
in Haskell 98? I.e. a function inserting an element or list at a given index into a list.
Note: This is NOT part of the homework, which was due today anyway.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我会通过稍微不同地查看
encode
和decode
问题来做到这一点。encode
将数据分解为n
列矩阵,然后将其转置(转置为n
行矩阵)并按行连接。decode
将数据分解为n
行矩阵,然后将其转置(转换为n
列矩阵)并按行连接。因此,我首先定义两个函数 - 一个将数组制作为
n
列矩阵:另一个将数组切片为
n
行矩阵:现在,编码解码相当简单:
I would do this by looking at the
encode
anddecode
problems slightly differently.encode
breaks up the data into an
-column matrix, which it then transposes (into an
-row matrix) and concatenates by rows.decode
breaks up the data into an
row matrix, which it then transposes (into an
columm matrix) and concatenates by rows.So I'd start by defining two functions - one to make an array into an
n
column matrix:and another to slice an array into an
n
row matrix:Now, encoding and decoding is fairly easy: