I have a function (using SetDelayed) that currently returns 3 values in a list. Later on I use the result of this list along with [[1]], [[2]], and [[3]] to use the values. Is there a way I can give each value a "name" of some sort, and return only one value in such a way that all these values can be accessed by name? (Coming from an object-oriented programming perspective, I just want to return a single object with a few fields/accessors.)
|
|
||||
|
Here are some options: Lists of Rules A simple option would be to return a list of rules:
Fields can then be extracted thus:
Wrapper Patterns A variation on this theme would be to define a pattern that represents a new value type:
Extracting fields is more verbose:
... but it opens the possibility of extracting values computed from multiple fields:
Manually Defined Wrapper Accessors We could extend the previous example by writing "accessor functions" that access components of a wrapper:
Automatically Defined Wrapper Accessors If we were going to define many such wrapper types, it would be convenient to automate the generation of the wrapper functions:
For example:
|
|||
|
|
|
Just picking up three named return values:
Or using an inert object with functions defined on itself:
|
|||
|
|
|
I'm not saying I recommend this. It's prone to leaking memory
So
Perhaps a better approach is passing the output variable to the function
So
|
||||


List[]– belisarius Oct 26 '12 at 23:00yourF[x_]:={a[x],b[x],c[x]}; {myA, myB, myC} = yourF[x]– belisarius Oct 26 '12 at 23:12