I believe you're looking for init.
How to return the first n-1 elements of a list of length n in Haskell?
Вопрос
I know about the tail function that returns the last n-1 elements of a list (where n is the length of the list), so I defined my own "cotail" function to return the first n-1 elements:
cotail = (reverse . tail . reverse)
Is this the best way, or is there a builtin function or a cleverer way to achieve this?
Решение 2
Другие советы
As the others have said, init
is what you're looking for. But here is how you can answer questions of the form "Is there a Haskell function to do X?" in general:
Figure out what the type signature of the function you want would be. In this case, we would expect the type signature to be
[a] -> [a]
.Search hoogle or hayoo. If you don't find it in one, try the other. Usually it doesn't matter much whether you get the order of the input parameters exactly right, but you may need to experiment.
Doing this search on Hayoo just now, init
shows up as the third result for me.
Use init
, as has been advised. But you need to be sure what you do with empty lists.
cotail xs = [x | x:_:_ <- tails xs]
This version of cotail
does not fail on empty lists, like drop 1
doesn't fail on empty lists (whereas tail
does)
The init function which does exactly what you need.