DownValues
[symbol] DownValues
uses HoldPattern
and RuleDelayed
to protect the downvalues from being evaluated, and it has attribute HoldAll
to get the specified symbol instead of its value.
f[x_] := x ^ 2
DownValues[f]
Mathics will sort the rules you assign to a symbol according to their specificity. If it cannot decide which rule is more special, the newer one will get higher precedence.
f[x_Integer] := 2
f[x_Real] := 3
DownValues[f]
f[3]
f[3.]
f[a]
The default order of patterns can be computed using Sort
with PatternsOrderedQ
:
Sort[{x_, x_Integer}, PatternsOrderedQ]
By assigning values to DownValues
, you can override the default ordering:
DownValues[g] := {g[x_] :> x ^ 2, g[x_Integer] :> x}
g[2]
Fibonacci numbers:
DownValues[fib] := {fib[0] -> 0, fib[1] -> 1, fib[n_] :> fib[n - 1] + fib[n - 2]}
fib[5]