[erlang-questions] Guards on assignment (i.e. assertions)

Richard O'Keefe ok@REDACTED
Tue Mar 2 01:42:39 CET 2010


On Mar 2, 2010, at 9:49 AM, Garrett Smith wrote:
> ]The guard would be applied with the assignment operator as a check
> before the pattern matching was applied. So, only the second form.

Erlang doesn't _have_ an assignment operator.
(Unless you want to count put(Key, Value) as an 'operator'.)
Erlang has a _binding_ construct.
There is no difference between

	Lhs = Rhs

and

	case Rhs of Lhs -> Lhs end

This may sound like nit-picking, but I think something important
is lurking in the shadows, and it does hinge on the difference
between imperative and functional languages.

In an imperative language, you might do
	Lhs := Rhs;
	assert Condition;
and what you are doing is demanding that the program be in a
"good" partition of its STATE SPACE.  The program moves around
in its state space whenever assignments happen, so it makes
sense to link assertions with assignments.

Of course, while it may "make sense to link assertions with
assignments", imperative languages like C and Java do not in
fact to do.  Instead of
	if B > C -> A = B end
they'd do
	assert(B > C); A = B;
and nothing stops us doing
	-define(assert(G), if G -> ok end).
	...
	(?assert(B > C), A = B)
in Erlang.

In a functional language, you might do
	let Lhs = Rhs in Expr
but there isn't any state space and there aren't any assignments
to move around in it (unless you're using ML or CAML).  In this
context, most of the work done by assertions in an imperative
language should be done by PRECONDITIONS or POSTCONDITIONS on
functions.  You shouldn't _need_ to check Lhs because the check
should be built into the computation of Rhs.  The assertions
are still _there_, it's just a matter of what they are asserting
_about_.



More information about the erlang-questions mailing list