In functional list manipulation, what do we call “inserting something between each item”?
-
18-09-2019 - |
Question
Occasionally I find I need to process a list by inserting a new item after each item, except the last one. Similar to how you might put a comma between each item of a list of strings.
I got fed up of coding the special case for the last (or first) item every time, so I captured the pattern in a Linq-style extension:
public static IEnumerable<T> Separate<T>(this IEnumerable<T> source,
Func<T> separator)
{
bool first = true;
foreach (T item in source)
{
if (first)
first = false;
else
yield return separator();
yield return item;
}
}
For example, this allows me to easily programatically fill a flow document with hyperlinks, but with a line-break between each one:
para.Inlines.AddRange(_recentFiles.Select(f => f.ToHyperlink())
.Separate(() => new LineBreak()));
Assuming this doesn't already exist in System.Linq.Enumerable (which is what I typically discover immediately after writing something like this), the question is, what is this Separate
operation on lists usually called in other functional frameworks or languages?
Solution
Haskell: intersperse
Zip
usually means a different operation (zip [a, b, c] [x, y, z] = [(a, x), (b, y), (c, z)]
)
OTHER TIPS
It's often called Join.
It looks a little like string.Join(), although Join doesn't return a real list.
It is also called interpose in Clojure.
user> (interpose "," ["a" "b" "c"])
("a" "," "b" "," "c")
Sounds like doing up a zipper (British - zip), with data on the long side and the separator on the other :-)