Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell arrays vs lists

Tags:

haskell

I'm playing with Haskell and Project Euler's 23rd problem. After solving it with lists I went here where I saw some array work. This solution was much faster than mine. So here's the question. When should I use arrays in Haskell? Is their performance better than lists' and in which cases?

like image 715
franza Avatar asked Nov 19 '11 19:11

franza


People also ask

Are Haskell lists immutable?

Data is immutable in Haskell. We do not mutate the existing list but build a new list from applying the function. Haskell helps us to avoid the security issue by default.

Does Haskell have array?

Although Haskell has an incremental array update operator, the main thrust of the array facility is monolithic. Arrays are not part of the Standard Prelude---the standard library contains the array operators. Any module using arrays must import the Array module.

What is an array in Haskell?

Definition of Haskell Array. In Haskell array is used to store the different values, it is immutable in nature, which means once assigned we cannot modify the original one. If we perform any operations on the array then it will always return us to the new array, only accessing elements is fine with the original one.

What is list in Haskell?

In Haskell, lists are a homogenous data structure. It stores several elements of the same type. That means that we can have a list of integers or a list of characters but we can't have a list that has a few integers and then a few characters. And now, a list!


1 Answers

The most obvious difference is the same as in other languages: arrays have O(1) lookup and lists have O(n). Attaching something to the head of a list (:) takes O(1); appending (++) takes O(n).

Arrays have some other potential advantages as well. You can have unboxed arrays, which means the entries are just stored contiguously in memory without having a pointer to each one (if I understand the concept correctly). This has several benefits--it takes less memory and could improve cache performance.

Modifying immutable arrays is difficult--you'd have to copy the entire array which takes O(n). If you're using mutable arrays, you can modify them in O(1) time, but you'd have to give up the advantages of having a purely functional solution.

Finally, lists are just much easier to work with if performance doesn't matter. For small amounts of data, I would always use a list.

like image 147
Tikhon Jelvis Avatar answered Oct 11 '22 15:10

Tikhon Jelvis