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