views:

402

answers:

4

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?

+5  A: 

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

Will Robertson
This way of doing things has one real advantage over the rule approach suggested by sakra: it allows you to mutate the "fields" of the "struct" in a straightforward way.
Pillsy
There's a problem with your answer: if a "field" is a list, its elements can't be changed individually. For example,x[foo]={1,2};x[foo] [[1]] =3 (* attempting to change list element *)will result in an error, because x[foo] is not an Lvalue.So it still doesn't fully replace C struct functionality.
+2  A: 

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.

Also see the Mathematica documentation on transformation rules.

sakra
+1  A: 

The transformation rules approach has the same drawback as the bracket approach. For instance, suppose you tried: (lastName /. person) = "Harvey" The result would be an error, not an assignment. The method works for retrieval but not for storage.

Jeff Brown at MSU Economics
+1  A: 

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}}

Atefeh