Skip to content

Instantly share code, notes, and snippets.

@lemonxah
Last active August 29, 2015 14:16
Show Gist options
  • Save lemonxah/b1a46c92d2fef5c40de9 to your computer and use it in GitHub Desktop.
Save lemonxah/b1a46c92d2fef5c40de9 to your computer and use it in GitHub Desktop.
PE 2
IEnumerable<int> fib() {
var s1 = 0;
var s2 = 1;
while (true) {
var o = s1 + s2;
s1 = s2;
s2 = o;
yield return o;
}
}
// this is prettier
Func<int,bool> isEven = i => i % 2 == 0;
Func<int,bool> under4Mill = i => i < 4000000;
var sum = fib().Where(isEven).TakeWhile(under4Mill).Sum();
// this is the one liner
sum = fib().Where(i => i % 2 == 0).TakeWhile(i => i < 4000000).Sum();
Console.WriteLine(sum);
def fib: Stream[Long] = {
def tail(h: Long, n: Long): Stream[Long] = h #:: tail(n, h + n)
tail(0, 1)
}
// pretty one
def even(i: Int) = i % 2 == 0
def under4mill(i: Int) = i < 4000000
fib filter even takeWhile under4mill sum
// one liner
fib filter (_ % 2 == 0) takeWhile (_ < 4000000) sum
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment