1

I have written a program that takes a message as a string and returns an anagram by padding the message with X's as needed such that the string length has exactly 4 factors then essentially rearranges the message as if it had been organized in a grid and read down instead of across. For example, inputting, "Haskell" would return the string, "HealslkX". I have written a program that encodes this anagram, but am having trouble writing a program that can reverse the previous program and decode the anagram, particularly with the removeX function that should remove the X padding. Here is what I have:

encode:

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'])

decode:

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)))
0

1 Answer 1

3

Just use removeX (init xs) instead of init xs && removeX xs. Haskell is not procedural (you don't write down a sequence of changes to make) but functional (you write down functions that produce new results from old). Haven't read the rest of the code to see if there are other errors, though.

Also consider removeX = reverse . dropWhile ('X'==) . reverse for better efficiency. Lists are singly-linked, so accesses and modifications at the end are relatively expensive.

Sign up to request clarification or add additional context in comments.

1 Comment

dropWhileEnd is in Data.List now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.