How do I convert a list of integers [1,2,3] to a string "123"
Sorry for asking the obvious, but I don't seem to be able to find the answer elsewhere.
How do I convert a list of integers [1,2,3] to a string "123"
Sorry for asking the obvious, but I don't seem to be able to find the answer elsewhere.
The best way would be to use show
and concatMap
, which is just a combination of concat
and map
:
> concatMap show [1, 2, 3]
"123"
This also works for numbers with more than one digit:
> concatMap show [10, 20, 30]
"102030"
Since type String = [Char]
, we can just treat this as a list processing problem The first part is to convert each number to its String
representation, which is done simply using show
. Since we want to apply this to a list of numbers, map
is the tool of choice. Finally, we want to join all the string representations (list of Char
representations) into a single string (list of Char
), so concat
is appropriate:
> concat $ map show [1, 2, 3]
"123"
Whenever you see concat $ map f some_list
, you can always use the pre-defined tool concatMap
, since this is precisely its definition:
> concatMap show [1, 2, 3]
"123"
As pointed out in the comments, you can use foldMap
from the Data.Foldable
module that generalizes the whole "map then combine" functionality. The Foldable
typeclass basically just means that you can use fold
s on it, and it also uses Monoid
, which basically just means you have a way to combine two elements, such as concatenation for lists or addition for numbers. Alternatively, you can also use the fact that lists form a Monad
and use the >>=
operator as
> [1, 2, 3] >>= show
"123"
In the end, all of these operations pretty much boil down to applying a function to each element, then combining those results together using some other function. It's a very general pattern and can be applied in a lot of cases, hence why there's generalizations of it.
Alternatively, you could use
map (chr . (ord '0' +)) [1,2,3,4]
if all of your integers are single digits (you would need to import chr
and ord
from Data.Char
).
This works because String
is just a type synonym of [Char]
in Haskell, so all we are doing is just mapping each Int
in your list to the appropriate Char
.