Struct data type in Mathematica?

此生再无相见时 提交于 2019-11-30 17:27:20
sakra

Update: Mathematica 10 has introduced Association, which has many of the most important properties of a struct. (See new answer.) The original, somewhat deprecated version of this answer is below.


You can use a Mathematica rule lists to mimic a C-like struct data type. E.g.,:

person = {firstName -> "John", lastName -> "Doe"}

You can then access the record's fields by using the /. operator:

firstName /. person

yields John.

lastName /. person

yields Doe.

To update a field of a record, prepend the updated field to the list:

PrependTo[person , firstName -> "Jane"]

firstName /. person then yields Jane.

Also see the Mathematica documentation on transformation rules.

If I understand your question correctly, you can simply write things like this:

x[foo] = bar
x[bar] = baz
x[1] = 7
x[7] = 1
?x

Then to access the data for any specific index just type the same (e.g., x[1] will return 7, x[foo] will return bar).

Jess Riedel

Mathematica 10 has introduced Association, which has many of the most important properties of a struct.

someData = <| "name" -> "Bob", "age" -> 23 |>

In[1]:= someData["name"]
Out[1]= Bob

In[2]:= someData["age"]
Out[2]= 23

In[3]:= someData[[2]]
Out[3]= 23

For more info, see

This way can work:

x[foo] = bar

x[bar] = baz

x[1] = 7

x[7] = 1

x[c] = {{1,2,3},{4,5,6}}

and also for changing the elements of a list field you can so the following:

x[c] = ReplacePart[x[c], {1, 1} -> 8]

which returns:

x[c] = {{8,2,3},{4,5,6}}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!