Rather neat way of doing multiple return values
Chris Nicholson-Sauls
ibisbasenji at gmail.com
Sat Mar 17 15:02:02 PDT 2007
kris wrote:
> Tom S wrote:
>> Downs wrote:
>>
>>> Here's a (imnsho) rather neat implementation of multiple return
>>> values from functions.
>>>
>>> (...)
>>> Have fun! :D
>>
>>
>> Hehehe nice :) Here's my version:
>>
>>
>> ---
>>
>> import std.stdio;
>> import std.bind;
>>
>>
>>
>> struct PtrTuple(P, V) {
>> P ptrs;
>>
>> void opAssign(V v) {
>> foreach (i, x; v.value) {
>> *ptrs.value[i] = x;
>> }
>> }
>> }
>>
>>
>>
>> PtrTuple!(PointerTuple!(Tuple!(T)), Tuple!(T)) tup(T ...)(inout T t) {
>> PtrTuple!(PointerTuple!(Tuple!(T)), Tuple!(T)) ptrs;
>> foreach (i, dummy_; t) {
>> ptrs.ptrs.value[i] = &t[i];
>> }
>>
>> return ptrs;
>> }
>>
>>
>> Tuple!(int, float, char) someFunc(int i) {
>> return tuple(i, 0.1f * i, cast(char)i);
>> }
>>
>>
>>
>> void main() {
>> int a;
>> float b;
>> char c;
>>
>> tup(a, b, c) = someFunc(55);
>>
>> writefln("a = %s", a);
>> writefln("b = %s", b);
>> writefln("c = %s", c);
>> }
>>
>> ---
>>
>> Maybe Phobos could use such a utility, as it (apparently) gets
>> reimplemented numerous times ?
>>
>>
>> --
>> Tomasz Stachowiak
>
>
> Cool, but it's worth pointing out that this is probably Latin to most
> people :)
Not I; in fact, I'm loving it. (Although I liked the PHP'ish use of list() for
assignment. I'm strange.) Maybe we could evolve this toward a LambdaMOO/ColdC style
scatter assignment. Contrived ColdC example:
protected method ._cmd_viewCacheInfo {
var width, depth, map, row;
[width, depth, map] = cache_info(); // <- scatter
.tell("Cache Width = ", width);
.tell("Cache Depth = ", depth);
.tell("Map: (Legend: i/I = Inactive, a/A = Active, I/A = Dity)");
for row in (map) {
.tell(" ", @row); // <- list spice, also available in scatter
}
.tell();
}
I can dream. And this comes right up against it, just need a way to specify a catch-all
at the end for trailing elements.
-- Chris Nicholson-Sauls
More information about the Digitalmars-d
mailing list