[m-users.] When is nondeterminism appropriate?

Zoltan Somogyi zoltan.somogyi at runbox.com
Tue Feb 16 14:09:12 AEDT 2021


2021-02-15 23:40 GMT+11:00 "Volker Wysk" <post at volker-wysk.de>:
> Am Sonntag, den 14.02.2021, 15:32 -0500 schrieb Philip White:
>> :- type result ---> ok(T) ; error(string).
>> 
>> "functions that can fail" (either because of user error or something
>> else) seems like the perfect time to use semidet, but if I
>> want to have good error messages, then semidet will not help me, and I
>> might as well try to make my function deterministic.
> 
> This might be a good opportunity for using exceptions.

One difference between those two approaches is that returning
an error indication explicitly makes it significantly easier to return
*more than one* error indication.

Consider the code in the Mercury compiler that parses a pragma
that has several arguments (e.g. foreign_proc pragmas). It is possible
for each argument to have one or more syntax errors inside it.
We want the parser to print an error message for *each* syntax error,
to allow programmers to fix N syntax error errors with one recompilation,
instead of N recompilations.

The compiler uses a variant of the approach described by Philip,
with the difference being that the error case describes not one error,
but one or more errors. The code for parsing e.g. a foreign_proc pragma
then just parses each argument, and then checks whether they all
returned ok(...). If yes, it constructs the representation of the pragma
from the arguments inside those ok()s, and wraps an ok() around it.
If not, it appends error lists inside the error()s, and wraps another
error() around the result. This code is simple and direct. I don't think
I would say the same of code that tried to do this with exceptions.

Zoltan.


More information about the users mailing list