haskell prelude

David Conrad drconrad at gmail.com
Fri Jun 22 18:22:07 PDT 2012


On Fri, 22 Jun 2012 22:37:41 +0200, Fran?ois Sarradin <fsarradin at gmail.com
> wrote:

>
> 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);
>    }
>
>
François,

Not really an infinite sequence unless you use BigInteger, is it? :)

import java.util.Iterator;
import java.math.BigInteger;
import static java.math.BigInteger.ONE;
import static java.math.BigInteger.ZERO;

public class Fibo {
    private Fibo() {
        throw new AssertionError("no instances");
    }

    public static Iterable<BigInteger> nacci() {
        return new Iterable<BigInteger>() {
            @Override public Iterator<BigInteger> iterator() {
                return new Iterator<BigInteger>() {
                    private BigInteger a = ONE, b = ZERO;

                    @Override public boolean hasNext() { return true; }

                    @Override public BigInteger next() {
                        set(a.add(b), a); // Note 1
                        return b;
                    }

                    private void set(BigInteger a, BigInteger b) {
                        this.a = a; this.b = b;
                    }
                };
            }
        };
    }
}


import in.digo.func.Take;
import java.math.BigInteger;
import static java.math.BigInteger.ZERO;
import static java.math.BigInteger.TEN;

public class Fib {
    public static void main(String[] args) {
        BigInteger googol = TEN.pow(100);
        System.out.printf("%,d%n",
            Take.whileTrue(n -> n.compareTo(googol) <= 0, Fibo.nacci())
            .reduce(ZERO, (a, b) -> a.add(b))); // Note 2
    }
}

$ time java Fib
24,130,015,357,889,614,840,807,962,620,028,350,479,216,011,277,190,196,743,261,610,776,878,424,511,662,841,261,217,058,994,930,287,040

real    0m0.234s
user    0m0.030s
sys     0m0.061s

Sum of all terms of the Fibonacci sequence up to a googol.

Note 1: What I really want to write is a, b = a + b, a, but Java doesn't
have tuples (yet?)
Is there a bug I can vote for on that? :)

Note 2: Take.whileTrue omitted for brevity, but it does what the name
implies.

A plus, et bon weekend,
David


More information about the lambda-dev mailing list