How do exceptions in Haskell work? - exception

In GHCi:
Prelude> error (error "")
*** Exception:
Prelude> (error . error) ""
*** Exception: *** Exception:
Why isn't the first one a nested exception?

The answer is that this is the (somewhat surprising) semantics of imprecise exceptions
When pure code can be shown to evaluate to a set of exceptional values (i.e. the value of error or undefined, and explicitly not the kind of exceptions generated in IO), then the language permits any value of that set to be returned. Exceptional values in Haskell are more like NaN in floating point code, rather than control-flow based exceptions in imperative languages.
An occasional gotcha for even advanced Haskellers is a case such as:
case x of
1 -> error "One"
_ -> error "Not one"
Since the code evaluates to a set of exceptions, GHC is free to pick one. With optimizations on, you may well find this always evaluates to "Not one".
Why do we do this? Because otherwise we'd overly constrain the evaluation order of the language, e.g. we would have to fix a deterministic result for:
f (error "a") (error "b")
by for example, requiring that it be evaluated left-to-right if error values are present. Very un-Haskelly!
Since we don't want to cripple the optimizations that can be done on our code just to support error, the solution is to specify that the result is a non-deterministic choice from the set of exceptional values: imprecise exceptions! In a way, all exceptions are returned, and one is chosen.
Normally, you don't care - an exception is an exception - unless you care about the string inside the exception, in which case using error to debug is highly confusing.
References: A semantics for imprecise exceptions, Simon Peyton Jones, Alastair Reid, Tony Hoare, Simon Marlow, Fergus Henderson. Proc Programming Languages Design and Implementation (PLDI'99), Atlanta. (PDF)

Related

create_mutable/2 in SICStus Prolog

The SICStus Prolog manual page on mutable terms states that:
[...] the effect of unifying two mutables is undefined.
Then, why does create_mutable(data,x) fail?
Shouldn't that rather raise an uninstantiation_error?
I cannot think of a situation when above case is not an unintentional programming error (X vs x)... please help!
The short answer to "Why does create_mutable/2 not throw an exception when output unification fails?" is just: Because this was how it was done when the feature was added to SICStus Prolog, and no one has made a strong case for changing this.
One important "difference between the stream created by open/4 and the mutable term created by create_mutable/2" is that open/4 has side-effects that are not undone if the output-unification of the call to open/4 fails.
In this sense, create_mutable/2 is somewhat more like is/2 which also just quietly fails if the output argument is some non-numeric non-variable term, e.g. in x is 3+4. This seems to be the common, and traditional, way of handling output arguments in Prolog.
I agree that a non-variable as second argument is most likely a programming error. The next version of the SICStus IDE, SPIDER, will warn for this (as it already does for is/2).
None of this, nor the example in the question, seems directly related to the cited documentation "[...] the effect of unifying two mutables [...]".

too greedy condition, or misused exception?

I have two alternative code fragments, with an intention to do (approximately) the same:
Closed-ended condition, with 3 cases of inputs resulting into just 2 cases of outputs:
this.showDropdowns ? parseInt(this.uploadForm.get('location').value, 10) : null;
Open-ended conditioning, with 3 possible cases of inputs resulting into 3 recombined (table non-plain matching) cases of outputs:
try {parseInt(this.uploadForm.get('location').value, 10)} catch (ParseIntError e) {return null;}
The first case is strict, allowing only the two resulting options explicitly prepared by the programmer: Either gives null (i), or the parsed value (ii), or the parsing falls (iii) back to the null.
See the Closed/Open questions described on Wikipedia, to understand me what I mean.
The second code-fragment is not so greedy, does not swallow any possible exception, so the values are the two (three) expected by a programmer: The successfully parsed value (a), or there is still an allowed option for any unexpected result, as an explicitly caught Exception (also merging the null input/output case (b) with the parsing error exception (c), the non-null input, to be parsed, but unprocessable), but still yet allowing a fourth case of whatever completely unimaginable in the moment of the programming (d), still letting it to bubble up as an uncaught exception.
The inputs could be just two, in general: null, or an Object.
The outputs on the other hand could be more complicated:
the hardcoded null, after the IF;
the successfully parsed value;
or Exceptions:
Completely wrong Object-type for the particular parsing.
Parsable Object-type, but wrong values in it, in many ways...
So the questions:
Is the first one too naive and too greedy, swallowing too much, or oppositely the aggregation/swallowing is the recommended way?
Would the second be misusing of the mechanism of exceptions, or just the standard plain usage?
Are these known distinguished cases/options, how to resolve problems? These might be even so general, that there are some rules, philosophical how-to's or Good practices, to judge/recognize, when exactly to use the 1st, or the 2nd? So what are the rules, the recommendations? Thanks.

How To Raise Exception with Message in Ada

I'm struggling a little bit to raise exceptions the way I'm used to coming from a C# background.
I have a utility function that expects input values to be in a very specific range, as defined by an external standard. If a value is supplied outside of that range (and there is one value in the middle of the range that is also invalid), then I want to raise an exception to the caller so that they break.
From what I can tell, the syntax is raise Invalid_Argument;
But- is it possible to supply a message with the exception? e.g. the Invalid_Argument exception is somewhat self-explanatory, but I could see further detail specifying what was wrong with the argument. How do I write a brief error message to be stuck into the exception?
It used (Ada 95) to be you had to write
Ada.Exceptions.Raise_Exception (Invalid_Argument’Identity,
"message");
(see Ada95RM 11.4.2(6)) but since Ada 2005 you’ve been able to say
raise Invalid_Argument with "message";
(A2005RM 11.3).
Note that the string part is a string expression, so you can add something to describe the actual invalid value if that would be useful.
First, you can define a [sub]type
[sub]type Valid_Range_For_X is [Integer] range 23 .. 2001;
This will catch most invalid values automatically. If you're using Ada 12, you can add
[sub]type Valid_Range_For_X is [Integer] range 23 .. 2001 with
Dynamic_Predicate => Valid_Range_For_X /= 42;
which will catch the internal invalid value as well. It's usually better to let the language do such checks for you than to do them manually.
If you're using an earlier version of Ada, then you'll have to manually check for the internal value. I usually prefer fine-grained exceptions to a general exception used for many things, differentiated by the exception message. So I would raise something like
X_Is_42
rather than
Invalid_Argument with "X is 42"
This makes it easier to distinguish the 42 case from the (often many) other kinds of invalid arguments. I realize not everyone agrees with this.

Ensuring that a predicate succeeds deterministically

This other question asks almost the same, but not quite. Rather, how do I demand that a goal succeeds deterministically (exactly once) and does not leave behind any choice points?
This is especially useful in the context of Prolog programs that are used as command-line tools: possibly read from standard input, take arguments, and write to standard output. In such a program, leaving a choice point after doing the work is invariably an error of the programmer.
SWI-Prolog offers deterministic/1, so one could write:
( deterministic(true)
-> true
; fail
)
Another, more portable way to achieve the same was suggested:
is_det(Goal, IsDet) :-
setup_call_cleanup(true, Goal, Det=true),
( Det == true
-> IsDet = true
; !,
IsDet = false
).
However, it seems useful to throw an error when this happens, but I don't know what this error would be. I looked quite carefully through the ISO error terms and I could not find an error that would obviously describe this situation.
Is it indeed better to throw an error, or should I just fail? If throwing an error is to be preferred, what would that error be?
EDIT: I am not sure what to because especially when side effects are involved, like writing something to standard output, it feels very wrong to have the side effect happen and then fail. It is almost necessary to rather throw an exception. This makes it also possible to decide that the remaining choice point is harmless (if not desirable) and just catch the exception, then write to standard error or return a different exit code.
But I really have no idea what describes the exception properly, so I don't know what term to throw.
Check out call_semidet/1 as proposed by Ulrich Neumerkel on the SWI-Prolog mailing list:
call_semidet/1 - clean removal of choice-points
In it, he proposes:
call_semidet(Goal) :-
( call_nth(Goal, 2)
-> throw(error(mode_error(semidet,Goal),_))
; once(Goal)
).
This proposed mode_error is a very good start.
In spirit, it follows the other errors: In this case, mode semidet is expected, and this is reflected in the thrown error term.

How to throw exception in a .oct file in octave?

I am currently developing geotiff reading and writing functions for octave using .oct files. I went through the octave documentation but could not find much on throwing exceptions. Does that mean I can throw exception the way I do it in C++ by just simply writing throw "error message"?
There are two ways, admittedly they are documented in two utterly separate places, not cross-linked/cross-referenced, which makes no sense, and if you didn't know the function/keyword you wouldn't find them:
error() raises an error, which stops the program. See 12.1 Raising Errors.
error("[%s] Here be wyrms", pkgname)
assert() both tests the condition then raises the error() with a customizable message (so don't do if (cond) ... error(...) ... endif).
See B.1 Test Functions.
% 1. Produce an error if the specified condition is zero (not met).
assert (cond)
assert (cond, errmsg)
assert (cond, errmsg, …)
assert (cond, msg_id, errmsg, …)
% 2a. Produce an error if observed (expression) is not the same as expected (expression); Note that observed and expected can be scalars, vectors, matrices, strings, cell arrays, or structures.
assert (observed, expected)
% 2b. a version that includes a (typically floating-point) tolerance
assert (observed, expected, tol)
See also the command fail()
Yes, you could just use something like
error ("mynewlib: Hello %s world!", "foo");
to signal errors which are catched and viewed.
(Personally I think such questions should really go to the GNU Octave mailing list where you'll find the core developers and octave-forge package maintainers).
I guess you want to build a wrapper around libgeotiff? Have a look at the octave-image package! Where do you host your code?
./examples/code/unwinddemo.cc might also be interesting for you. It shows how to use unwind_protect and define user error handlers.
http://hg.savannah.gnu.org/hgweb/octave/file/3b0a9a832360/examples/code/unwinddemo.cc
Perhaps your function should then be merged into the octave-forge mapping package: "http://sourceforge.net/p/octave/mapping/ci/default/tree/"