Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In functional list manipulation, what do we call "inserting something between each item"?

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?

like image 522
Daniel Earwicker Avatar asked Jul 21 '09 11:07

Daniel Earwicker


2 Answers

Haskell: intersperse

Zip usually means a different operation (zip [a, b, c] [x, y, z] = [(a, x), (b, y), (c, z)])

like image 177
Dario Avatar answered Oct 06 '22 02:10

Dario


It's often called Join.

like image 24
Lou Franco Avatar answered Oct 06 '22 01:10

Lou Franco