Last week I needed to write a piece of configuration where a container was assigned a certain amount of memory and a couple of configuration keys for the process running insideit were set as shares of the available memory. In other words, container has memory
X and process has a key set to
X / N and another which is
X / M.
In order to get to this I implemented integer division using
fold and asked on StackOverflow (link) whether my solution made sense or not.
Two nice outcomes were a very nice alternative solution and an interesting point raised by @Gabriel439 to implement integer division as a built-in.
This requires some discussion of course, firstly regarding whether you do see a need for this to be in the language and, if there are no objections, on how to deal with division by zero.
Unless we want to further discuss the introduction of a type which is all non-zero
Naturals, I see three possible designs (in pseudo-Haskell):
- Return an
Optional Naturalwhich is
Nothingwhen dividing by 0 and
Justthe integer division of the two dividends in other cases
quotient :: Natural -> Natural -> Optional Natural quotient n 0 = Nothing quotient n m = Just (div n m)
- Return 0 when dividing by 0
quotient :: Natural -> Natural -> Natural quotient n 0 = 0 quotient n m = div n m
- Return the numerator when dividing by 0
quotient :: Natural -> Natural -> Natural quotient n 0 = n quotient n m = div n m
The third was actually just the result of my first attempt at implementing the function. I don’t think it’s a good design in general but it didn’t look completely off in my specific case (do you want to know how many shares empty shares of memory in the container? All of them, buddy!) so I thought it was worth mentioning.
The first one is very explicit about the values on which the operation is defined, but I’m afraid it can become a bit unwieldy to manage. Users would end up writing boilerplate code to define a default value.
The second one doesn’t make much sense mathematically, but if well documented is probably the conservative choice to make.
Adopting 1. and 2. as separate available choices is another possibility (calling them, for example,