kwargs v0.0.1 - Keyword arguments with strong types

Atila Neves atila.neves at gmail.com
Mon Feb 11 17:03:36 UTC 2019


https://code.dlang.org/packages/kwargs

There have been many posts asking about keyword arguments for D a 
la Python. Usually I reply saying to just use the type system, 
but that has the incovenience of having to pass all 7 parameters 
before the optional 8th one you actually care about despite you 
being ok with the default values before that. std.process.execute 
is a particular thorn in my side since I usually only want to 
change `workDir`, but I digress. Behold:


--------------------------
import kwargs;

struct Foo { string value; }
struct Bar { string value; }
struct Baz { string value; }

size_t funImpl(in Foo foo, in Bar bar = Bar("lebar"), in Baz baz 
= Baz("lebaz")) {
     return foo.value.length + bar.value.length + baz.value.length;
}

alias fun = kwargify!funImpl;

fun(Foo()).should == 10;
fun(Bar("b"), Foo("fo")).should == 8;
fun(Bar("b"), Baz("ba"), Foo("foo")).should == 6;
------------------------------------------


The API for compile-time parameters isn't as nice, but seeing as 
how there's no way in D that I know of currently to reflect on 
those, this is what I managed to conjure up:


----------------------
struct Foo { int val; }
struct Bar { int val; }
struct Baz { int val; }

int[] funImpl(Foo foo, Bar bar, Baz baz)() {
     return [foo.val, bar.val, baz.val];
}

alias fun = kwargify!(funImpl, Required!Foo, Optional!(Bar(2)), 
Optional!(Baz(3)));

fun!(Foo(1)).should == [1, 2, 3];
fun!(Baz(9), Foo(7)).should == [7, 2, 9];
fun!(Baz(9), Bar(8), Foo(7)).should == [7, 8, 9];
----------------------


More information about the Digitalmars-d-announce mailing list