How can I get detailed error messages from a pure function in D?

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 if an error condition occurs, I have some idea of ​​what caused this (I can always put this in the debug block later).

Now, since writeln is not clean, vecMult is also not clean. 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 good way to get debug output from a pure function without making it unclean?

+6
source share
1 answer

You can use debug blocks to bypass cleanliness 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 create your program using the -debug compiler to include debug blocks.

+6
source

Source: https://habr.com/ru/post/974058/


All Articles