简体   繁体   English

在 Mathematica 中通过引用传递列表元素

[英]Pass list element by reference in Mathematica

I am working with this data structure which I call an "associationList", which has the following format:我正在使用这个我称之为“associationList”的数据结构,它具有以下格式:

<| key1->{value1, value2,...}, key2->{value1,value2,...},...|>

I want to have the function Add[assocList_,key_,value_] add key->{value} to the associationList by reference.我想让函数Add[assocList_,key_,value_]通过引用将key->{value}到 associationList 中。 I have the following code:我有以下代码:

Add[assoc_, key_, elt_] :=
  If[Head@assoc[key] === Missing,
   AppendTo[assoc, key -> {elt}],
   AppendTo[assoc[key], elt]];
SetAttributes[AddToAssocList, HoldFirst];

The Add function works for this example: Add 函数适用于此示例:

y=<||>;
Add[y,1,a];
(* y is <|1->{a}|> *)
Add[y,1,b];
(* y is <|1->{a,b}|> *)

But when I change the example to the following, I get an error:但是当我将示例更改为以下内容时,出现错误:

y={<||>};
Add[y[[1]],1,a];
(* y is <|1->{a}|> *)
Add[y[[1]],1,b];
(* Error - Association - "<|1->{a}|> in the part assignment is not a symbol" *)

Using any type of Hold doesn't seem to help.使用任何类型的 Hold 似乎都无济于事。 Any ideas?有任何想法吗?

The answer is to change assoc[key] in Add to assoc[[ Key[key] ]] .答案是在 Add to assoc[[ Key[key] ]]更改assoc[key] assoc[[ Key[key] ]] This works because assoc[key] gives an association, while assoc[[ Key[key] ]] gives a reference to the association.这是有效的,因为assoc[key]给出了一个关联,而assoc[[ Key[key] ]]给出了对关联的引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM