Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Struct data type in Mathematica?

After playing with Mathematica's symbolic and numerical capabilities, I find it to be a decent programming language, too. However, something making it less appealing as a general-purpose language is the lack of C-like struct data type (or the record type as known in Pascal). How can I get around this problem?

like image 499
felix Avatar asked Sep 21 '09 05:09

felix


2 Answers

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.

like image 174
sakra Avatar answered Oct 15 '22 00:10

sakra


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).

like image 8
Will Robertson Avatar answered Oct 14 '22 23:10

Will Robertson