re: Project Euler #2 - Even Fibonacci numbers VIEW POST

FULL DISCUSSION
 

In Javascript using filter and reduce.

var memo = [0, 1];
function fib (n) {
    if(memo.length-1 < n) {
        memo[n] = fib(n-1)+fib(n-2);
    }
    return memo[n];
}

// creates array with elements from function that takes the index as argument while a given condition holds
function takeWhile (fromFunc, cond, arr=[]) {
    var n = arr.length;
    var val = fromFunc(n);
    if(cond(val)) {
        arr.push(val);
        return takeWhile(fromFunc, cond, arr);
    }
    return arr;
}

var sum = 
    takeWhile(fib, n => n < 4000000)
    .filter(n => n%2==0)
    .reduce((acc, c) => acc+c, 0);

console.log(sum);

Haskell:

fibo a b = a:fibo b (a+b)
isEven = (== 0) . flip mod 2

fibSumEvenUnder n = sum $ filter isEven $ takeWhile (<n) $ fibo 1 2
ans = fibSumEvenUnder 4000000
code of conduct - report abuse