Is there a haskell function to combine a list with a separator?

Is there a function to concatenate delimited list items? For example:

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

Thanks for any answer!

+82
list haskell concat
Feb 10 2018-12-12T00:
source share
4 answers

Yes there are :

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

intersperse is more general:

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

In addition, for the specific case when you want to join a whitespace, there are unwords :

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

unlines works similarly, only lines are inserted using a newline character (and for some reason a newline is added at the end too).

+149
Feb 10 2018-12-12T00:
source share
 joinBy sep cont = drop (length sep) $ concat $ map (\w -> sep ++ w) cont 
+2
Mar 04 '16 at 4:34
source share

If you want 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) 
0
Feb 04 '17 at 9:49 on
source share

It's not hard to write a single line file with foldr

 join sep xs = foldr (\a b-> a ++ if b=="" then b else sep ++ b) "" xs join " " ["is","there","such","a","function","?"] 
0
May 21 '17 at 20:02
source share



All Articles