Article: Writing Julia style multiple dispatch code in D
jmh530 via Digitalmars-d-announce
digitalmars-d-announce at puremagic.com
Fri Aug 25 07:30:03 PDT 2017
On Friday, 25 August 2017 at 01:04:31 UTC, data pulverizer wrote:
> [snip]
With respect to your point about immutability, you might be
interested in the parameterize function in dstats.distrib. I
hadn't noticed that was there, but I think it accomplishes, to a
limited extent, the behavior of what you want. It returns a
delegate with the values of the distribution fixed in there.
Along the same lines, I think below is how I would set it up,
rather than the mixin approach I discussed above. While it does
not currently work with the parametrize funciton currently, I
believe that with some simple adjustments it could.
import std.stdio : writeln;
struct Normal
{
import dstats : normalCDF, normalCDFR, normalPDF,
invNormalCDF;
alias cdf = normalCDF;
alias cdfr = normalCDFR;
alias pdf = normalPDF;
alias density = pdf;
alias icdf = invNormalCDF;
}
struct LogNormal
{
import dstats : logNormalCDF, logNormalCDFR, logNormalPDF;
alias cdf = logNormalCDF;
alias cdfr = logNormalCDFR;
alias pdf = logNormalPDF;
alias density = pdf;
//no icdf for LogNormal in dstats
}
private void hasMemberCheck(alias T, string x)()
{
import std.traits : hasMember;
static assert(hasMember!(T, x), T.stringof ~ " must have " ~
x ~" member to
call " ~ x ~ " function");
}
auto cdf(alias T, U...)(U u)
{
hasMemberCheck!(T, "cdf");
return T.cdf(u);
}
auto pdf(alias T, U...)(U u)
{
hasMemberCheck!(T, "pdf");
return T.pdf(u);
}
auto pmf(alias T, U...)(U u)
{
hasMemberCheck!(T, "pmf");
return T.pmf(u);
}
auto cdfr(alias T, U...)(U u)
{
hasMemberCheck!(T, "cdfr");
return T.cdfr(u);
}
auto density(alias T, U...)(U u)
{
hasMemberCheck!(T, "density");
return T.density(u);
}
auto icdf(alias T, U...)(U u)
{
hasMemberCheck!(T, "icdf");
return T.icdf(u);
}
void main()
{
writeln(Normal.cdf(0.5, 0.0, 1.0));
writeln(cdf!Normal(0.5, 0.0, 1.0));
writeln(icdf!Normal(cdf!Normal(0.5, 0.0, 1.0), 0.0, 1.0));
writeln(LogNormal.cdf(0.5, 0.0, 1.0));
writeln(cdf!LogNormal(0.5, 0.0, 1.0));
//writeln(icdf!LogNormal(cdf!LogNormal(0.5, 0.0, 1.0), 0.0,
1.0));
//error
}
More information about the Digitalmars-d-announce
mailing list