I wonder if there is a “functional programming” reason for the function heads not to be implemented in List (or more generally in TraversableLike). To me, heads would be the exact opposite of tails but I must miss something.
As Scala is easy to read, here is what I would see (for the List case):
def heads[T](li:List[T]):List[List[T]] = li match {
case Nil => Nil
case head::tail => (Nil::heads(tail)).map(head::_)
}
So, here are the few possibilities I have thought of for this function not to be implemented:
headrepresents the first element of aList, so it would not make sense to create a function to iterate over all heads are there is only one. Then why not a functionprefixes?- It is not possible to make this function tail recursive so we prefer to ignore it.
- It is useless (is it?)
- It is not compatible with the philosophy of functional programming (why?)
Thanks in advance for your answer.
I think you’re looking for inits.
head = first element
last = last element
tail = all except head
tails = recurses tail
init = all except last
inits = recurses init
See the descriptions under trait Traversable in the Collections API.