How do you use templates in D?
Andrew Pennebaker
andrew.pennebaker at gmail.com
Tue Oct 18 11:28:59 PDT 2011
ntrel2<http://www.reddit.com/r/d_language/comments/lghzs/how_do_you_use_templates_in_d/>has
the answer:
char genChar() {
return cast(char) uniform(0, 128);
}
T[] genArray(T)(T function() gen) {
int len = uniform(0, 100);
T[] arr = [];
for(int i = 0; i < len; i++) {
arr ~= gen();
}
return arr;
}
string genString() {
return genArray(&genChar).idup;
}
Now I'm curious: How can I pass and accept a collection of lambdas? The
lambdas will each have different, arbitrary returns types. And how do I call
a function using a collection of values, something like Lisp's (apply f
args) ?
Cheers,
Andrew Pennebaker
www.yellosoft.us
On Tue, Oct 18, 2011 at 1:56 PM, Andrew Pennebaker <
andrew.pennebaker at gmail.com> wrote:
> I'm writing a function called genArray that accepts a function gen and
> returns a random array populated by calling gen(). genString builds on
> this by returning genArray(&genChar). But my type signatures are wrong.
>
> In dashcheck.d:
>
> char genChar() {
> return cast(char) uniform(0, 128);
> }
>
> T[] genArray(T function() gen) {
> int len = uniform(0, 100);
> T[] arr = [];
>
> for(int i = 0; i < len; i++) {
> arr ~= gen();
> }
>
> return arr;
> }
>
> string genString() {
> return genArray(&genChar);
> }
>
> Trace:
>
> dashcheck.d(17): Error: undefined identifier T
> dashcheck.d(17): Error: T is used as a type
> dashcheck.d(17): Error: undefined identifier T
> dashcheck.d(17): Error: T is used as a type
>
> Full code at GitHub <https://github.com/mcandre/dashcheck>
>
> Cheers,
>
> Andrew Pennebaker
> www.yellosoft.us
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d/attachments/20111018/e0905f1f/attachment.html>
More information about the Digitalmars-d
mailing list