Reputation: 4708
In many programming languages there is a combined operation that returns both the quotient and the remainder of a division as integers. In a lot of cases it is called divmod
because it serves both the purposes of the division and the modulo function in one step.
I suppose the intention of having one operation is, that the division calculation doesn't need to be executed twice and that the results don't need to be represented as potentially lossy floating point values.
Is there such a combined function in Elixir? I can only find div
and rem
separately.
Upvotes: 5
Views: 2238
Reputation: 2952
@doc """
## Parameters
number - any integer/float
divisor - what to divide by
## Returns
{quotient, remainder}
## Example
iex(6)> Data.divmod(12, 2)
{6, 0}
iex(7)> Data.divmod(12, 3)
{4, 0}
iex(8)> Data.divmod(12, 4)
{3, 0}
iex(9)> Data.divmod(12, 4.5)
{2, 3.0}
"""
def divmod(number, divisor) do
result = number / divisor
quotient = result |> Kernel.floor
remainder = number - (quotient * divisor)
{quotient, remainder}
end
Upvotes: 0
Reputation: 121010
There is none is the language core library, but you might easily construct it yourself:
divmod =
fn e, d ->
~w|div rem|a
|> Enum.map(&apply(Kernel, &1, [e, d]))
|> List.to_tuple()
end
#⇒ #Function<12.99386804/2 in :erl_eval.expr/5>
divmod.(5, 2)
#⇒ {2, 1}
There are two possible reasons why it’s not presented in the standard library: a) Elixir
ideology is to provide a scaffold, not the swiss-knife-framework and b) Erlang
is not actually the best choice for doing math.
Upvotes: 4