Search code examples
haskellio-monad

Iterate over a list until the resulting list is an empty list


I'm trying to see if I can do something like this:

Say I have a list: [1, 8, 90, 100, 82]

Now, what I would like to do is something like this

print [8, 90, 100, 82]
print [90, 100, 82]
print [100, 82]
print [82]

So basically, I would like to print the remainder of the list until I get an empty list, and then stop. Is there some way I can do this in Haskell?

EDIT: I'm looking for a more general solution. For example, I'd also like to be able to produce this:

list [10, 80, 90, 82, 28]

 [70, 80, 72, 18]
 [52, 62, 54]
 [10, 2]
 [8]

Solution

  • What about exploiting the IO monad:

    func [_] = return ()
    func (_:xs) = print xs >> func xs
    

    When one calls this it results in:

    *Main> func [1, 8, 90, 100, 82]
    [8,90,100,82]
    [90,100,82]
    [100,82]
    [82]
    

    As you can read here, the return can be seen as the "no operation" operation and the binding operator>> can be seen as perform the first operation before the second operation.