Anonymous user
Retrieving an Element of an Array: Difference between revisions
→{{header|D}}: D
(added standard ml) |
(→{{header|D}}: D) |
||
Line 102:
(defun array-value (array index)
(aref array index))
=={{header|D}}==
Generic, template-based method. Allows retriving elements
of arrays and objects having opIndex method implemented.
<lang D>
// GetElem.d
module GetElem;
import tango.core.Variant;
import tango.core.Traits;
/// objects must have opIndex method
template GetItemType(T) { alias ReturnTypeOf!(T.opIndex) GetItemType; }
// specialization for arrays
template GetItemType(T : T[]) { alias T GetItemType; }
GetItemType!(T) GetElem(T, U)(T array, U idx)
{
return array[idx];
}
</lang>
Sample usage:
<lang D>
import tango.io.Stdout;
import GetElem;
class SampleContainer {
static char[][] data = [ "lazy", "fox" "jumped", "over", "dog" ];
public:
char[] opIndex(uint pos) { return data[pos]; }
}
void main()
{
auto y = new SampleContainer;
auto x = [5, 1, 7, 3, 6, 4, 2 ];
Stdout (GetElem(x, 3)).newline;
Stdout (GetElem(y, 3)).newline;
// generate exception
Stdout (GetElem(x, -1)).newline;
}
</lang>
=={{header|Delphi}}/{{header|Object Pascal}}/Standard {{header|Pascal}}==
|