문제

DownValue 규칙의 LHS를 얻기 위해 Mathematica에 내장 기능이 있는지 아는 사람이 있습니까? 코드를 작성하는 방법을 알고 있지만 내장 된 것은 기본적으로 보입니다.

예를 들어:

a[1]=2;
a[2]=3;

BuiltInIDoNotKnowOf[a] 보고 {1,2}

도움이 되었습니까?

해결책

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]

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top