3
\$\begingroup\$

I'm just starting to experiment with F# (from a C# background). I think I'm starting to get into the right way of thinking, but this code still seems pretty awkward. Is there a better (more terse) way to accoAny comments appreciated. (BTW, this is supposed to sum all even fibonacci numbers up to 4,000,000)

let rec fib x y max acc =
 let z = x + y
 if z < max then
 if z%2=0 then
 fib y z max (z + acc)
 else
 fib y z max acc
 else
 acc
let result = fib 1 2 4000000 2
printfn "%d" result
200_success
145k22 gold badges190 silver badges478 bronze badges
asked Jun 2, 2012 at 23:33
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

I think the solution reads better if you separate concerns a bit more instead of rolling it all into one mega function.

For instance, with these helper functions (that each do one—and only one—thing):

let fib =
 Seq.unfold
 (fun (cur, next) -> Some(cur, (next, cur + next)))
 (0I, 1I)
let isEven n = n % 2I = 0I

you can express the solution at a high level (almost at the level you would explain it in words!):

fib //given the set of fibonacci numbers
|> Seq.filter isEven //take those that are even
|> Seq.takeWhile (fun n -> n <= 4000000I) //not exceeding 4,000,000
|> Seq.sum //and sum them
answered Jun 4, 2012 at 16:29
\$\endgroup\$
1
  • \$\begingroup\$ Cool. I like that. I'm going to read up on Seq.unfold. \$\endgroup\$ Commented Jun 4, 2012 at 18:29

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.