Home > other >  How to make define a segments function
How to make define a segments function

Time:03-22

How to define a function segments which takes a finite list xs as its argument and returns the list of all the segments of xs. (A segment of xs is a selection of adjacent elements of xs .)

For example, segments [1, 2, 3] = [[1, 2, 3], [1, 2], [2, 3], [1], [2], [3]].

I know how to write a inits, but how can I extend to this situation!

segments :: [a] -> [[a]]
segments [] = []
segments (x:xs) = [x:xs]    segments (init (x:xs))

CodePudding user response:

If you can write your own inits_ function (I specially add _ to the end because inits is standard function with a bit different behavior), you can write function segments by calling inits_ for all tails (I just rewrote your code of segments and rename it to inits_):

inits_ :: [a] -> [[a]]
inits_ [] = []
inits_ xs = xs : inits_ (init xs)

segments :: [a] -> [[a]]
segments [] = []
segments (x:xs) = inits_ (x:xs)    segments xs
  • Related