Is there any haskell function to concatenate list with separator?

ListHaskellConcat

List Problem Overview


Is there a function to concatenate elements of a list with a separator? For example:

> foobar " " ["is","there","such","a","function","?"]
["is there such a function ?"]

Thanks for any reply!

List Solutions


Solution 1 - List

Yes, there is:

Prelude> import Data.List
Prelude Data.List> intercalate " " ["is","there","such","a","function","?"]
"is there such a function ?"

intersperse is a bit more general:

Prelude> import Data.List
Prelude Data.List> concat (intersperse " " ["is","there","such","a","function","?"])
"is there such a function ?"

Also, for the specific case where you want to join with a space character, there is unwords:

Prelude> unwords ["is","there","such","a","function","?"]
"is there such a function ?"

unlines works similarly, only that the strings are imploded using the newline character and that a newline character is also added to the end. (This makes it useful for serializing text files, which must per POSIX standard end with a trailing newline)

Solution 2 - List

It's not hard to write one-liner using foldr

join sep xs = foldr (\a b-> a ++ if b=="" then b else sep ++ b) "" xs
join " " ["is","there","such","a","function","?"]

Solution 3 - List

Some other ideas of implementations of intersperse and intercalate, if someone is interested:

myIntersperse :: a -> [a] -> [a]
myIntersperse _ [] = []
myIntersperse e xs = init $ xs >>= (:[e])

myIntercalate :: [a] -> [[a]] -> [a]
myIntercalate e xs = concat $ myIntersperse e xs

xs >>= f is equivalent to concat (map f xs).

Solution 4 - List

joinBy sep cont = drop (length sep) $ concat $ map (\w -> sep ++ w) cont

Solution 5 - List

If you wanted to write your own versions of intercalate and intersperse:

intercalate :: [a] -> [[a]] -> [a]
intercalate s [] = []
intercalate s [x] = x
intercalate s (x:xs) = x ++ s ++ (intercalate s xs)

intersperse :: a -> [a] -> [a]
intersperse s [] = []
intersperse s [x] = [x]
intersperse s (x:xs) = x : s : (intersperse s xs)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFopa Léon ConstantinView Question on Stackoverflow
Solution 1 - ListNiklas B.View Answer on Stackoverflow
Solution 2 - ListIlya KharlamovView Answer on Stackoverflow
Solution 3 - ListAlexisView Answer on Stackoverflow
Solution 4 - ListAlayaView Answer on Stackoverflow
Solution 5 - ListZoey HewllView Answer on Stackoverflow