Add Integer.ceil_div function
#14913
Merged
+57
−0
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Implements
Integer.ceil_div, which complementsInteger.floor_divby rounding towards positive infinity when the quotient would not be an integer.Rationale for this function
Ceiling division is quite useful for chunking up data. For instance, if you want to split data into chunks of 1024, then
Integer.ceil_div(data_size, 1024)will tell you the number of chunks that will result. Or, if you want to split a list into no more than eight chunks of similar size, you can doInteger.ceil_div(length(list), 8)to get such a chunk size.As further justification, both of these chunking use-cases happen to be present in an Elixir codebase I work in. They're currently implemented as
ceil(a / b), but a pure integer version of this operation (keeping it immune to any floating-point weirdness) would be more apropos in my opinion.As a last point, it seems enough people have asked about this in other languages to make it seem a widely useful feature beyond the situations I myself have experienced.
So if the rationale seems convincing enough for this to be in the standard library, here's a PR :)
I also expanded the unit tests for
Integer.floor_divandInteger.modto cover a few more cases with different operand signs.