Haskell arrays vs lists

前端 未结 3 1698
情歌与酒
情歌与酒 2021-01-01 15:35

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. S

3条回答
  •  不思量自难忘°
    2021-01-01 16:40

    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.

提交回复
热议问题