1
\$\begingroup\$

I have already done many of the Project Euler questions in other languages before, but whenever learning a new language, I like to do the problems again in that language.

Here is my elixir version of

Find the sum of all Fibonacci numbers below 4,000,000.

stream = Stream.unfold({0,1}, fn {a, b} -> {a, {b, a + b}} end)
Enum.reduce_while(stream, 0, &(
 cond do
 &1 < 4000000 and rem(&1, 2) == 0 ->
 {:cont, &2 + &1}
 &1 < 4000000 ->
 {:cont, &2}
 true ->
 {:halt, &2}
 end
))

Can anyone spot a way to make my code fit the elixir paradigm more? Are there things I could improve?

Toby Speight
87.2k14 gold badges104 silver badges322 bronze badges
asked Jul 1, 2019 at 21:18
\$\endgroup\$
3
  • \$\begingroup\$ Not sure why the downvote, if this isn't the purpose of this site then what is? \$\endgroup\$ Commented Jul 1, 2019 at 21:23
  • 1
    \$\begingroup\$ Someone has voted to close it as "Unclear what you're asking". I don't see why this would be considered unclear though, and this looks very much ontopic. \$\endgroup\$ Commented Jul 1, 2019 at 21:44
  • \$\begingroup\$ Someone seems to have raised a "Unclear what you're asking" close vote. But you have added that to your question since then, so your question should be good to go. \$\endgroup\$ Commented Jul 1, 2019 at 21:45

1 Answer 1

2
\$\begingroup\$

I'd improve two things:

  • take advantage of ability to specify multiple clauses for anonymous function,
  • use underscore for big numbers to improve code readability.

My take on your code:

{0, 1}
|> Stream.unfold(fn {a, b} -> {a, {b, a + b}} end)
|> Enum.reduce_while(0, fn
 value, acc when value < 4_000_000 and rem(value, 2) == 0 -> {:cont, acc + value}
 value, acc when value < 4_000_000 -> {:cont, acc}
 _value, acc -> {:halt, acc}
end)
answered Jul 8, 2019 at 14:38
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Also, I like your use of an explicit fn over the submitters &- the latter is often hard to read and usually I will only use it for very short stuff, probably just the &function/arity construct and nothing else. \$\endgroup\$ Commented Jul 30, 2019 at 23:30

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.