# Test math.cem standard library
# Include math functions (inline for now - no module system yet)
# Absolute value
: abs ( Int -- Int )
dup 0 i.< if
0 swap i.subtract
then
;
# Maximum of two values
: max ( Int Int -- Int )
2dup i.> if
drop
else
nip
then
;
# Minimum of two values
: min ( Int Int -- Int )
2dup i.< if
drop
else
nip
then
;
# Modulo operation
: mod ( Int Int -- Int )
2dup
i.divide
i.multiply
i.subtract
;
# GCD using Euclidean algorithm
: gcd ( Int Int -- Int )
dup 0 i.= if
drop
else
2dup mod
rot drop
gcd
then
;
# Power (base^exp)
: pow ( Int Int -- Int )
dup 0 i.= if
drop drop 1
else
dup 1 i.= if
drop
else
over
swap 1 i.subtract
pow
i.multiply
then
then
;
# Sign function
: sign ( Int -- Int )
dup 0 i.= if
drop 0
else
dup 0 i.< if
drop 0 1 i.subtract
else
drop 1
then
then
;
# Tests
: main ( -- )
5 abs 5 i.= if "abs(5) = 5 ✓" io.write-line else "abs(5) FAILED" io.write-line then
0 5 i.subtract abs 5 i.= if "abs(-5) = 5 ✓" io.write-line else "abs(-5) FAILED" io.write-line then
3 7 max 7 i.= if "max(3,7) = 7 ✓" io.write-line else "max(3,7) FAILED" io.write-line then
9 2 max 9 i.= if "max(9,2) = 9 ✓" io.write-line else "max(9,2) FAILED" io.write-line then
3 7 min 3 i.= if "min(3,7) = 3 ✓" io.write-line else "min(3,7) FAILED" io.write-line then
9 2 min 2 i.= if "min(9,2) = 2 ✓" io.write-line else "min(9,2) FAILED" io.write-line then
48 18 gcd 6 i.= if "gcd(48,18) = 6 ✓" io.write-line else "gcd(48,18) FAILED" io.write-line then
100 35 gcd 5 i.= if "gcd(100,35) = 5 ✓" io.write-line else "gcd(100,35) FAILED" io.write-line then
2 0 pow 1 i.= if "pow(2,0) = 1 ✓" io.write-line else "pow(2,0) FAILED" io.write-line then
2 3 pow 8 i.= if "pow(2,3) = 8 ✓" io.write-line else "pow(2,3) FAILED" io.write-line then
5 2 pow 25 i.= if "pow(5,2) = 25 ✓" io.write-line else "pow(5,2) FAILED" io.write-line then
0 5 i.subtract sign 0 1 i.subtract i.= if "sign(-5) = -1 ✓" io.write-line else "sign(-5) FAILED" io.write-line then
0 sign 0 i.= if "sign(0) = 0 ✓" io.write-line else "sign(0) FAILED" io.write-line then
5 sign 1 i.= if "sign(5) = 1 ✓" io.write-line else "sign(5) FAILED" io.write-line then
;