Mathematica Downvalue Lhs - wolfram-mathematica

Does anybody know if there is a built-in function in Mathematica for getting the lhs of downvalue rules (without any holding)? I know how to write the code to do it, but it seems basic enough for a built-in
For example:
a[1]=2;
a[2]=3;
BuiltInIDoNotKnowOf[a] returns {1,2}

This is like keys() in Perl and Python and other languages that have built in support for hashes (aka dictionaries). As your example illustrates, Mathematica supports hashes without any special syntax. Just say a[1] = 2 and you have a hash. [1]
To get the keys of a hash, I recommend adding this to your init.m or your personal utilities library:
keys[f_] := DownValues[f][[All,1,1,1]] (* Keys of a hash/dictionary. *)
(Or the following pure function version is supposedly slightly faster:
keys = DownValues[#][[All,1,1,1]]&; (* Keys of a hash/dictionary. *)
)
Either way, keys[a] now returns what you want. (You can get the values of the hash with a /# keys[a].) If you want to allow for higher arity hashes, like a[1,2]=5; a[3,4]=6 then you can use this:
SetAttributes[removeHead, {HoldAll}];
removeHead[h_[args___]] := {args}
keys[f_] := removeHead ### DownValues[f][[All,1]]
Which returns {{1,2}, {3,4}}. (In that case you can get the hash values with a ### keys[a].)
Note that DownValues by default sorts the keys, which is probably not a good idea since at best it takes extra time. If you want the keys sorted you can just do Sort#keys[f]. So I would actually recommend this version:
keys = DownValues[#,Sort->False][[All,1,1,1]]&;
Interestingly, there is no mention of the Sort option in the DownValues documention. I found out about it from an old post from Daniel Lichtblau of Wolfram Research. (I confirmed that it still works in the current version (7.0) of Mathematica.)
Footnotes:
[1] What's really handy is that you can mix and match that with function definitions. Like:
fib[0] = 1;
fib[1] = 1;
fib[n_] := fib[n-1] + fib[n-2]
You can then add memoization by changing that last line to
fib[n_] := fib[n] = fib[n-1] + fib[n-2]
which says to cache the answer for all subsequent calls.

This seems to work; not sure how useful it is, though:
a[1] = 2
a[2] = 3
a[3] = 5
a[6] = 8
Part[DownValues[a], All, 1, 1, 1]

Related

Summation Elixir

I am trying to recreate this equation in Elixir:
For now I am working on an easy example and I have something like this:
Enum.each(1..2, fn x -> :math.pow(1 + 1/1, -x) end)
However, while using Enum.each I am getting an :ok output, and therefore I can't inject it later to Enum.sum()
I will be grateful for help.
While the answer by #sabiwara is perfectly correct, one’d better either use Stream.map/2 to avoid building the intermediate list that might be huge, or directly Enum.reduce/3 to the answer.
# ⇓ initial value
Enum.reduce(1..2, 0, &:math.pow(1 + 1/1, -&1) + &2)
Enum.each/2 is for side effects, but does not return a transformed list.
You are looking for Enum.map/2.
Alternatively, you could use a for comprehension:
for x <- 1..2, do: :math.pow(1 + 1/1, -x)

How do I make a function use the altered version of a list in Mathematica?

I want to make a list with its elements representing the logic map given by
x_{n+1} = a*x_n(1-x_n)
I tried the following code (which adds stuff manually instead of a For loop):
x0 = Input["Enter x0"]
a = Input["a"]
M = {x0}
L[n_] := If[n < 1, x0, a*M[[n]]*(1 - M[[n]])]
Print[L[1]]
Append[M, L[1]]
Print[M]
Append[M, L[2]]
Print[M]
The output is as follows:
0.3
2
{0.3}
0.42
{0.3,0.42}
{0.3}
Part::partw: Part 2 of {0.3`} does not exist. >>
Part::partw: Part 2 of {0.3`} does not exist. >>
{0.3, 2 (1 - {0.3}[[2]]) {0.3}[[2]]}
{0.3}
It seems that, when the function definition is being called in Append[M,L[2]], L[2] is calling M[[2]] in the older definition of M, which clearly does not exist.
How can I make L use the newer, bigger version of M?
After doing this I could use a For loop to generate the entire list up to a certain index.
P.S. I apologise for the poor formatting but I could find out how to make Latex code work here.
Other minor question: What are the allowed names for functions and lists? Are underscores allowed in names?
It looks to me as if you are trying to compute the result of
FixedPointList[a*#*(1-#)&, x0]
Note:
Building lists element-by-element, whether you use a loop or some other construct, is almost always a bad idea in Mathematica. To use the system productively you need to learn some of the basic functional constructs, of which FixedPointList is one.
I'm not providing any explanation of the function I've used, nor of the interpretation of symbols such as # and &. This is all covered in the documentation which explains matters better than I can and with which you ought to become familiar.
Mathematica allows alphanumeric (only) names and they must start with a letter. Of course, Mathematic recognises many Unicode characters other than the 26 letters in the English alphabet as alphabetic. By convention (only) intrinsic names start with an upper-case letter and your own with a lower-case.
The underscore is most definitely not allowed in Mathematica names, it has a specific and widely-used interpretation as a short form of the Blank symbol.
Oh, LaTeX formatting doesn't work hereabouts, but Mathematica code is plenty readable enough.
It seems that, when the function definition is being called in
Append[M,L2], L2 is calling M[2] in the older definition of M,
which clearly does not exist.
How can I make L use the newer, bigger version of M?
M is never getting updated here. Append does not modify the parameters you pass to it; it returns the concatenated value of the arrays.
So, the following code:
A={1,2,3}
B=Append[A,5]
Will end up with B={1,2,3,5} and A={1,2,3}. A is not modfied.
To analyse your output,
0.3 // Output of x0 = Input["Enter x0"]. Note that the assignment operator returns the the assignment value.
2 // Output of a= Input["a"]
{0.3} // Output of M = {x0}
0.42 // Output of Print[L[1]]
{0.3,0.42} // Output of Append[M, L[1]]. This is the *return value*, not the new value of M
{0.3} // Output of Print[M]
Part::partw: Part 2 of {0.3`} does not exist. >> // M has only one element, so M[[2]] doesn't make sense
Part::partw: Part 2 of {0.3`} does not exist. >> // ditto
{0.3, 2 (1 - {0.3}[[2]]) {0.3}[[2]]} (* Output of Append[M, L[2]]. Again, *not* the new value of M *)
{0.3} // Output of Print[M]
The simple fix here is to use M=Append[M, L[1]].
To do it in a single for loop:
xn=x0;
For[i = 0, i < n, i++,
M = Append[M, xn];
xn = A*xn (1 - xn)
];
A faster method would be to use NestList[a*#*(1-#)&, x0,n] as a variation of the method mentioned by Mark above.
Here, the expression a*#*(1-#)& is basically an anonymous function (# is its parameter, the & is a shorthand for enclosing it in Function[]). The NestList method takes a function as one argument and recursively applies it starting with x0, for n iterations.
Other minor question: What are the allowed names for functions and lists? Are underscores allowed in names?
No underscores, they're used for pattern matching. Otherwise a variable can contain alphabets and special characters (like theta and all), but no characters that have a meaning in mathematica (parentheses/braces/brackets, the at symbol, the hash symbol, an ampersand, a period, arithmetic symbols, underscores, etc). They may contain a dollar sign but preferably not start with one (these are usually reserved for system variables and all, though you can define a variable starting with a dollar sign without breaking anything).

Is there a more readable way to write for k, v in pairs(my_table) do ... end in lua if I never use k?

Is there a more readable way in lua to write:
for k, v in pairs(my_table) do
myfunction( v )
end
I'm never using k, so I'd like to take it out of the loop control, so it's clear I'm just iterating over the values. Is there a function like pairs() that only gives me a list of the values?
There is no standard function that only iterates values, but you can write it yourself if you wish. Here is such an iterator :
function values(t)
local k, v
return function()
k, v = next(t, k)
return v
end
end
But normally people just use pairs and discard the first variable. It is customary in this case to name the unused variable _ (an underscore) to clearly indicate the intent.
I've seen people use the _ variable instead of k or i.
why would you use the pairs() function if you don't want the key/value pairs of the table you're enumerating then?
for example, this is even shorter to type:
local t = {"asdf", "sdfg", "dfgh"}
for i=1, #t do
print(t[i])
end
otherwise, i always just did this:
local t = {"asdf", "sdfg", "dfgh"}
for _,v in pairs(t) do
print(v)
end
edit: for your scenario, where you want to enumerate only values in a table with non-numeric keys, probably the clearest thing you could do would be to write your own table iterator function like this:
local t = {["asdf"] = 1, ["sdfg"] = 2, ["dfgh"] = 3}
function values(tbl)
local key = nil
return function()
key = next(tbl, key)
return tbl[key]
end
end
for value in values(t) do
print(value)
end
then, it is very explicit that you're only traversing the values of the table t. like pairs(), this is not guaranteed to traverse in order since it uses next().
It's your coding style, really. If you can read it and you're consistent with it then it shouldn't matter.
However, I tend to use:
for i,c in
"i" standing for "index" and "c" standing for "child", but "v" for "value" works as well. And even if you're not using the index variable, it's still good practice.
Another thing you might do is:
for n = 1, 10
when dealing with numbers. But once again, it's you're coding style and as long as it's consistent you should be good.
From Lua Style Guide:
The variable consisting of only an underscore "_" is commonly used as a placeholder when you want to ignore the variable:
for _,v in ipairs(t) do print(v) end
Note: This resembles the use of "_" in Haskell, Erlang, Ocaml, and Prolog languages, where "_" takes the special meaning of anonymous (ignored) variables in pattern matches. In Lua, "_" is only a convention with no inherent special meaning though. Semantic editors that normally flag unused variables may avoid doing so for variables named "_" (e.g. LuaInspect is such a case).
So I would expect underscore (_) name is more readable for unused variables.

Possible to block OwnValues when DownValues already exist?

For cases where one has already assigned DownValues associated with the name 'a', is there an accepted way to block the assignment of OwnValues to the same name? (I originally came across this issue while playing with someone's attempt at implementing a data dictionary.)
Here's what I mean to avoid:
Remove[a];
a[1] := somethingDelayed
a[2] = somethingImmediate;
DownValues[a]
a[1]
a[2]
Returns...
{HoldPattern[a[1]] :> somethingDelayed,
HoldPattern[a[2]] :> somethingImmediate}
somethingDelayed
somethingImmediate
And now if we were to evaluate:
a = somethingThatScrewsUpHeads;
(* OwnValues[a] above stored in OwnValues *)
a[1]
a[2]
We get...
somethingThatScrewsUpHeads[1]
somethingThatScrewsUpHeads[2]
Is there an easy/flexible way to prevent OwnValues for any Name in DownValues? (Lemme guess... it's possible, but there's going to be a performance hit?)
I don't know if this is an "accepted" way, but you could define a rule that prevents Set and SetDelayed from acting upon a:
Remove[a];
a[1] := somethingDelayed
a[2] = somethingImmediate;
a /: HoldPattern[(Set|SetDelayed)[a, _]] := (Message[a::readOnly]; Abort[])
a::readOnly = "The symbol 'a' cannot be assigned a value.";
With this rule in place, any attempt to assign an OwnValue to a will fail:
In[17]:= a = somethingThatScrewsUpHeads;
During evaluation of In[17]:= a::readOnly:
The symbol 'a' cannot be assigned a value.
Out[17]= $Aborted
In[18]:= a := somethingThatScrewsUpHeads;
During evaluation of In[18]:= a::readOnly:
The symbol 'a' cannot be assigned a value.
Out[18]= $Aborted
However, this rule will still allow new DownValues for a:
In[19]:= a[3] = now;
a[4] := later
In[20]:= a[3]
Out[20]= now
In[21]:= a[4]
Out[21]= later
Performance
The rule does not seem to have an appreciable impact on the performance of Set and SetDelayed, presumably since the rule is installed as an up-value on a. I tried to verify this by executing...
Timing#Do[x = i, {i, 100000000}]
... both before and after the installation of the rule. There was no observable change in the timing. I then tried installing Set-related up-values on 10,000 generated symbols, thus:
Do[
With[{s=Unique["s"]}
, s /: HoldPattern[(Set|SetDelayed)[s, _]] :=
(Message[s::readOnly]; Abort[])
]
, {10000}]
Again, the timing did not change even with so many up-value rules in place. These results suggest that this technique is acceptable from a performance standpoint, although I would strongly advise performing performance tests within the context of your specific application.
I am not aware of any way to directly "block" OwnValues, and since Mathematica's evaluator evaluates heads before anything else (parts, application of DownValues, UpValues and SubValues, etc), this does not bring us anywhere (I discussed this problem briefly in my book).
The problem with a straightforward approach is that it will likely be based on adding DownValues to Set and SetDelayed, since it looks like they can not be overloaded via UpValues.
EDIT
As pointed by #WReach in the comments, for the case at hand UpValues can be successfully used, since we are dealing with Symbols which must be literally present in Set/SetDelayed, and therefore the tag depth 1 is sufficient. My comment is more relevant to redefining Set on some heads, and when expressions with those heads must be allowed to be stored in a variable (cases like Part assignments or custom data types distinguished by heads)
END EDIT
However, adding DownValues for Set and SetDelayed is a recipe for disaster in most cases ( this thread is very illustrative), and should be used very rarely (if at all) and with extreme care.
From the less extreme approaches, perhaps the simplest and safest, but not automatic way is to Protect the symbols after you define them. This method has a problem that you won't be able to add new or modify existing definitions, without Unprotect-ing the symbol.
Alternatively, and to automate things, you can use a number of tricks. One is to define custom assignment operators, such as
ClearAll[def];
SetAttributes[def, HoldAll];
def[(op : (Set | SetDelayed))[lhs_, rhs_]] /;
Head[Unevaluated[lhs]] =!= Symbol || DownValues[lhs] === {} :=
op[lhs, rhs]
and consistently wrap SetDelayed- and Set-based assignments in def (I chose this syntax for def - kept Set / SetDelayed inside def - to keep the syntax highlighting), and the same for Set. Here is how your example would look like:
In[26]:=
Clear[a];
def[a[1]:=somethingDelayed];
def[a[2]=somethingImmediate];
def[a=somethingThatScrewsUpHeads];
In[30]:= {a[1],a[2]}
Out[30]= {somethingDelayed,somethingImmediate}
You can then go further and write a code - processing macro, that will wrap SetDelayed- and Set-based assignments in def everywhere in your code:
SetAttributes[useDef, HoldAll];
useDef[code_] := ReleaseHold[Hold[code] /. {x : (_Set | _SetDelayed) :> def[x]}]
So, you can just wrap your piece of code in useDef, and then don't have to change that piece of code at all. For example:
In[31]:=
useDef[
Clear[a];
a[1]:=somethingDelayed;
a[2]=somethingImmediate;
a=somethingThatScrewsUpHeads;
]
In[32]:= {a[1],a[2]}
Out[32]= {somethingDelayed,somethingImmediate}
In the interactive session, you can go one step further still and set $Pre = useDef, then you won't forget to wrap your code in useDef.
EDIT
It is trivial to add diagnostic capabilities to def, by using the pattern - matcher. Here is a version that will issue a warning message in case when an assignment to a symbol with DownValues is attempted:
ClearAll[def];
SetAttributes[def, HoldAll];
def::ownval =
"An assignment to a symbol `1` with existing DownValues has been attempted";
def[(op : (Set | SetDelayed))[lhs_, rhs_]] /;
Head[Unevaluated[lhs]] =!= Symbol || DownValues[lhs] === {} := op[lhs, rhs]
def[(Set | SetDelayed)[sym_, _]] :=
Message[def::ownval, Style[HoldForm[sym], Red]];
Again, by using useDef[] (possibly with $Pre), this can be an effective debugging tool, since no changes in the original code are at all needed.

How to convert Mathematica binary dump file to list of definitions?

As the Documentation says, "DumpSave writes out definitions in a binary format that is optimized for input by Mathematica." Is there a way to convert a Mathematica binary dump file back to the list of definitions without evaluating them? Import["file.mx","HeldExpression"] does not work...
DumpSave stores values associated with the symbol, i.e. OwnValues, DownValues, UpValues, SubValues, DefaultValues, NValues, FormatValues.
All the evaluation was done in the session on Mathematica, and then DumpSave saved the result of it.
These values are stored in internal formal. Reading the MX files only creates symbols and populates them with these values by reading this internal format back, bypassing the evaluator.
Maybe you could share the problem that prompted you to ask this question.
[EDIT] Clarifying on the issue raised by Alexey. MX files save internal representation of symbol definitions. It appears that Mathematica internally keeps track of:
f[x_Real] := x^2 + 1
DumpSave[FileNameJoin[{$HomeDirectory, "Desktop", "set_delayed.mx"}],
f];
Remove[f]
f[x_Real] = x^2 + 1;
DumpSave[FileNameJoin[{$HomeDirectory, "Desktop", "set.mx"}], f];
setBytes =
Import[FileNameJoin[{$HomeDirectory, "Desktop", "set.mx"}], "Byte"];
setDelayedBytes =
Import[FileNameJoin[{$HomeDirectory, "Desktop", "set_delayed.mx"}],
"Byte"];
One can, then, use SequenceAlignment[setBytes, setDelayedBytes] to see the difference. I do not know why it is done that way, but my point stands. All the evaluation on values constructed using Set has already been done in Mathematica session before they were saved by DumpSave. When MX file is read the internal representation is read back into Mathematica sessions, and no evaluation of loaded definitions is actually performed.
You can assign Rules instead of RuleDelayed's to DownValues, which is equivalent to the immediate definitions. The right-hand side of the assignment stays unevaluated and is copied literally, so the command corresponding to
Clear[f];
f[x_Real] = x^2 + 1;
DumpSave["f.mx", f];
Clear[f];
f = a;
<< f.mx;
Definition[f]
would be
Clear[f];
f = a;
DownValues[f] := {f[x_Real] -> x^2 + 1}
Definition[f]
f = a
f[x_Real] = x^2+1
(cf. with your example of Clear[f]; f = a; f[x_Real] = x^2 + 1; Definition[f] which does not work, assigning a rule for a[x_Real] instead). This is robust to prior assignments to x as well.
Edit: It is not robust to side effects of the right-hand side, as an example in the comments below shows. To assign a downvalue avoiding any evaluation one can use the undocumented System`Private`ValueList like in the following:
Clear[f];
f := Print["f is evaluated!"];
DownValues[f] := System`Private`ValueList[f[x_Real] -> Print["definition is evaluated!"]];
(no output)
Note that the assignment got seemingly converted to delayed rules:
DownValues[f]
{HoldPattern[f[x_Real]] :> x^2 + 1}
but Definition (and Save) show that the distinction from a := has internally been kept. I don't know why DownValues don't display the truth.
To answer the original question, you would probably do best with importing the dump file and exporting the relevant symbols using Save, then, if expecting this to be loaded into a kernel tainted by prior definitions, convert the assignments into assignments to DownValues as above programatically. It might be easier to scope the variables in a private context before the export, though, which is what the system files do to prevent collisions.

Resources