rgbds
rgbds copied to clipboard
[Feature request] More built-in math functions (MIN, MAX, ABS/SGN)
- [ ]
MIN(args...)= the minimum one of args (must be at least one) - [ ]
MAX(args...)= the maximum one of args (must be at least one) - [ ]
SGN(N)= 1, 0, or -1, depending on the sign of N - ~~
ABS(N)= the absolute value of N~~ (this is equivalent toN * SGN(N))
I frequently write conditionals like these:
; N = min(..., 42)
N = ...
if N > 42
N = 42
endc
; N = max(..., 0)
N = ...
if N < 0
N = 0
endc
; N = abs(...)
N = ...
if N < 0
N = -N
endc
; X = sgn(N)
X = 0
if N > 0
X = 1
elif N < 0
X = -1
endc
; now use X as a factor in further calculations
In theory, user-defined functions will eventually allow these. However, built-in functions would not have to wait for that, and would reserve an obvious name for them. Even after user-defined functions are implemented, MIN and MAX would be difficult to define like this without vararg, recursion, overloading, and ternary support.
def min(a) = a
def min(a, b) = a < b ? a : b
def min(a, b, ...) = min(min(a, b), ...)
def max(a) = a
def max(a, b) = a > b ? a : b
def max(a, b, ...) = max(max(a, b), ...)
def sgn(n) = n > 0 ? 1 : n < 0 ? -1 : 0
def abs(n) = n * sgn(n)
def abs(n) = n > 0 ? n : -n
def sgn(n) = n != 0 ? n / abs(n) : 0
Since there is a user-defined alternative, why make them built-in? If they're found to be used really often and to be performance hits, then we'll consider making them built-in. (We should suggest in the docs to only define them if not already defined, for future-proofing)
IF !DEF(min)
def min(a) = a
; ...
ENDC
While we're at this, how should function names be standardized?
There will be a user-defined alternative eventually, assuming varargs, recursion, overloading, and the ternary operator are all implemented. Until then, you still have to do if X < 42 \ X = 42 \ endc. I've seen enough such greater/less-than checks that I think MIN+MAX would be worthwhile, to write one line instead of three.
For standardized function names, so far it seems like rgbasm has gone with the typical or straightforward names for built-in functions (SIN, ATAN2, BANK, etc), with a convention of STR-prefixing all string-related functions.
All the built-in functions so far are for operations that would be difficult or impossible to do with the available integer operators; in particular the fixed-point math and trigonometry functions. There are a lot of useful small functions on integers, and it's probably simplest to leave those for user-defined (once that's possible).