编写代码来反转Haskell程序

时间:2017-09-28 17:20:45

标签: function haskell

我编写了一个程序,它将消息作为字符串,并根据需要通过用X填充消息来返回anagram,使得字符串长度恰好有4个因子,然后基本上重新排列消息,就好像它已经在网格中组织并读取而不是跨越。例如,输入" Haskell"将返回字符串," HealslkX"。我编写了一个程序来编码这个字谜,但我在编写一个可以反转前一个程序并解码anagram的程序时遇到了麻烦,特别是应该删除X填充的removeX函数。这就是我所拥有的:

编码:

import Data.List

factors :: Int -> [Int]
factors n = [x | x <- [1..n], n `mod` x == 0]

split :: Int -> [a] -> [[a]]
split _ [] = []
split n xs =
    let (ys, zs) = splitAt n xs
    in  ys : split n zs

encode :: [Char] -> [Char]
encode (x:xs) = if (length (factors (length xs))) == 4 then concat 
(transpose (split ((factors (length xs))!!2) xs))
else encode (xs ++ ['X'])

解码:

import Data.List

factors :: Int -> [Int]
factors n = [x | x <- [1..n], n `mod` x == 0]

split :: Int -> [a] -> [[a]]
split _ [] = []
split n xs =
    let (ys, zs) = splitAt n xs
    in  ys : split n zs

removeX :: [a] -> [a]
removeX xs = if (last xs) == 'X' then ((init xs) && removeX xs)
 else xs

decode :: [Char] -> [Char]
decode (x:xs) = removeX (concat (transpose (split ((factors (length xs))!!1) xs)))

1 个答案:

答案 0 :(得分:3)

只需使用A | B | C | D | E A A A A F 12 32 43 23 2 代替D A 23 。 Haskell不是程序性的(你不记下要做的一系列更改)但是功能性(你写下了从旧产生新结果的函数)。但是,Haven没有阅读其余的代码,看看是否还有其他错误。

还要考虑removeX (init xs)以提高效率。列表是单链接的,因此最后的访问和修改相对昂贵。