Allow some function equality comparison #1978
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Relax the initial restriction on comparing functions, introduced in #975, which is that comparing a function to anything else errors out. In practice comparing a function to a value of some other type isn't a problem, and can be useful to allow patterns like
fun x => if x != null then ... else ...
without having first to defensively check ifx
is a function, because that would fail at runtime. One can think for example of quick contracts such aslet IsZero = from_predicate ((==) 0)
, which currently fails with a dynamic type error if we try to do(fun x => x) | IsZero
. We'd need to do something likefrom_predicate (fun x => !(std.is_function x) && x == 0)
, which is annoying.Instead, we only forbid comparison between two function-like values (functions, match expressions and custom contracts) and between two opaque foreign values. Comparing a function-like value to a number of a string is fine and just returns false.
The initial motivation for restricting function comparison is that it's never something that is meaningful to do, so it's most probably an error, and that it breaks reflexivity of
==
, becausef != f
whenf
is a function. Arguably, the relaxed restriction proposed in this PR still fits the bill.For context, this came up in #1975, where custom contracts is internally a pair of function
(immediate, delayed)
, each of which can benull
, but then we can't do control flow such asif immediate != null then ...
. While the%typeof%
work-around does work, it doesn't feel right.