Let's consider an example: I want to turn on/off a light bulb. In C, I could just write:
struct lightbulb { int is_turned_on; /* from 1 to 10 */ int light_intensity; }; Whenever I want to turn the light bulb on or off, I change is_turned_on to 1 and how bright it is by setting light_intensity from 1 (dimmest) to 10 (brightest).
How can I do the same in functional programming? I guess I will have to create a list to hold these values, create a function ON and OFF to "turn" the light bulb on/off, and a function to return the light intensity of the light bulb. Every time the function is called, a new lightbulb is returned:
(defun turn-on() '(1 0)) (defun turn-off() '(0 0)) (defun light-intensity (x) `(0 ,(eval x))) I can see that function like light-intensity is a continuous function similar to a linear function. It will evaluate to the same result no matter how many times we pass the same argument x, for every x. The result of each function is a new light bulb with different state.
The problem is, how can I persist states? Obviously, I have to store it in somewhere in my memory through variable.
UPDATE: I found answer to above question through c2 Wiki - Functional Programming
How do data items persist?
On the stack. In a sequential, batch program, data is initialized and transformed in a top-level function. In a long-lived program like a server, a top level looping function is called recursively, passing global state from one call to the next.
I also have to create a new object (list) every time the function is called, how can I destroy the previous old object?
Isn't it more efficient and simpler to just mutate the variables through defparameter and setf? Imagine if it's not a light bulb, but a more complicated object with much more information? How can I model this as a function?
structdeclaration. In Lisp you cannot apply0. And I don't understand what you are asking.... Mutable data is not really functional programming.