Every now and then I struggle with converting between different types Motoko has to offer.
Generally conversion within differently-sized instances of one type work well - say I want to convert an Int8
to an Int16
then there’s methods for that - might have to go via Int
, but it works and behaves as expected, trapping on overflow etc.
However once you start going between different types, it quickly gets hairy. Say I want to convert a Nat
to an Int
. Obviously NatN
might overflow an IntN
, so I’d fully expect to have to handle overflow. However - as far as I can tell there is simply no way to do that at all.
I like to use Nat
when a value is guaranteed to be positive, to be more semantically precise. However this then prevents me from ever using this value in a calculation where I might get a negative result.
The same goes for eg these conversions:
-
IntN
→NatN
, this is safe so really should be easy. YetIntN.abs()
returns an…IntN
. You can achieve this with a roundtrip throughInt
(NatN.fromNat(IntN.toInt().abs())
) but let’s be real, that’s insane. -
Nat
→Float
. While you can convert betweenInt64
andFloat
, the inability to get anywhere from aNat
prevents this -
Text
→ Numeric. Usually languages offer a way to parse a text-based representation of a numerical value - think Go’sstrconv
module, C’sstroto...
functions etc. As far as I am able to tell, there is no such thing in Motoko.
Am I missing information? The above is based on what I could find in the docs of the stdlib, but I might have missed it. Or am I misusing the type system? Or are these simply examples of Motoko being a very young language, still?
I must say that I enjoy many of the concepts I have encountered in Motoko - pattern matching makes for much nicer error handling than magic return values or exceptions. But its type system tends to be a hindrance as often as it is a help.