[erlang-questions] Guards on assignment (i.e. assertions)
Mon Mar 1 21:50:25 CET 2010
You could easily make a user space assert macro. One that can optionally
take a message to print out as well on failure, and you could compile it out
in opt (non-debug) builds (courtesy or the erlang preprocessor)
?ASSERT(B > C when is_integer(B), "Bad value for B"),
ASSERT would then be trivial to write using preprocessor stringifier.
-define(ASSERT(Guarg, Str), case true of Guard -> ok; _ -> io:format(Str)
Not tested obviously but you get the idea.
On Mon, Mar 1, 2010 at 3:44 PM, Garrett Smith <> wrote:
> Right, that's fine. It's even pretty readable. Though when it fails,
> you just get an ambiguous "exception error: no true branch found when
> evaluating an if expression", which is why I prefer the case
> Both case and if are a bit verbose. A simpler syntax would, I think,
> encourage this practice.
> On Mon, Mar 1, 2010 at 2:34 PM, David Mercer <> wrote:
> > That seems like a legitimate use of the "if" keyword.
> > A = if B > C -> B end
> > Or
> > if B > C -> A = B end
> >> -----Original Message-----
> >> From: [mailto:]
> >> Behalf Of Garrett Smith
> >> Sent: Monday, March 01, 2010 2:00 PM
> >> To: Erlang Questions
> >> Subject: [erlang-questions] Guards on assignment (i.e. assertions)
> >> In most cases, assertions come "free" in Erlang in guards and pattern
> >> matching. There are cases though where I'd like to apply a guard a
> >> statement like this:
> >> A = B when B > C
> >> I currently do this:
> >> A = case B of ValidB when ValidB > C -> ValidB end
> >> or, a simpler form (but the error message on failure isn't as clear):
> >> A = if B > C -> B end
> >> There are other ways as well, e.g. using functions, etc. but I like
> >> the first form.
> >> I'm wondering how others implement basic assertions on assignments. I
> >> think if the first form were supported by the language, I'd use the
> >> "assert" pattern and my code would be better for it.
> >> Garrett
> >> ________________________________________________________________
> >> erlang-questions (at) erlang.org mailing list.
> >> See http://www.erlang.org/faq.html
> >> To unsubscribe; mailto:
> erlang-questions (at) erlang.org mailing list.
> See http://www.erlang.org/faq.html
> To unsubscribe; mailto:
More information about the erlang-questions