λ Tony's Blog λ

Project Euler Problem 2 Functional Java

Posted on October 3, 2008

Project Euler Problem 2 using Functional Java:

import fj.data.Stream;
import fj.P1;
import fj.F2;
import static fj.function.Integers.even;
import static fj.pre.Ord.intOrd;
import static fj.pre.Monoid.intAdditionMonoid;
import static fj.data.Stream.cons;
import static fj.Function.curry;

...

Stream<integer> fibs = new F2<Integer, Integer, Stream<integer>>() {
  public Stream<integer> f(final Integer a, final Integer b) {
    return cons(a, P1.curry(curry(this).f(b)).f(a + b));
  }
}.f(1, 2);

final int problem2 = intAdditionMonoid.sumLeft(fibs.takeWhile(intOrd.isLessThan(1000001)).filter(even).toList());