Elixir中是否存在divmod函数?单次返回除法商与余数
Great question! You’re absolutely right that Elixir’s standard library doesn’t ship with a built-in divmod function that returns both quotient and remainder in one go—right now, you’re limited to using the separate div/2 (for integer division) and rem/2 (for remainder) functions individually.
Why no built-in divmod?
Elixir’s design philosophy leans toward small, single-responsibility functions, and the core team has opted to keep division and remainder operations separate. Plus, since div/2 and rem/2 are both optimized and fast, there’s rarely a performance hit from calling them sequentially if you need both values.
Creating your own divmod function
If you want the convenience of a combined function, it’s trivial to implement one yourself that wraps the standard library functions:
defmodule MyMath do def divmod(a, b) do {div(a, b), rem(a, b)} end end
This function will behave exactly like the separate div/2 and rem/2 calls, following Elixir’s rules (for example, the remainder will have the same sign as the dividend):
MyMath.divmod(10, 3) # => {3, 1} MyMath.divmod(-10, 3) # => {-4, 2} MyMath.divmod(10, -3) # => {-4, -1}
You can drop this into a utility module in your project and use it whenever you need both values at once.
内容的提问来源于stack exchange,提问作者aef

