I am trying to decode a string that can contain numbers but am not sure in how these characters can be detected apart from pattern matching like this.
This is not meant to be done with any imported library functions I just need to find a way to repeat the character dependent on the number after the initial character.
decode :: String -> String
decode [] = []
decode (x:xs)
| x == '1' = x : decode xs
| x == '2' = x : x : decode xs
| x == '3' = x : x : x : decode xs
| x == '4' = x : x : x : x : decode xs
| x == '5' = x : x : x : x : x : decode xs
| x == '6' = x : x : x : x : x : x : decode xs
| x == '7' = x : x : x : x : x : x : x : decode xs
| x == '8' = x : x : x : x : x : x : x : x : decode xs
| x == '9' = x : x : x : x : x : x : x : x : x : decode xs
| otherwise = (x:xs)
Doing this just returns the following:
ghci> decode "a1b2"
"a1b2"
So am not sure what is currently going wrong
You're looking at the first character to be a digit, then repeating that digit. Otherwise you're just returning the input string.
This isn't right.
We need to look at two characters at the beginning of a string. If the second is a digit, we need to repeat. If it isn't, then typical run length encoding means it only occurs once. After all,
"c1"is longer than"c", which makes for a poor compression system.Fortunately pattern matching makes this straightforward.
Using your rather simple, but tedious repetition logic:
If you import
Data.Charyou ca test if the second char is a digit, and then manipulate that digit to repeat the character the correct number of times.