The question asked is very straight-forward and is simple enough to solve. What I am looking for is that hopefully I can get some understanding for using the constructs and built-ins of the Haskell language itself.
That said, the question is as follows:
Joseph and Jane are making a contest for apes. During the process, they have to communicate frequently with each other. Since they are not completely human, they cannot speak properly. They have to transfer messages using postcards of small sizes.
To save space on the small postcards, they devise a string compression algorithm:
If a character, \$ch\$, occurs \$n(> 1)\$ times in a row, then it will be represented by \$\{ch\}\{n\}\$. where \$\{x\}\$ is the value of \$x\$. For example, if the substring is a sequence of \$4\$ 'a' ("aaaa"). it will be represented as "a4".
If a character, \$ch\$, occurs exactly one time in a row, then it will be simply represented as \$\{ch\}\$. For example, if the substring is "a". then it will be represented as "a".
Help Joseph to compress a message. msg.
Input
The only line of input contains a string. msg.
Output
Print the string msg as a compressed message.
Create a messaging system where each word (token) will be compressed based on any consecutive characters.
Single sequenced characters remain the same but multiple identical consecutive characters will be replaced by the character followed by an integer representing the number of times it repeats consecutively.
Example input and output:
Sample Input #00: > abcaaabbb Sample Output #00: > abca3b3 Sample Input #01: > abcd Sample Output #01: > abcd
My code:
-- String representation as a simple Compression Algorithm -- module Main where import Text.Printf compression :: String -> String -> String -> Int -> String compression input output prevChar count | input == "" && output == "" = output | prevChar == "" = compression (tail input) output ([head input]) 1 | input == "" && count > 1 = output ++ prevChar ++ (show count) | input == "" && count < 2 = output ++ prevChar | prevChar == ([head input]) = compression (tail input) output prevChar (count+1) | prevChar /= ([head input]) && count < 2 = compression (tail input) (output ++ prevChar) ([head input]) 1 | prevChar /= ([head input]) && count > 1 = compression (tail input) (output ++ prevChar ++ (show count)) ([head input]) 1 main :: IO () main = do let s1 = "aaabaaaaccaaaaba" printf "Decompressed: %s and Compressed: %s" s1 (compression s1 "" "" 0)
I feel as though some of my Haskell code can be clunky and could use some more features of the language itself as I mentioned earlier.
Now this isn't a full-blown application or even a part of a module for an actual application but just an exercise to improve my working knowledge and skill for writing Haskell.