Would it be possible to add a function
try : (ActionFail m) => a -> m a
to DAML, which turns an erroneous expression into a failing action using the same message?
If not, why not?
Would it be possible to add a function
try : (ActionFail m) => a -> m a
to DAML, which turns an erroneous expression into a failing action using the same message?
If not, why not?
There is no way to catch a call to error in DAML , it will abort the transaction. If you want catchable errors you can use something like Either Text a where you represent errors as Left "error" and success as Right a. Then you can handle the error simply by pattern matching. Note that a lot of methods, e.g., abort are overloaded so you can use abort "foo" in Either Text and it will produce a Left "foo". So if you don’t want to decide upfront how errors are handled, you can write your code with a CanAbort constraint and then later decide which instance you use.
I know there isn’t a way to do it right now. But would there by any issues if one added such a function to LF? My thinking is that it would give an easy way to handle errors such as division by zero.
I don’t see an issue with adding such a function. Of course you can argue about how useful it would be.
Note that you run into strictness issues if try is simply a function. So you have to be somewhat careful when implementing it.
In strict languages try is one of a handful of operators (along with if, and and or, as examples) that are not strict (and thus also not functions).
Edit: s/lazy/strict/
Do you mean “are lazy” rather than “are not lazy”? I’d be very confused if if was eager.
At least theoretically, I learnt that if is sugar for a case expression, i.e.
if b then x else y ===
case b of
True -> x
False -> y
There are implicit binders around the x and y branches (since True and False have implicit unit arguments) which means they aren’t evaluated “eagerly” even in strict languages like OCaml. This is the word of Bob Harper anyway. I think you can use the same reasoning for and and or (though the actual implementation would be different).