[Tutor] Shared State

Alan Gauld alan.gauld at btinternet.com
Mon Jul 29 21:03:25 CEST 2013


On 29/07/13 19:30, wolfrage8765 at gmail.com wrote:

> I want to learn to program in a more functional manor, in fact I am
> now reading a book on Erlang, but I still mostly program in Python.  I
> want to know how you reduce side-effects in a GUI program, and further
> how you handle side effects when you must.

You can do a pure functional GUI but it will be slow.....
In my experience functional is much better suited to batch processing 
scenarios - for example each thread launched by a GUI may be functional 
but the overall GUI is better with shared state, usually using OOP.

Remember too that

x = f(x)

is the functional equivalent of

f(x)   # x is set inside f()

So, GUI state can be encapsulated in a data structure (tuple, dict, 
class) and your functions can return an updated version of the state.
But with multiple threads that means lots of update calls and thread 
safe synchronisation - hence a slow GUI.

> was violating DRY, as every thread would be storing it's own copy of
> the state variables that it cared about.

Or you pass in the current values each time you call the update() function.

> host IP is obtained the program establishes a connection and transfers
> the files, during the transfer the UI is updated with the progress.

The update needs to be as fast as possible and only done at the end of 
any extensive processing. Store the results in an intermediate container 
if necessary (temporary state - a compromise on pure functional but...).

Personally I only use pure FP where it makes sense, trying to force FP 
into a solution that it doesn't fit well is a lot of pain for little 
gain IMHO. (The same is true for OOP of course! And the good news is 
that many of the places OOP does not suit fit very well with FP!)

You might find it helpful to see how Lisp or Haskell? or erlang? 
programmers work with GUIs, there are a few web tutors for that...
The biggest problem is that the GUI frameworks themselves are not FP 
friendly. You might find this link interesting:

http://stackoverflow.com/questions/2672791/is-functional-gui-programming-possible


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list