
Glurk wrote:
So, perhaps that's why I am having difficulty in seeing how some functional programming ideas apply.
What's got me a little puzzled at the moment is non mutable data. On the one hand, I think it's great that I can mostly forget about errors caused by my variables having unexpected values, and that I can reason about my program much more easily...
However, on the other hand, I wonder how it ties in with real world systems that do in fact do deal with objects that change state.
For example, if I was building a library system - I might have book objects, and if a book gets borrowed, there remains the same book object, but it now just has a different state - from "on shelf" say, to "borrowed".
Now, in Haskell, I might have a function to lend a book :-
lend book1
and this is going to return a new book, with the appropriate status change.. ...but what of the old book ? I don't want 2 book objects floating around.. ....to my way of thinking, it's really not a new book, it really is a change of state.
How do people see this kind of situation ? Is it just the way of looking at it... ? Do I just accept that I toss out my old library object, and have a new one, which happens to be the same as the old one, except for the "new" book which is now borrowed ?
Do I really need to get over thinking of objects in the first place, even though it's what I see exist in the real world ?
The point is that the real world doesn't happen inside the computer, only a model of it. The functional paradigm is based on the idea that immutable variables make for great models, even when state changes are involved. In other words, the book in your example is not a real book, it's just a few bytes in the computer that model it for the purpose of tracking whether it's lent out or not. For instance, these few bytes can be a unique ID and a possible lend function is lend :: BookID -> Library -> Library where the data type Library is a giant table of book IDs that keeps track of which ones are lent out and which are not. Together with a notion of "the current library", this is enough to model your example. In the end, even the library example is somewhat special in that it's too much about reality. Most programming problems, like sorting, compressing, type inference, etc. etc. are more abstract in nature and there is no a priori reason why mutable variables would be a good way of describing and modeling them. In fact, physics has been very successful at modeling the real world without mutable variables for centuries. Regards, Heinrich Apfelmus -- http://apfelmus.nfshost.com