The question asked is very straight-forward and is simple enough to solve. What I am looking for hopefully 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:
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.