rslt ← {larg} (fn ##.inverse) argt ⍝ General function inverse.
Suggested by Mike Day, operator [inverse] tries to find the (left) inverse of
its function operand with respect to its (left and) right argument(s). It does
this by trying to find an explicit inverse function using →invs←; if this fails
inverse resorts to an iterative approach using →invr←.
NB: from Dyalog V11, this operator is available as a language primitive.
Bugs:
Inverse will fail to terminate if iterative sub-function →invr← fails to termin-
ate.
Technical note:
[inverse] uses error guards to try first one approach and then the other.
inverse←{⍺←{⍵} ⍝ General function inverse.
0::'no inverse'⎕SIGNAL ⎕EN ⍝ Give up after trying an
0::⍺∘⍺⍺ invr ⍵ ⍝ _iterative method_, after trying to find an
⍺ ⍺⍺ invs ⍵ ⍝ _explicit inverse function_.
}
Note that [inverse] is amenable to being extended with any number of techniques,
so long as each knows when to give up and signal to give the next method a shot:
inverse←{⍺←{⍵} ⍝ General function inverse.
0::'no inverse'⎕SIGNAL ⎕EN ⍝ Give up after trying in reverse order:
0::⍺∘⍺⍺ invr ⍵ ⍝ _iterative method_
0::⍺ ⍺⍺ invs ⍵ ⍝ _explicit inverse function_.
0::⍺∘⍺⍺ invt ⍵ ⍝ ...
0::⍺ ⍺⍺ invu ⍵ ⍝ ...
'start'⎕signal 99 ⍝ start searching for inverse.
}
Examples:
⌽invs'abc' ⍝ →invs← finds inverse of ⌽
cba
⌽invr'abc' ⍝ but →invr← fails.
no inverse
⌽invr'abc'
^
{2+⍵}invr 10 ⍝ →invr← finds inverse of {2+⍵}
8
{2+⍵}invs 10 ⍝ but →invs← fails (because it's a dfn).
no inverse
{2+⍵}invs 10
^
⌽ inverse'abc' ⍝ [inverse] succeeds,
cba
{2+⍵}inverse 10 ⍝ with both functions.
8
⍝ [dual] is an operator that applies its left operand between
⍝ an application and inverse application of its right operand.
dual←{⍵⍵ inverse ⍺⍺ ⍵⍵ ⍵} ⍝ aka "under".
mean←{(+/⍵)÷⍴⍵}∘, ⍝ Arithmetic mean function.
mean 1 2 3 4 5
3
geom←mean dual⍟ ⍝ Geometric mean.
geom 1 2 3 4 5
2.6052
harm←mean dual÷ ⍝ Harmonic mean.
harm 1 2 3 4 5
2.1898
rms←mean dual(*∘2) ⍝ Root mean square.
rms 1 2 3 4 5
3.3166
pres←+/dual÷ ⍝ Parallel electrical resistance.
pres 1 2 3 4 5
0.43796
intg←{⌊0.5+⍵} ⍝ nearest integer.
rnd2←intg dual(×∘100) ⍝ round to 2 decimal places (SL).
rnd2 1 2÷3
0.33 0.67
rnda←{intg dual(×∘(10*⍺))⍵} ⍝ round to ⍺ decimal places (SL).
4 rnda 1 2÷3
0.3333 0.6667
⍝ Operator →pow← could be extended for negative powers:
pow←{ ⍝ Explicit function power.
⍺<0:(-⍺)⍺⍺ invs ∇∇ ⍵ ⍝ -ive power:
↑{⍵}∘⍺⍺/(⍳⍺),⊂⍵ ⍝ +ive power:
}
4 (1∘+)pow 10 ⍝ fourth successor of 10.
14
¯4 (1∘+)pow 10 ⍝ fourth predecessor of 10.
6
3 +\pow 1 2 3 4 5 ⍝ +ive power.
1 5 15 35 70
¯3 +\pow 1 5 15 35 70 ⍝ -ive power.
1 2 3 4 5
See also: invs invr pow
Back to: contents
Back to: Workspaces
Trouble seeing APL font?