In D, suppose I have a function like:
private static double vecMult(immutable Vector v1, immutable Vector v2) pure {
double sum = 0.0;
foreach(ulong k; v1.keys)
sum += v1[k] * v2[k];
return sum;
}
Now, suppose, for debugging or testing purposes, I would like to insert something like:
private static double vecMult(immutable Vector v1, immutable Vector v2) pure {
double sum = 0.0;
foreach(ulong k; v1.keys)
if(!(k in v2)){
writeln(k);
exit(1);
}
sum += v1[k] * v2[k];
return sum;
}
so that, if an error condition happens, I have some idea of what caused it ( I can always put this in a debug block later).
Now, since writeln is not pure, vecMult is no longer pure either. If vecMult is a low level function that is called by other pure functions, that call other pure functions, then removing the "pure" keyword from vecMult is non-trivial.
Is there a nice way to obtain debugging output from a pure function without making it non-pure?
You can use debug
blocks to bypass purity in pure
functions. Example:
private static double vecMult(immutable Vector v1, immutable Vector v2) pure {
double sum = 0.0;
foreach(ulong k; v1.keys) {
debug if(!(k in v2)){
writeln(k);
exit(1);
}
sum += v1[k] * v2[k];
}
return sum;
}
Remember to build your program with the -debug
compiler switch to enable debug
blocks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With