Tuple basics

Bill Baxter wbaxter at gmail.com
Fri Sep 12 21:34:12 PDT 2008


On Sat, Sep 13, 2008 at 11:50 AM, Sam Hu <samhu.samhu at gmail.com> wrote:
> Thanks BB,
>
> Acctually I have a copy of D spec. but still don't understand the section of Tuple.As you know not so many people using or studying D,esp in my country,so it seems that here is the best place to raise question-:)

No problem.  I just asked because often it is hard to find the
relevant sections in the spec.  No point in re-explaining all that if
you problem was just that you couldn't find the doc.

But anyway, knowing you've read that, and didn't get it, gives us a
better idea what your current level of understanding is.

I'll try to explain the basics. [Though I got distracted and downs
jumped in in the mean time... but here's what I wrote anyway]

The starting point is variadic templates.
Often it is useful to write a template that takes a variable number of
arguments.
In D you can write this:

void TupleTaker(alias fn, Tup...)(Tup theTuple)
{
     // do some logging or something
     // now call the function with supplied args
     fn(theTuple);
}

You can call that like this:

   TupleTaker!(writefln)("hi there customer %s, I'm %s", 32, "Bob");

And then it's just like you called writefln directly.  But you could
put any number of args there.  So that's maybe the biggest use of
Tuples.  Forwarding args to functions, and saving argument lists to
call functions later.

Inside TupleTaker,
Tup is a *type* tuple:
  - Tup[0] is the type of the first arg passed in (string)
  - Tup[1] is the type of the second (int),
  - Tup[2] is string again.

theTuple is a *value* tuple.  It consists of one item of each type in
the type tuple
  - theTuple[0]  is "hi there customer %s"
  - theTuple[1] is 32
  - theTuple[2] is "Bob"


In some ways a tuple is kind of like an anonymous struct, in that it
contains various elements of various types.  However you access the
parts of a tuple by index rather than by name.

In fact you can make a tuple out of a struct by using .tupleof, as
Downs pointed out.  That means you can call an N argument function
using an N member struct like so:
    n_arg_function(my_n_arg_struct.tupleof);

---bb


More information about the Digitalmars-d-learn mailing list