Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I take the last n elements of a list

Tags:

To obtain the last n elements of a list xs, I can use reverse (take n (reverse xs)), but that is not very good code (it keeps the complete list in memory before returning anything, and the result is not shared with the original list).

How do I implement this lastR function in Haskell?

like image 857
Joachim Breitner Avatar asked Jun 22 '13 16:06

Joachim Breitner


People also ask

How do you pop the last n elements from a list in Python?

Python3. Method 3: Using pop() method: the pop() method will remove the last element from the list, So to remove last k elements from the python list, we need to perform the pop() operation k times.

How do I get the last 3 elements of a list in Python?

To get the last element of the list in Python, use the list[-1] syntax. The list[-n] syntax gets the nth-to-last element. So list[-1] gets the last element, and list[-2] gets the second to last. The list[-1] is the most preferable, shortest, and Pythonic way to get the last element.

How do you slice the last 5 elements of a list in Python?

Method #2 : Using islice() + reversed() The inbuilt functions can also be used to perform this particular task. The islice function can be used to get the sliced list and reversed function is used to get the elements from rear end.


1 Answers

This should have the property of only iterating the length of the list once. N for drop n and n - 1 for zipLeftover.

zipLeftover :: [a] -> [a] -> [a] zipLeftover []     []     = [] zipLeftover xs     []     = xs zipLeftover []     ys     = ys zipLeftover (x:xs) (y:ys) = zipLeftover xs ys  lastN :: Int -> [a] -> [a] lastN n xs = zipLeftover (drop n xs) xs 

Here is an alternative shorter and perhaps better since as Satvik pointed out it is often better to use recursion operators then explicit recursion.

import Data.Foldable  takeLeftover :: [a] -> t -> [a] takeLeftover [] _ = [] takeLeftover (x:xss) _ = xss  lastN' :: Int -> [a] -> [a] lastN' n xs = foldl' takeLeftover xs (drop n xs) 

Also note Will Ness's comment below that takeLeftover is just:

takeLeftover == const . drop 1 

Which makes things rather tidy:

lastN' :: Int -> [a] -> [a] lastN' n xs = foldl' (const . drop 1) xs (drop n xs) -- or -- lastN' n xs = foldl' (const . drop 1) <*> drop n 
like image 185
Davorak Avatar answered Sep 25 '22 04:09

Davorak