intercalate

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

intersperse takes a value of type a and intersperses it between the elements of a list of a.

intercalate takes a list of a as its first argument, intersperses that list of a between the other lists in a [[a]], and concats the resulting list of lists.

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.

Others, such as text and bytestring, have both functions.

  • text
    • intersperse :: Char -> Text -> Text Data.Text
    • intercalate :: Text -> [Text] -> Text Data.Text
  • bytestring

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.

Type Classes offers courses and projects to get you started and make you an expert in FP with Haskell. For $29/month, you get access to the complete archive and all the latest content.