Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 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?

like image 630
John Doucette Avatar asked Aug 19 '14 22:08

John Doucette


1 Answers

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.

like image 161
Vladimir Panteleev Avatar answered Oct 24 '22 09:10

Vladimir Panteleev