开发者

Haskell. Why are arrays faster than lists?

开发者 https://www.devze.com 2022-12-08 19:53 出处:网络
I am studying Haskell. I have the next question: The 开发者_JS百科List type is a basic type in Haskell.

I am studying Haskell. I have the next question:

The 开发者_JS百科List type is a basic type in Haskell. Array in Haskell is based on lists. This is the list of indices [Ix a] and function presents by table - list of pairs [(Ix a,Value)]. Why is Array faster than lists, if inside it use lists?


I am afraid you're wrong.

There're several implementations of arrays in Haskell, but as far as I understand, all of them are implemented on top of contiguous memory arrays. Because of this there's a possibility of O(1) access to element for reading.

Similarity between arrays and lists exists only on operation set level.


Arrays are not based on lists, they are implemented similarly to other programming languages, with a continuous memory area.

The most common way to create them, the array function takes a list of index, value pairs as an argument and when you print them they are shown like such a list as well. This is because arrays in Haskell can be indexed not just by integers but by anything that implements the Ix typeclass, for example (Int, Int)-pairs, Booleans, Char's and many other versions. So the [(index, value)] representation is really the only sensible, consistent way to display an array as general as the ones in Haskell.


Arrays are not based on lists. Lists are a regular, recursive data type:

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

While the various array libraries, such as uvector, array, vector, carray, hmatrix, use low level read and write operations to present an interface to arrays. There's no similarity, other than that both data structures can represent sequences, though with different complexity.

0

精彩评论

暂无评论...
验证码 换一张
取 消