I just started learning Elixir and stumbled upon this challenge over on Programming Puzzles & Code Golf. It is a well-suited task for beginners, so I chose to give it a go (to be clear, give it a go means solve it normally, not golfing it). To keep this question self-contained, here is the task – citing the linked post:
For a given positive integer \$n\$:
- Repeat the following until \$n < 10\$ (until \$n\$ contains one digit).
- Extract the last digit.
- If the extracted digit is even (including 0) multiply the rest of the integer by \$2\$ and add \$1\$ ( \$2n+1\$ ). Then go back to
step 1else move to
- Divide the rest of the integer with the extracted digit (integer / digit) and add the remainder (integer % digit), that is your new \$n\$.
For example, \$61407\$ gives \$5\$ when ran through this mechanism. I've come up with the following code:
defmodule ExtractAndDivide do def extract_and_divide(x) do if x < 10 do x else head = div x, 10 tail = rem x, 10 case rem tail, 2 do 0 -> head * 2 + 1 |> extract_and_divide 1 -> div(head, tail) + rem(head, tail) |> extract_and_divide end end end end
I'm seeking general advice, but mainly focusing on the following:
- Naming and Syntax better practices (usage of parenthesises, variable names etc.)
- Usage of
|>(pipe) in this context. Would you ever see it used the way I did it in production code? Should I switch to "normal" notation instead?
- Less verbose or more elegant way to avoid the seemingly unaesthetic
if x < 10 do x ... else ... endstructure, perhaps using
casewould be better here?
- Is recursion the way to go? Should I stick to it or are there better, equivalent methods?