Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

This is a more general declarative vs imperative question so if you search for "declarative programming", you should find lots of examples. But here is one, taken from Bret Victor[0]:

Consider a classic drawing API:

    // stem
    fill('green')
    rect(146, 60, 8, 200)

    // flower
    fill('red')
    circle(120, 30, 50)

    // leaves
    ellipse(173, 120, 40, 20)
    ellipse(123, 130, 40, 20)
    
Now, imagine we first wrote the code for stem and leaves, than later added the code for the flower (in the reference, copied it from elsewhere). The code has a bug in it - the leaves are red. This is just one example: once you have a "hidden" state, you have to manage it. You always have to be aware of the effects that every line makes on the state and how the state affects the other lines. A "React"-like (simply declarative) API would look more like:

   stem = filled('green', rect(146, 60, 8, 200))
   flower = filled('red', circle(120, 30, 50))
   leaves = [
     filled('green', ellipse(173, 120, 40, 20))
     filled('green', ellipse(123, 130, 40, 20))
   ]
   plant = [stem, flower].concat(leaves)
   ...
   draw(plant)
The code is now referentially transparent, I could replace uses of variables by their values and nothing would change, since the functions have no effects. The effects are pushed to the edge of the code, in this case the call to draw which actually performs the drawing, or when React updates the DOM with the results obtained from a render method.

http://worrydream.com/#!/LearnableProgramming



Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: