Created
August 25, 2010 01:12
-
-
Save psfblair/548640 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| (* Each new term in the Fibonacci sequence is generated by adding the previous two terms. | |
| By starting with 1 and 2, the first 10 terms will be: | |
| 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... | |
| Find the sum of all the even-valued terms in the sequence which do not exceed four million. *) | |
| #light | |
| let fibonacci = fun(x: int, y: int) -> Some( x, (y, x+y) ) | |
| let sequence = Seq.unfold fibonacci <| (1,2) //I like having the tuple at the end better than at the beginning. | |
| let evenFibsUnder4Million = seq {for x in (Seq.takeWhile (fun(x) -> x < 4000000) sequence) do | |
| if x % 2 = 0 then yield x } | |
| let answer = Seq.fold (+) 0 evenFibsUnder4Million | |
| // More compact | |
| let fibonaccis = Seq.unfold( fun(x, y) -> Some( x, (y, x+y)) ) <| (1,2) | |
| let evenFibsUnder4Million = seq {for x in (Seq.takeWhile (fun(x) -> x < 4000000) fibonaccis) do | |
| if x % 2 = 0 then yield x } | |
| let answer = Seq.fold (+) 0 evenFibsUnder4Million | |
| // Or even | |
| let fibonaccis = Seq.unfold( fun(x, y) -> Some( x, (y, x+y)) ) <| (1,2) | |
| let answer = seq {for x in (Seq.takeWhile (fun(x) -> x < 4000000) fibonaccis) do | |
| if x % 2 = 0 then yield x } | |
| |> Seq.fold (+) 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment