Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ERL-1122: Function to fail in guards #4011

Closed
OTP-Maintainer opened this issue Dec 20, 2019 · 1 comment
Closed

ERL-1122: Function to fail in guards #4011

OTP-Maintainer opened this issue Dec 20, 2019 · 1 comment
Assignees
Labels

Comments

@OTP-Maintainer
Copy link

Original reporter: hauleth
Affected version: Not Specified
Component: Not Specified
Migrated from: https://bugs.erlang.org/browse/ERL-1122


Such function would be useful for custom guards in Elixir (and probably other languages that allow defining such). Example could be {{is_struct/2}} in Elixir which would fail if the second argument is non-atom. Current hack involves using function that will always fail, ex.:

{code:ruby}
defguard is_struct(struct, type)
  when is_map(struct) and (is_atom(type) or hd([]))
    and :erlang.map_get(:__struct__, struct) == type
{code}

However that seems pretty unidiomatic. Having function like {{erlang:guard_fail/0}} would make it more readable and would show the intended behaviour.
@OTP-Maintainer
Copy link
Author

bjorn said:

There does not seem to be much use for a {{guard_fail/0}} BIF for Erlang programs, and for Elixir it seems that you could easily add your own {{guard_fail/0}} function that expands to an expression that will fail in a guard.

By the way, there is another way to make a guard fail. Perhaps this is clearer:
{code:java}
defguard is_struct(struct, type)
  when is_map(struct) and (is_atom(type) or :fail)
    and :erlang.map_get(:__struct__, struct) == type
{code}
This works because a non-boolean value as the left operand of any boolean operation ({{and}}, {{andalso}}, and so on) will cause the entire guard to fail.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants