I've read that a Declarative language is called "stateless". This means that we can imagine that internally every variable is a constant variable, and it never get reassigned ( in contrast with what usually happens in procedural programming). How can this work?
1 Answer
This isn't as exotic as it sounds, and you can do it in a procedural language fairly easily. The basic idea is just that instead of changing a value you just have a function return a new value. For instance, instead of something like
string read()
{
string s = '';
while((string c = getchar()) != '\n')
{
s += c;
}
return s;
}
you could write something like
string read()
{
string c = getchar();
if(c == '\n')
{
return '';
}
else
{
return c + read();
}
}
See how no variable ever gets reassigned here?
There are some subtleties here that I'm not going into, but I just wanted to illustrate that the idea is not that farfetched.
f(x) = x*x+4
wherex
ranges from0
to10
. We callx
a variable, even if we don't alter its value in the definition off(x)
. I think that if you read some tutorial for any functional programming language, you will understand the general idea: functions work as in maths. $\endgroup$