Reputation: 705
I've started to learn haskell for real recently, and I'm doing some exercises from wikibooks. I'm doing exercise with RLE encoding, and I've come with solution like this:
import Data.List
rle :: String -> [(Int,Char)]
rle [] = []
rle xs = zip lengths chars
where
groups = group xs
lengths = map length groups
chars = map head groups
rle_toString :: [(Int, Char)] -> String
rle_toString [] = []
rle_toString (x:xs) = show (fst x ) ++ show (snd x) ++ rle_toString xs`
Not a very elegant solution, but it almost works. The problem is, that I get output like this: "7'a'8'b'7'j'6'q'3'i'7'q'1'p'1'a'16'z'2'n'"
. The single quotes with chars are not vetry elegant. How can I achieve output like: "7a8b7j6q3i7q1p1a16z2n"
?
Upvotes: 1
Views: 917
Reputation: 4231
show
is used to print values as they appear in Haskell source code, and thus puts single quotes around characters (and double quotes around strings, and so on). Use [snd x]
instead to show just the character.
In Haskell, String
is just shorthand for List of Char [Char]
. For example, the String "Foo"
can also be written like this: ['F','o','o']
. So, to convert a single character to a string, just put in in brackets: [char]
.
Upvotes: 6
Reputation: 11362
The problem is your use of show
on a character. show 'a' == "'a'"
.
The solution is to realize that strings are just lists of characters, so if c
is a character, then the one-character string that contains c
is just [c]
.
Upvotes: 1