简体   繁体   中英

Operator or method for turning a Scala stream into a stream of streams (suffixes of given stream)

The problem is simple: Convert a stream of elements into a stream of streams of those elements where the first element is the original stream, the second is the tail of the original stream, the third is the tail of the tail, and so on...

Example: (1, 2, 3, ...) becomes ((1, 2, 3, ...), (2, 3, 4, ...), (3, 4, 5, ...), ...)

My question is not exactly how to obtain this stream, because it's simple, but whether there is already a method or an operator that does this in an idiomatic way. In case there is no such method, I'm also looking for an adequate name for this operation. I feel that expand or unfold doesn't really nail it but something along these lines.

Update: The background is that I have a function of type Stream[A] => B and I want map it on a stream of all the suffixes of the input stream. Therefore it seems practicable to convert the stream to a Stream[Stream[A]] first in order to map over it. I need a proper name for it because this seems to be a recurring pattern in my code.

I finally found the answer myself: .tails does exactly what I'm looking for. From the docs:

Iterates over the tails of this sequence. The first value will be this sequence and the final one will be an empty sequence, with the intervening values the results of successive applications of tail.

returns: an iterator over all the tails of this sequence

The iterator can then be trivially turned into a stream if needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM