I've been playing with java 8, and i didn't manage to write an implementation to the function zipWith (taken from haskell):
zipWith takes two streams, and a bifunction, and returns a stream which consists of the stream elements applied to the bifunction in pairs. the type signature:
<K,J,T> Stream<T> zipWith(Stream<K> s1, Stream<J> s2, BiFunction<K,J,T> f)
for example, (let's use arrays instead of streams to clarify), assuming that the function add, well, adds:
zipWith({1 ,2 ,3},
{9 ,4 ,6},add) =
{1+9,2+4,3+6} = {10,6,9}
I didn't find any way to implement this function. of course, it should be done lazily, computing the elements as they are needed, as this is the whole purpose of streams.
if there was any way to pop a value from a stream, i could implement the function this way:
public<K,J,T> Stream<T> zipWith(Stream<K> s1, Stream<J> s2, BiFunction<K,J,T> f)
{
Function<K,T> newf = (x) -> f.apply(x, s2.pop());
return s1.map(newf);
}
but as far as I know, there isn't such function.
anybody has any idea how to implement this? or maybe it's impossible?
on a side note, a potential problem with implementations can be that someone else might access the streams and push values off them. is there any way to "tell" the streams they are consumed, so that nobody else could touch them, although they aren't already consumed?