user-defined operators

James Hague <>
Mon Mar 29 17:11:40 CEST 2004

> K:
> +/1 2 3 4 5
> Erlang:
> lists:foldl (fun (X, A) -> X + A end, 0, [1, 2, 3, 4]).

Well, in Erlang you can just use lists:sum([1,2,3,4]).  As much as I admire
the Heaviside operators of J and K, I have to admit that hardcoding versions
for a handful of operators covers most of the same territory.

What I *would* like to see in Erlang (and I have brought this up before, to
the chagrin of many), is to extend basic math operators to work on tuples.
That is:

	{1,2,3} + {4,5,6} returns {5,7,9}
	1 + {2,4,6} returns {5,6,7}
	{2,4,6} + 1 returns {5,6,7}
	-{1,2,3} returns {-1,-2,-3}

This is simple, concise, and natural.  It also enables faster numeric work
in Erlang, not that this is a primary goal.  It should not be extended to
[1,2,3] + [4,5,6], as lists are not atomic like tuples.  Unlike most other
proposals, this could be implemented by changing a few functions in
erl_arith.c.  Some warnings would need to be disabled in the compiler, were
this made official.  One point of debate: whether to allow nested tuples.  I
would say no, as this starts leading to confusing agreement rules.

A related and more complex change--which I'm not proposing--is to
special-case tuples of floats, to avoid heap allocating each individual
float.  This is what OCaml does.  But doing this in Erlang would be messier.

More information about the erlang-questions mailing list