Data
Data

Reputation: 769

Converting a list of tuples with type (Char, Int) to a String in Haskell

I'm trying to take a list of tuples, with type [(Char, Int)] and convert it to a string. For example:

tupToStr [('j',9),('x',1),('f',3)]
"j9x1f3"

My attempt is below. My problem is the cons operator requires all values to have the same type. So I can't do 'j' : 9 : [] for example. Therefore you'll see a placeholder function, intToChar, which would ideally convert an Int to a Char. Is there a simple way of doing this conversion, that fits concisely into my existing function? If not, how would you write a function to do the conversion in question?

tupToStr :: [(Char, Int)] -> String
tupToStr []     = []
tupToStr (x:xs) = (fst x) : intToChar(snd x) : tupToStr xs 

Upvotes: 0

Views: 1579

Answers (3)

karakfa
karakfa

Reputation: 67467

tupToStr = concatMap (\(c,i) -> c:show i)

Upvotes: 4

Data
Data

Reputation: 769

Change the bottom line to:

tupToStr ((a,b):xs) = a : show b ++ tupToStr xs

Upvotes: 1

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476493

We can use the intToDigit :: Int -> Char function from Data.Char for that. Furthermore it is more elegant to use pattern matching in the tuple instead of using fst and snd. So we can rewrite it to:

import Data.Char(intToDigit)

tupToStr :: [(Char, Int)] -> String
tupToStr [] = []
tupToStr ((c, n):xs) = c : intToDigit n : tupToStr xs

Note that this will only work given n is always in the range 0..15 (intToDigit will use 'a'..'f' for values greater than nine). In case you want to process values outside the range, you can use show, but this will of course return a String. With the above code, we get:

Prelude Data.Char> tupToStr [('j',9),('x',1),('f',3)]
"j9x1f3"

Upvotes: 2

Related Questions