I have a college project in which I need to create a program which simulates an Erlang variable. I'm new in this type of programming so I don't quite understand.
I appreciate if someone can help me out or give me advice on how to approach this problem.
This would simulate a rudimentary Erlang variable which can take values of type int.
It should get you started; for generalising it boost::any http://www.boost.org/doc/libs/1_48_0/doc/html/any.html would come in handy.
> Can you explain to me how that code works step by step or at least how did you think it through?
Variables in Erlang are not like variables as most programmers (in other languages) think about variables; they are like variables as mathematicians think of variables.
An erlang variable is write-once - once a value has been associated with it, it cannot be changed.
X = 3. associates 3 with the variable X
X = 2 + 1. is fine; Erlang successfully matches the right-hand side, 3 to the left-hand side, X and produces the result 3.
X = 7. is an error; a matching error because Erlang tries to match the right-hand side, 7 to the left-hand side, X.
In the class erlang_var, this behaviour is mimicked. You might find this simplified version without templates easier to understand:
struct erlang_int_var
{
erlang_int_var( int v ) : value(v) {}
// implicit conversion to the value of the variable
operatorint () const { return value ; }
// the assignment operator = is overloaded to mimic Erlang behaviour
// it tries to match the right-hand side of the = with the left-hand side
// if there is no match, an exception is thrown to indicate a match-error
// if there is a match, the value of the variable is returned
intoperator= ( const erlang_int_var& another_var )
{
if( value != another_var.value ) throw std::logic_error("no match for rhs") ;
return value ;
}
intoperator= ( int another_value )
{
if( value != another_value ) throw std::logic_error("no match for rhs") ;
return value ;
}
int value ;
};