Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

In Mathematica there is a way to create struct-like data type:

struct[myField]=value

I want to return myStruct from a function:

getStruct[input_List] := Module[{struct},
   (*populate struct[key]=value from input*)
   Return[struct];
   ];

But when I do:

st = getStruct[myInput];
DownValues[st]

it returns nothing, because it references symbol that was created inside function (like struct$1299885). I can still access this struct with st["field"], but it's not very usefully without field list.

Basically, I want to pass structs between functions, easily get field list AND easily access values inside those fields. And no, I don't want to do this with global symbols - I want to keep everything in local scope. Is it possible with Mathematica?

I tried this approach because you can easily nest structs within each other and easily access nested fields, like st["field1"]["field2"]. I can also do this with list of rules, but nested access requires a lot of code and looks ugly for something so simple.

Edit: it seems I was missing something very simple. To get list of fields I just needed to run:

DownValues[Evaluate[st]]

Thanks, Leonid.

share|improve this question
2  
You want DownValues[Evaluate[st]]. Not sure why this was downvoted. –  Leonid Shifrin Dec 28 '13 at 15:23
    
Thank you! This what I was looking for! –  EvgenijM86 Dec 28 '13 at 15:31
    
@LeonidShifrin Quite a lot of downvoting on questions these days. Perhaps a hats byproduct. –  belisarius Dec 28 '13 at 15:37
    
@LeonidShifrin Strange, I don't see any downvotes. Actually, I only see one vote in total. –  Sjoerd C. de Vries Dec 28 '13 at 15:51
1  
more on structs in this post mathematica.stackexchange.com/q/990/66 –  Faysal Aberkane Dec 28 '13 at 16:05
show 2 more comments

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.