-1

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?

Turion
  • 5,684
  • 4
  • 26
  • 42
  • 3
    BTW, "returns the last _n_ - 1 elements" is not really a great description. Generally, lengths are not a good property for lists, since they may be infinite (and even when they aren't, `length` is unnecessarily expensive because it needs to traverse the entire list). Better say simply "`tail` returns all elements except for the `head`". Likewise, `init` returns all elements except for the `last` one. – leftaroundabout Mar 27 '14 at 11:56
  • True, but it serves the purpose, i.e. everybody understands my question. – Turion Mar 27 '14 at 13:05

4 Answers4

8

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:

  1. 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].

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

mhwombat
  • 8,026
  • 28
  • 53
6

I believe you're looking for init.

fjh
  • 12,121
  • 4
  • 46
  • 46
2

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)

Sassa NF
  • 5,306
  • 15
  • 22
1

The init function which does exactly what you need.

Alethes
  • 922
  • 7
  • 9