Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell List functions

Tags:

haskell

I was wondering why in Haskell there are not symmetry in some function names:

For example:

  • head : get the first element

  • last : get the last element

Is there good reason why for example head function was not named first, or the other way around - last function could be named end or something similar.


1 Answers

Haskell's function has two couples of list functions:

  1. head :: [a] -> a, and tail :: [a] -> [a]; and
  2. init :: [a] -> [a] and last :: [a] -> a.

Learn You a Haskell for the Greater Good made a nice illustration about this:

enter image description here

The head thus is the first element of the list, whereas the tail is the list that contains the remaining elements.

The init takes all the elements except the last one, and last thus takes the last element.

A list in Haskell is a conceptually a linked list. Usually random access is not very common in list processing. Usually most list processing functions take a list and processes this like a stream of items.

It is common nomenclature of linked lists [wiki] to specify:

The head of a list is its first node. The tail of a list may refer either to the rest of the list after the head, or to the last node in the list. In Lisp and some derived languages, the next node may be called the cdr (pronounced could-er) of the list, while the payload of the head node may be called the car.

like image 141
Willem Van Onsem Avatar answered May 08 '26 02:05

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!