haskellnoob
haskellnoob

Reputation: 211

Give out suffixes (Haskell)

I mean: Input: suffixes ["Hello"] Output: ['ello','llo','lo','o'] or something.. The beginning is:

> suffixes :: [a] -> [[a]]
> suffixes [] = []

I think it is a little bit like

> drop (n+1) (x:xs) = drop n xs
> drop _ xs = xs

But here I want to omit always the first element of the "surviving" list. How to start? Maybe

> suffixes as = [as!!2:xs] 

or similar?

Upvotes: 0

Views: 1074

Answers (2)

Lee
Lee

Reputation: 144176

Data.List.tails can be used to get the list of all suffixes of another list, and you can use drop 1 to drop the first element of the output list:

import Data.List
suffixes = drop 1 . tails

If you want the prefixes you can use Data.List.inits. Note this returns prefixes in increasing order or length, while tails returns suffixes in decreasing length order.

Upvotes: 4

Aaron Cronin
Aaron Cronin

Reputation: 2103

tails from Data.List will do what you want.

tails "hello"
--["hello", "ello", "llo", "lo", "o", ""]--

It seems like you don't want the first element so you can drop 1.

Upvotes: 5

Related Questions