Skip to main content
2 of 5
added 1 character in body
toolic
  • 15.8k
  • 6
  • 29
  • 217

HackerRank, Haskell simple "compression" algorithm

The question asked is very straight-forward and is simple enough to solve. What I am looking for hopefully is that I can get some understanding for using the constructs and built-ins of the Haskell language itself.

That said, the question is as follows:enter image description here

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.

tijko
  • 782
  • 1
  • 5
  • 13