Czy jest jakaś funkcja haskell do łączenia listy z separatorem?

Czy istnieje funkcja do łączenia elementów listy z separatorem? Na przykład:

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

Dzięki za każdą odpowiedź!

Author: Matvey Aksenov, 2012-02-10

4 answers

Tak, jest :

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

intersperse jest nieco bardziej ogólne:

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

Również, w konkretnym przypadku, w którym chcesz połączyć się ze znakiem spacji, jest unwords:

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

unlines działa podobnie, tylko że ciągi znaków są implodowane za pomocą znaku nowej linii i że znak nowej linii jest również dodawany na końcu. (To czyni go użytecznym do serializacji plików tekstowych, które zgodnie ze standardem POSIX muszą kończyć się końcową linią nowego wiersza)

 179
Author: Niklas B.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-12 09:12:24
joinBy sep cont = drop (length sep) $ concat $ map (\w -> sep ++ w) cont
 2
Author: Alaya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-04 04:34:26

Jeśli chcesz napisać własne wersje intercalate i 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)
 1
Author: Zoey Hewll,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-04 11:38:48

Nietrudno napisać jednolinijkowy za pomocą foldr

join sep xs = foldr (\a b-> a ++ if b=="" then b else sep ++ b) "" xs
join " " ["is","there","such","a","function","?"]
 1
Author: Ilya Kharlamov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-22 03:42:57