Reputation: 25
I want to make a String from a list of chars [Lettre]
For example, ['1', '2', '3', 'W', '5', '5', 'W', '3'] should be printed as (1, 2, 3, W, 5, 5, W, 3)
Now, I use
data Lettre = Steen Char
makeString :: [Lettre] -> String
makeString [] = ""
makeString [Steen(x)] = x:[]
makeString (Steen(x):xs) = (x:", ") ++ makeString xs
but I feel like this could be easier.
Is there a simple function, something like toString? I tried using some functions I knew, but it doesn't seem to work on my code, so I keep using makeString.
A big thanks to anyone who could help me out :)
Upvotes: 0
Views: 156
Reputation: 531265
Given a list of a characters, you could use intersperse
, but that only allows single-character separators.
> "(" ++ intersperse ',' "123W55W3" ++ ")"
"(1,2,3,W,5,5,W,3)"
For a multicharacter separator like ", "
, you can use intercalate
, but then you need a list of String
, not a list of Char
.
The solution is to lift each character into a string, then use intercalate
.
> "(" ++ intercalate ", " (map pure "123W55W3") ++ ")"
"(1, 2, 3, W, 5, 5, W, 3)"
I'm assuming the input is an actual [Char]
/String
value; if you actually have some more complicated Char
wrapper, like
newtype Lettre = Steen Char
as could be inferred from your attempt, use instead something like
makeString :: [Lettre] -> String
makeString xs = "(" ++ intercalate ", " [[x] | Steen x <- xs] ++ ")"
Upvotes: 7