While reading the Pony Tutorial on Operations, I noticed that some infix operators have partial and unsafe versions. Coming from C#, Java, Python, and JS/TS, I haven't the faintest clue what those do.
In C# there are checked
and unchecked
contexts for arithmetic. In a checked
block, math that would result in a overflow throws an exception. Are the unsafe operators related to that?
Can someone please explain unsafe and partial operators?
The regular operators, such as
add
/+
,mod
/%%
, etc. will always return the most sensible result. This leads to certain results, such as division by zero being equal to 0. This is because these functions are mathematically considered non-partial, meaning that for every input, there is a defined output; even if the output may be unusual, like an addition that overflows having its result being smaller than the inputs.However, there are certain situations where having a clearly defined result for every input is not what the programmer wants. That's where unsafe and partial operators come in.
unsafe
version of the operators removes these guarantees, and uses a quicker CPU instruction that may give unexpected results for certain inputs. This is useful when you know that your inputs cannot reach certain conditions (eg. overflow, division by zero), and you want your code to squeeze out some extra performance. From the documented definition of theadd_unsafe
/+~
andmod_unsafe
/%%~
operators intrait Integer
¹, for example:partial
. These will raise errors that you can handle as usual. Also reading the documentation of theadd_partial
/+?
andmod_partial
/%%?
operators intrait Integer
¹, we find:¹ This trait is implemented by all integer types in Pony, both signed and unsigned.