Search code examples
haskellfunctional-programminghaskell-prelude

Why does Haskell function tails include the whole list?


Introduction and context

In Haskell we have the function tail that provides the suffix of a list.

For example:

tail [1,2,3]

gives

[2, 3]

The function tails would give instead all the suffixes:

tails [1,2,3]

gives

[[1,2,3],[2,3],[3],[]]

Question

Why does it return tha whole list as first argument? I expected to return all real suffixes, i.e. I expected

tails [1,2,3]

to give

[[2,3],[3],[]]

or maybe even

[[2,3],[3]]

without the empty list.

Is there a formal/logical reason for tails to behave this way, or is it just random, i.e. simply how it used to work in the original implementation and never changed?

I searched the question around and I did not find a decent explanation for this.


Solution

  • As the documentation on tails :: [a] -> [[a]] [Hackage] says:

    The tails function returns all final segments of the argument, longest first.

    so all suffixes. A list is always a suffix of itself. tails is essentially implemented as:

    tails :: [a] -> [[a]]
    tails [] = [[]]
    tails xs@(_:xs') = xs : tails xs'
    

    it thus returns the list itself, and the tails of its tail, if any. If you are only interested in the strict tails, we can work with the tail of the tale:

    tail . tails
    

    which is guaranteed to work, since for an empty list, tails [] will return a singleton list, and thus (tail . tails) [] will then return an empty list.