Note that there are some explanatory texts on larger screens.

plurals
  1. POCan everything be modelled as functions?
    primarykey
    data
    text
    <p>Let's consider an example: I want to turn on/off a light bulb. In C, I could just write:</p> <pre><code>struct lightbulb { int is_turned_on; /* from 1 to 10 */ int light_intensity; }; </code></pre> <p>Whenever I want to turn the light bulb on or off, I change <code>is_turned_on</code> to 1 and how bright it is by setting <code>light_intensity</code> from 1 (dimmest) to 10 (brightest). </p> <p>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 <code>ON</code> and <code>OFF</code> 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:</p> <pre><code>(defun turn-on() '(1 0)) (defun turn-off() '(0 0)) (defun light-intensity (x) `(0 ,(eval x))) </code></pre> <p>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 <code>x</code>, for every x. The result of each function is a new light bulb with different state.</p> <p>The problem is, how can I persist states? Obviously, I have to <em>store</em> it in somewhere in my memory through variable. </p> <p><strong>UPDATE:</strong> I found answer to above question through <a href="http://c2.com/cgi/wiki?FunctionalProgramming" rel="nofollow">c2 Wiki - Functional Programming</a></p> <blockquote> <p><strong>How do data items persist?</strong></p> <p>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.</p> </blockquote> <p>I also have to create a new object (list) every time the function is called, how can I destroy the previous old object? </p> <p>Isn't it more efficient and simpler to just mutate the variables through <code>defparameter</code> and <code>setf</code>? 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?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload