Tropical algebra overloading: Difference between revisions

Line 257:
5 ⊗ (8 ⊕ 7) == 5 ⊗ 8 ⊕ 5 ⊗ 7 = true
</pre>
 
=={{header|Nim}}==
We could define ⊕ and ⊗ as procedures but would have to use <code>⊕(a, b)</code> and <code>⊗(a, b)</code> instead of the more natural <code>a ⊕ b</code> and <code>a ⊗ b</code>. We preferred to define a type MaxTropical distinct of float. In Nim, it is possible to borrow operations from the parent type, which we did for operator `<=` (required by the standard max function) and for the function `$` to convert a value to its string representation. The ⊕ operator is then defined by overloading of the `+` operator and the ⊗ operator by overloading of the `*` operator.
 
We also defined the -Inf value as a constant, MinusInfinity.
 
<lang Nim>import strformat
 
type MaxTropical = distinct float
 
const MinusInfinity = MaxTropical NegInf
 
# Borrowed functions.
func `<=`(a, b: MaxTropical): bool {.borrow.} # required by "max".
func `$`(a: MaxTropical): string {.borrow.}
 
# ⊕ operator.
func `+`(a, b: MaxTropical): MaxTropical = max(a, b)
 
# ⊗ operator.
func `*`(a, b: MaxTropical): MaxTropical = MaxTropical float(a) + float(b)
 
# ⊗= operator, used here for exponentiation.
func `*=`(a: var MaxTropical; b: MaxTropical) =
float(a) += float(b)
 
# ↑ operator (this can be seen as an overloading of the ^ operator from math module).
func `^`(a: MaxTropical; b: Positive): MaxTropical =
case b
of 1: return a
of 2: return a * a
of 3: return a * a * a
else:
result = a
for n in 2..b:
result *= a
 
 
echo &"2 ⊗ -2 = {MaxTropical(2) * MaxTropical(-2)}"
echo &"-0.001 ⊕ -Inf = {MaxTropical(-0.001) + MinusInfinity}"
echo &"0 ⊗ -Inf = {MaxTropical(0) * MinusInfinity}"
echo &"1.5 ⊕ -1 = {MaxTropical(1.5) + MaxTropical(-1)}"
echo &"-0.5 ⊗ 0 = {MaxTropical(-0.5) * MaxTropical(0)}"
echo &"5↑7 = {MaxTropical(5)^7}"
let x = 5 * (8 + 7)
let y = 5 * 8 + 5 * 7
echo &"5 ⊗ (8 ⊕ 7) equals 5 ⊗ 8 ⊕ 5 ⊗ 7 is {x == y}"</lang>
 
{{out}}
<pre>2 ⊗ -2 = 0.0
-0.001 ⊕ -Inf = -0.001
0 ⊗ -Inf = -inf
1.5 ⊕ -1 = 1.5
-0.5 ⊗ 0 = -0.5
5↑7 = 35.0
5 ⊗ (8 ⊕ 7) equals 5 ⊗ 8 ⊕ 5 ⊗ 7 is true</pre>
 
=={{header|Phix}}==
Anonymous user