idiom for producing comma-seperated lists?

Antony Courtney
Fri, 08 Aug 2003 09:48:22 -0400

I often need to format a list of strings using some character as a 
*seperator* rather than a terminator for the items.  Is there some 
simple combinator or idiom from the Prelude or standard libraries that 
could be used for this purpose?

I ended up defining my own variation on foldr1 to solve this (code 
below), but I'd be much happier using some more standard solution:

-- A variation on foldr1 that takes an extra argument to be returned if
-- the list is empty.

foldrs :: (a -> a -> a) -> a -> [a] -> a
foldrs f z [] = z
foldrs f _ xs = foldr1 f xs

-- Example: format a list of strings, using a comma as a seperator:
mkSepStr :: [String] -> String
mkSepStr xs = foldrs (\x s -> x ++ ", " ++ s) "" xs

t0 = mkSepStr []                   -- ==> ""
t1 = mkSepStr ["hello"]            -- ==> "hello"
t2 = mkSepStr ["10","20","30"]     -- ==> "10, 20, 30"

What do the rest of you do to solve this particular problem?  If there 
isn't a standard solution, perhaps something like foldrs would be a 
useful addition to the Prelude.



Antony Courtney
Grad. Student, Dept. of Computer Science, Yale University