Return last n elements from lists in Haskell

Viewed 420

I'm new to Haskell and currently trying to understand pattern matching. So would it be possible to get the last 3 elements from a list like this one: [[1,2,3,4,5,6], [5,6,7,8,9], [10,11,12,13]] to return something like this [(4,5,6), (7,8,9), (11,12,13)]?

here's my code

lastElems [] = []
lastElems ((x:xs):ys) = drop (length xs - 3) xs : lastElems ys

I think it does what it supposed to do but it returns as lists in a list instead of tuples. Could anyone please give me a hint on how to tackle this?

And does this also mean that you can't use (:) with tuples? Thanks in advance.

1 Answers

drop :: Int -> [a] -> [a] takes an Int and a list [a], and returns an [a]. This also makes sense since the number is arbitrary, and thus we can not know at compile time how many elements the list will have.

We can however make use of explicit recursion to retrieve the last three elements:

last3 :: [a] -> (a, a, a)
last3 [x1, x2, x3] = (x1, x2, x3)
last3 (_:xs@(_:_:_:_)) = last3 xs

then lastElems is just a mapping of last3:

lastElems :: [[a]] -> [(a, a, a)]
lastElems = map last3

this function of course does not work for lists with less than three elements.

Related