UI patterns in functional languages

functional programmingstateui

I would like to start fiddling with ClojureScript, but I am puzzled about some points. My problem is what is a good way to deal with state changes coming from user interaction, when you trying to work functionally.

Let me give a couple of examples. I have in mind applications which run in the browser, but I think the issue is more general. Of course something will be changing – the DOM at least. But I would like to find out how to organize the rest of the code to work with immutable data structures.

1) Say I want to attach some events to some DOM object. This is not hard to do in a mostly functional way: when you create the node, you attach it a hash map with the various event handlers. But consider the case where you are using event delegation. Then when you create a new node, you may attach a event handler to some parent node that probably already exists. So you would have to change the hash associated to the already existing node.

2) Say I am designing an autocomplete module for an input field. Every time the user presses a key, I can make a call to a server to get the suggestions. This is easy. But now suppose I want to optimize it a bit. If I know all results matching foo there is no point in asking again for all results matching foobar; I can just filter the former. So I need to build some kind of cache. This cache will be updated every time the user inserts a new word which is not a superset of the words previously entered. Again: how do I model the cache? The most reasonable way seems to be a hash map mapping words to results, but it should be mutable.

Can you suggest some patterns that would make it easier to incorporate changes due to user interaction into a functional design?

Best Answer

As mentioned in the comments you should look up "Functional Reactive Programming" and you should also read some of the posts at http://prog21.dadgum.com/archives.html. More specifically you should probably read "Don't Fall in Love With Your Technology", "Write Code Like You Just Learned How to Program", "Functional Programming Doesn't Work (and what to do about it)", and maybe a few other ones.

Completely avoiding mutability and side-effects is practically impossible. Even Haskell programmers will once in a while make use of unsafePerformIO to break out of the purely functional, side-effect free, statically typed paradigm to do certain things. If you are embarking on this project as a purely academic exercise then go right ahead and avoid mutability and side-effects as much as possible but if you are trying to build a usable product on a deadline then no pattern is going to save you.