For the Lisp class, we were given a simple string string string encryption, which I tried to solve in Haskell. Basically, one just breaks a string into strings of length n , and then wraps the result. Concatenating the resulting list of character lists is an encrypted string. Decoding is a bit more complicated, since the last line of input may not contain elements (incomplete columns as a result) that you need to take care of.
This is my solution in Haskell:
import Data.List import Data.Ratio import Data.List.Split encode :: String -> Int -> String encode sn = concat . transpose $ chunk ns decode :: String -> Int -> String decode sn = 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
This does the job, but I'm not sure if this will be considered idiomatic by Haskell, as my index game doesn't seem too declarative. Could this be improved, and if so, how?
By the way, is there something similar to
insertAt in Haskell 98? That is, a function that inserts an item or list with a given index into the list.
Note. This is NOT part of the homework that was supposed to happen anyway.
danlei
source share