Tropical algebra overloading: Difference between revisions

(→‎{{header|Vlang}}: Rename "Vlang" in "V (Vlang)")
Line 500:
Expecting 5 ⊗ 8 ⊕ 5 ⊗ 7 == 13. Got 13.0 ✔
</pre>
 
=={{header|jq}}==
{{works with|jq}}
 
'''Also work with gojq''' subject to the qualifications described below.
 
In this entry, jq's support for "::" in definitions is used. This
feature is not supported by gojq, so to adapt the following for gojq,
one could either modify the names, or place the definitions in a
module named `Tropical` and delete the "Tropical::" prefix within the
module itself.
 
Since the jq values for plus and minus infinity are `infinite` and
`-infinite` respectively, no special constructor for Tropical
numbers is needed.
 
Note that in the following, no checks for the validity of inputs are
included.
<syntaxhighlight lang=jq>
# ⊕ operator
def Tropical::add($other):
[., $other] | max;
 
# ⊗ operator
def Tropical::mul($other):
. + $other;
 
# Tropical exponentiation
def Tropical::exp($e):
if ($e|type) == "number" and ($e | . == floor)
then if ($e == 1) then .
else . as $in
| reduce range (2;1+$e) as $i (.; Tropical::mul($in))
end
else "Tropical::exp(\($e)): argument must be a positive integer." | error
end ;
 
# pretty print a number as a Tropical number
def pp:
if isinfinite then if . > 0 then "infinity" else "-infinity" end
else .
end;
def data: [
[2, -2, "⊗"],
[-0.001, -infinite, "⊕"],
[0, -infinite, "⊗"],
[1.5, -1, "⊕"],
[-0.5, 0, "⊗"]
];
 
def task1:
data[] as [$a, $b, $op]
| if $op == "⊕"
then "\($a|pp) ⊕ \($b|pp) = \($a | Tropical::add($b) | pp)"
else
"\($a|pp) ⊗ \($b|pp) = \($a | Tropical::mul($b) | pp)"
end;
 
def task2:
5 as $c
| "\($c|pp) ^ 7 = \($c | Tropical::exp(7) | pp)";
def task3:
5 as $c
| 8 as $d
| 7 as $e
| ($c | Tropical::mul($d) | Tropical::add($e)) as $f
| ($c | Tropical::mul($d) | Tropical::add( $c | Tropical::mul($e))) as $g
| "\($c) ⊗ (\($d) ⊕ \($e)) = \($f | pp)",
"\($c) ⊗ \($d) ⊕ \($c) ⊗ \($e) = \($g | pp)",
"\($c) ⊗ (\($d) ⊕ \($e)) == \($c) ⊗ \($d) ⊕ \($c) ⊗ \($e) is \($f == $g)" ;
 
task1, task2, task3
</syntaxhighlight>
{{output}}
See e.g. [[#Wren|Wren]].
 
=={{header|Julia}}==
2,446

edits