The intercalate
function is useful but can be confusing – some people aren’t sure how to pronounce it, it’s not a common English word, and it’s easily confused with intersperse
. We’re here to salve this anxiety.The words ‘intersperse’ and ‘intercalate’ are near synonyms in English, although ‘intercalate’ has a few specialized uses. ‘Intercalate’ is pronounced “in-ter’-kuh-late” with the main stress on the ter. Cognate words such as intercalar in Spanish may be more commonly used than ‘intercalate’ is in English; we’ve been told the Italian version sometimes has the specialized meaning of inserting meaningless words and phrases such as “I mean” or “like” between sentences. We point this out here because for us it was a helpful mnemonic – inserting strings such as “like” into lists of strings.
Both intercalate
and intersperse
are from the Data.List
module in the base
library, and they are related to each other.Data.List
λ> import Data.List
λ> :type intersperse
intersperse :: a -> [a] -> [a]
λ> :type intercalate
intercalate :: [a] -> [[a]] -> [a]
intersperse
takes a value of type a
and intersperses it between the elements of a list of a
.
λ> intersperse ' ' "seriously"
"s e r i o u s l y"
λ> intersperse (-1) [10..15]
[10,-1,11,-1,12,-1,13,-1,14,-1,15]
intercalate
takes a list of a
as its first argument, intersperses that list of a
between the other lists in a [[a]]
, and concat
s the resulting list of lists.
λ> intercalate ", like, " ["seriously", "wow"]
"seriously, like, wow"
λ> intercalate [1, 2, 3] [[0], [4, 5, 6], [0]]
[0,1,2,3,4,5,6,1,2,3,0]
Thus, intercalate
is equivalent to concat (intersperse xs [xs])
.
It is worth noting that versions of these functions for collections other than lists exist in the various packages and modules that house those types.
Some, such as NonEmpty
and Data.Sequence
from the containers
package, only have intersperse
.
intersperse :: a -> NonEmpty a -> NonEmpty a
Data.NonEmpty
intersperse :: a -> Seq a -> Seq a
Data.Sequence
Others, such as text
and bytestring
, have both functions.
text
bytestring
intersperse :: Word8 -> ByteString -> ByteString
Data.ByteString
intercalate :: ByteString -> [ByteString] -> ByteString
Data.ByteString
When a module has both functions, they are usually listed next to each other in the documentation.
Finally, there are generalizations of both these functions in the ListLike
package; unfortunately, they don’t live in the same module.
intersperse :: ListLike full item => item -> full -> full
Data.ListLike
intercalate :: (ListLike a item, ListLike b a) => a -> b -> a
Data.ListLike.Utils