haskell prelude
François Sarradin
fsarradin at gmail.com
Fri Jun 22 13:37:41 PDT 2012
Here is a copy of source code I have written once to produce fib numbers as
an infinite stream. It uses an Iterator (as Brian has proposed).
@Test
public void shouldGetFibonacciNumbersAsInfiniteStream() {
Iterator<Integer> fibIterator = new AbstractIterator<Integer>() {
int a = 1;
int b = 0;
@Override
protected Integer computeNext() {
Integer result = b;
b = a + b;
a = result;
return result;
}
*
*
};
assertThat(limit(fibIterator, 8)).containsOnly(0, 1, 1, 2, 3, 5, 8, 13);
}
Note: here I have used JUnit, Fest-assert, and Guava.
I have also tempted to write an implementation based on lazy streams. This
version is compatible with Java 5+.
public Stream<Integer> fibs(final int a, final int b) {
return new Stream<Integer>(a, new Supplier<Stream<Integer>>() {
@Override
public Stream<Integer> get() {
return fibs(b, a + b);
}
});
}
@Test
public void shouldReturnFibonacciSeries() {
assertThat(limit(fibs(1, 1), 8)).containsOnly(1, 1, 2, 3, 5, 8, 13, 21);
}
You can find the implementation of *my* streams in Github:
https://github.com/fsarradin/fsarradin-utils/tree/master/src/main/java/org/kerflyn/javafp
This repo is not intended for Java 8, but to extend the functionalities of
Guava with Java version 5+.
françois-
2012/6/22 Brian Goetz <brian.goetz at oracle.com>
> In the new streams library, laziness can be handled by writing iterators
> (yes, I know they're yucky) and treating them as stream sources. So it
> is fairly easy to create a stream source for infinite sequences,
> transform with filter/map/flatMap, and consume the bits you want as if
> they were iterators.
>
> On 6/21/2012 9:33 AM, Luc Duponcheel wrote:
> > Some time ago Sven Eric Panitz posted an experimental haskell prelude
> > library to this group (one of his goals being to work with "infinite
> > iterables" (right?))
> >
> >
> > So I tried out something similar to
> >
> > public class Test{
> > final private static Function2<Integer, Integer, Iterable<Integer>>
> fibs =
> > (Integer z, Integer y) -> cons(z, cons(y, fibs.eval(y, z + y)));
> > public static void main(String[] args){
> > System.out.println(take(5, fibs.eval(1, 1)));
> > }
> > }
> >
> > but this results in a stack overflow
> >
> > So my question to Sven (and others (?)) is:
> > is there an elegant similar way to define fibs without this issue?
> >
> >
> > thx
> >
> > Luc
> >
>
>
More information about the lambda-dev
mailing list