M. Lanza
M. Lanza

Reputation: 6790

FP: Reflecting state in absence of actual state change?

I am new to some of the advanced functional programming ideas, in particular: how to work with immutable data. Data structures are often composites, composed of smaller data structures. For instance, if we have a Family collection which is made up all of the Members of a household. We might construct the family:

var flintstones = new Family().
    add(new Member({name: 'Fred'})).    //returns new instance of family 
    add(new Member({name: 'Wilma'}).    // "
    add(new Member({name: 'Pebbles'})); // "
var fred = flintstones.get({name: 'Fred'}).set({lname: 'Flintstone'});
flintstones = fred.family(); //new instance of family with latest fred.

Notice how changing fred did not actually change flintstones. I can grab a fresh reference to flintstones but for what purpose? As all objects are mere snapshots I can't see the point of retaining a reference. State changes have been abstracted away, so we're not going to use the Observer pattern. Thus, how are dependent things like GUIs that care about state changes handled? What is the functional alternative to observation for keeping things in sync? I don't see the objects themselves as having any business in rendering themselves. How might a functional program handle keeping the state of a single-page webapp GUI in sync?

For what it's worth Rich Hickey's talks inspired me to explore functional programming. I get his concepts, but I struggle with leaping to a practical implementation (in JavaScript).

Upvotes: 3

Views: 180

Answers (1)

Matthew Strawbridge
Matthew Strawbridge

Reputation: 20640

In your example, Family is supposed to be immutable. So each call to add must return a whole new object that is based on the contents of the existing object (themselves immutable, so copying them isn't a problem) plus the new thing. Similarly, the set you call on Fred must return a whole new family member based on Fred but with a different last name. (Therefore the original Fred inside Flintstones is not changed at all.)

The advantage of this functional style is that once you've got a reference to an object, you know it's not going to change. If it was valid when it was constructed, you don't have to keep checking whether it's still valid. Any you can pass the object out of your code without having to clone it first to protect your internal copy from being changed.

If you want to learn more about functional programming you might be better off trying out a purely functional language such as Haskell or F#; trying to do functional programming in JavaScript is just likely to be confusing.

Upvotes: 2

Related Questions