Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A question concerning list accesses from a noobie functional programmer

This might be a silly and obvious question, but why are list access algorithm examples implemented in linear time? I understand that most applications involve traversing lists rather than accessing them randomly, but what if you want to perform an access on a list with random accesses?

like image 979
alexgolec Avatar asked May 14 '11 06:05

alexgolec


2 Answers

Because lists are by design a linear structure. They are the canonical recursive data type, defined as:

 data [a] = [] | a : [a]

That is, either the empty list, or a cons node, consisting of an element, and a tail, which is also a list.

This structure precisely corresponds to inductive definitions in mathematics, and correspondingly, makes it trivial to write many functions as simple recursive calls.

The recursive data type does not admit random access in non-linear time, however. For that you need hardware support (which we all have), and a more sophisticated data type (or less sophisticated, depending on your viewpoint).

Summary: lists are computer science's encoding of induction as a recursive data structure. It's fundamental, you need it, but it doesn't do random access.

like image 184
Don Stewart Avatar answered Oct 20 '22 06:10

Don Stewart


Haskell lists correspond to linked lists in imperative languages; they are inherently sequential since you only have access to the head and need to traverse to find other elements.

If you want random access you should choose some other data type. Perhaps from Data.Array or Data.IntMap.

like image 35
augustss Avatar answered Oct 20 '22 07:10

augustss