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.
intersperse are from the
Data.List module in the
base library, and they are related to each other.
λ> 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
λ> 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
concats the resulting list of lists.
λ> intercalate ", like, " ["seriously", "wow"] "seriously, like, wow" λ> intercalate [1, 2, 3] [, [4, 5, 6], ] [0,1,2,3,4,5,6,1,2,3,0]
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
Data.Sequence from the
containers package, only have
Others, such as
bytestring, have both functions.
It’s worth noting that 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.