[erlang-questions] Process scope variable

Richard A. O'Keefe ok@REDACTED
Fri Feb 20 01:51:54 CET 2015

On 20/02/2015, at 3:34 am, Imants Cekusins <imantc@REDACTED> wrote:
> well the "state" gs calls would be quite fail-proof: get_state,
> set_state. The gs would only hold the state and make it accessible
> from anywhere.
> the rest of the program flow stays pretty much intact, no?
> to operate on the state variables I would still need to get state,
> assign it to a local variable in a function, then pass it to some
> function to work on this var.
> I do not aim to completely eliminate args. e.g. there would still be funs like
> parse(Bin) -> #parsed{}.
> it would be obvious from parse/1 signature that it does not change the
> state - another benefit.

Possibly I did not get enough sleep, but somehow I just couldn't understand
this.  Let's consider three functions.  I'll use Haskell syntax because I like it.

pure :: In -> Out
reader :: State -> In -> Out
writer :: State -> In -> (State, Out).

From this it is obvious that

 - pure does not depend on or change State
 - reader depends on State but does not change it
 - writer depends on State and may (but need not) change it.

I could write this in C as

    Out pure(In x)
        /*@ globals @*/
        /*@ modifies nothing @*/;
    Out reader(In x)
        /*@ globals state @*/
        /*@ modifies nothing @*/;
    Out writer(In x)
        /*@ globals state @*/
        /*@ modifies state @*/;

and similar markup is available for Ada and Java.

But using your approach

pure   :: In -> Out
reader :: Pid -> In -> Out
writer :: Pid -> In -> Out

I *cannot* distinguish a function that just reads the state from a
function that changes it.

One of the reasons I used to love the programming language Clean,
before they decided to concentrate on Windows, is that Clean makes
it easy to *BREAK UP THE STATE* into small pieces.  For example,
I can write a Clean function that modifies one file WITHOUT that
function being able to touch anything else in the file system.
Shoving *all* the state in one object and "mak(ing) it accessible
everywhere" increases the potential for errors.

Finally, it must have occurred to you that passing a state record/map
around and fishing stuff out of it is CHEAP, while sending a message
to another process, having it receive, sending a message back, and
receiving that is EXPENSIVE.  As an interprocess mechanism, it's
cheap enough to use whenever appropriate.  As a substitute for
assignment statements, OUCH.  Have you measured this cost?

Had you considered the possibility of developing whatever-it-is in
Elixir? http://elixir-lang.org/crash-course.html  Elixir allows
rebinding variables, so you can do
    {state,y} = f State, x
    {state,z} = g State, y

More information about the erlang-questions mailing list