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!
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 .
items. pop_back(); Removes last element from items, without returning anything.
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.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With