Rather than checking the actual types, the code can just blindly do the arithmetic and for ideally if passed an object that has overloaded all the proper operators, it should simply work.
But it doesn't always "just work". Why? Because the overloadable operators is not the complete exposed interface for numbers.
What happens if I call pack? If I try using a class object instead of a scalar, it just doesn't do anything like I expected! More subtly, built-in functions like seek or subscripting will want actual scalars, and if the object can't be converted to a value in the domain of scalars when operator "0+" is triggered, then it won't work.
More subtle are various assumptions people make about numbers that might not be true for a class type.
Well, I have an idea. In my (extreme) example, I want to pack and unpack 64-bit values. Floats don't go that high, and 52 bits is probably enough for current use, but what happens when someone tries to use the code with a INT64 or BIGINT or somesuch, as might be natural to do? The code doesn't know about any of these types, but it can suppose that people might do that, in general, and watch out for it.
So, extend the interface! In its simplest form, if $x is not a scalar, it calls $x->foo() to get the job done, and the caller needs to make sure that a suitable foo is defined in the package's namespace. In Perl, it's easy to simply inject the function.
Unless these are standards for overloading that the module author simply left out, I don't really like to do that. But it illustrates the idea.
Everything I need from the parameter will be defined as functions in an adaptor object, and a hash can associate adaptors with the ref name. The user of the module can then supply the proper adaptor to go with whatever number class he's using. In this example, it may need functions for 'q' packing and hex formatting and parsing.
What do you think?
—John
In reply to Custom Number Types, Adaptors, Interfaces by John M. Dlugosz
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |