문제

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

I believe you're looking for init.

다른 팁

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.

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top