In the Middle: Intersperse and Intercalate

This week we continue looking at some useful list-based functions in the Haskell basic libraries. Last time around we looked at boolean functions, this time we'll explore a couple functions to add elements in the middle of our lists.

These functions are intersperse and intercalate:

intersperse :: a -> [a] -> [a]

intercalate :: [a] -> [[a]] -> [a]

Using "intersperse" will place a single item in between every item in your list. For example:

>> intersperse 0 [1, 2, 1]
[1, 0, 2, 0, 1]

This can be used in strings, for example, to space out the letters:

>> intersperse ' ' "Hello"
"H e l l o"

The "intercalate" function is similar but "scaled up". Instead taking a single element and a list of elements as its two inputs, it takes a list and a "list of lists". This is even more flexible when it comes to the use case of separating strings. For example, you can comma separate a series of words:

>> intercalate ", " ["Hello", "my", "friend"]
"Hello, my, friend"

Using intercalate combined with map show can make it very easy to legibly print a series of items if you use commas, spaces, and newlines!

Another use case for intercalate could be if you are constructing a numeric matrix, but you want to add extra columns to pad on the right side. Suppose this is our starting point:

1 2 3 4
5 6 7 8
9 8 7 6
5 4 3 2

But what we want is:

1 2 3 4 0 0 0
5 6 7 8 0 0 0
9 8 7 6 0 0 0
5 4 3 2 0 0 0

Here's how we do this:

>> intercalate [0, 0, 0] [[1, 2, 3, 4], [5, 6, 7, 8], [9, 8, 7, 6], [5, 4, 3, 2]]
[ 1, 2, 3, 4, 0, 0, 0
, 5, 6, 7, 8, 0, 0, 0
, 9, 8, 7, 6, 0, 0, 0
, 5, 4, 3, 2, 0, 0, 0
]

The result ends up as just a single list though, so you can't really compose calls to intercalate. Keep that in mind! Also, unlike the boolean functions from last time, these only work on lists, not any Foldable object.

Make sure you subscribe to our monthly newsletter so you can stay up to date with the topic each month! Subscribing will give you access to all our subscriber resources, including our Beginners Checklist, so don't miss out!

Previous
Previous

"Group" Theory

Next
Next

Booleans in Lists