Tuples as paramters

Jeffrey Straszhiem stimuli@REDACTED
Mon Sep 25 05:05:53 CEST 2000

On Sun, Sep 24, 2000 at 08:10:47PM -0500, Andy with Recycled Electrons

> Hi..

> I've got a newbie question;  What's wrong with this code:

Don't worry, I'm a newbie too.

> nadd({mean1, variance1, number_samples1},
>      {mean2, variance2, number_samples2}) ->	% N1 + N2
> 	{mean1 + mean2,				% mean
> 	 variance1 + variance2,			% variance
> 	 (number_samples1 + number_samples2)/2	% number of samples
> 	}.

Variables in Erlang must start with an uppercase letter.  The compiler
assumes that you are trying to match a pattern with atoms names mean1,
variance1, etc.; instead of variables by those names.  Try giving them
uppercase names, like this:

nadd( {Mean1, Variance1, NumSamples1},
      {Mean2, Variance2, NumSamples2}) ->
       {Mean1 + Mean2,
        Variance1 + Variance2,
        (NumSamples1 + NumSamples2) /2

See if this doesn't give better results.

Just to help in the future, the cryptic error message that you got was
telling you that the interpreter could not find a matching function
clause for the arguments.  That is, of the patterns you listed, none
matched the actual data.

You can tell this by changing the full stop in your bad code to a
semicolon, and adding another clause like so:

nadd(A,B) -> {here, A, B}.

If you then try you will see it returns:

{here, {1,2,3}, {10,11,12}}

or whatever your exact numbers were.  This is because the triples end
up matching to the variables A and B, where they wouldn't match the
atoms mean1, mean2, and so forth.

Does this make sense now? :)

-- Jeffrey Straszheim              |  A sufficiently advanced
-- Systems Engineer, Programmer    |  regular expression is
-- http://www.shadow.net/~stimuli  |  indistinguishable from
-- stimuli AT shadow DOT net       |  magic

More information about the erlang-questions mailing list