Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing C-style encapsulation techniques in Clojure?
    primarykey
    data
    text
    <p>I am working on my first (non-trivial) <a href="http://code.google.com/p/stacked-crooked/source/browse/trunk/PlayGround/Clojure/Tetris.clj" rel="nofollow noreferrer">Clojure program</a> I don't really feel comfortable with how I am declaring all my mutable state globally. For example:</p> <pre><code>(def next-blocks (atom [])) (def num-next-blocks 1) (def is-game-over (atom false)) (def user-name (atom (str))) (def hs-xml (atom nil)) </code></pre> <p>Since I use C a lot at work I came up with the idea of using common C-style encapsulation techniques. It typically involves struct object that passed as a first argument to any "member functions" that operate on it. See <a href="http://www.kernel.org/pub/linux/utils/kernel/hotplug/libudev/libudev-udev-device.html" rel="nofollow noreferrer">udev</a> for example.</p> <p>Applying this to Clojure would result in functions that look like this (untested):</p> <pre><code>(defstruct gamestate) (defn game-new [] (struct-map gamestate :level (atom 0) :score (atom 0) ;etc... )) (def game-get-score [game] @(game :score)) (defn game-set-score [game new-score] (reset! (game :score) new-score)) (defn game-get-level [game] @(game :level)) (defn game-inc-level [game] (swap! (game :level) inc)) ; etc... </code></pre> <p>I think it would definitely be a step forward to the global defines that I'm using currently.</p> <p>So is this the recommended way to go? Or is there a more standard Clojure way?</p> <h3>Update</h3> <p>I'm currently using Clojure 1.1.0.</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