Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to get the last element of a list in Haskell

What is the fastest way to get the last element of a list in Haskell. Also in next iteration, I want to remove first and last element of the list. What is the most elegant way to do it? I am trying list comprehension, but that does not look very efficient!

like image 311
Dilawar Avatar asked Sep 11 '11 07:09

Dilawar


People also ask

How do you get last element of a list in Haskell?

You can use the last function to get the last element of a list. As for how to remove the first and last elements, you could use (init .

How do you remove the last element in a list in Haskell?

items. pop_back(); Removes last element from items, without returning anything.

What is last Haskell?

The last method gets the last element of a Haskel list. A Haskell list can be of any data type, a string of letters, an array of numbers, etc.


2 Answers

You can use the last function to get the last element of a list.

As for how to remove the first and last elements, you could use (init . tail), but I don't know how efficient that is.

I think this image from Learn You A Haskell shows the list functions fairly well:

illustration of list functions

like image 190
icktoofay Avatar answered Sep 25 '22 03:09

icktoofay


last and init will do the job just fine for a one-off. However they are both O(n), so if you need to manipulate both ends of a list often, as you seem to imply, you might want to consider using Data.Sequence instead, which supports O(1) insertion and removal of items at both ends.

like image 45
hammar Avatar answered Sep 24 '22 03:09

hammar