Using C style encapsulation methods in Clojure?

I'm working on my first (non-trivial) Clojure program. I really don't like the way I announce all of my volatile state around the world. For instance:

(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))

Since I use C a lot, I came up with the general C-style encapsulation methods. Usually it includes a struct object, which is passed as the first argument to any "member functions" that work on it. See udev , for example.

Applying this to Clojure will give you functions that look like (unverified):

(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...

I think this will definitely be a step forward towards the global definitions that I am currently using.

So is this the recommended way? Or is there a more standard way to Clojure?

Update

Clojure 1.1.0.

+3
3

, , (. Rich Hickey ). , ( ).

, . , .

(defn play-game [name score blocks]
  (let [level (start-mission (:level score) blocks)]
    (if level
      (assoc score :level level)
      score)))

(defn the-whole-game []
  (let [name (ask-username)
        score (or (load-score name) {:level 0, :score 0}]
    (when-let [new-score (play-game name score [])]
       (save-score name new-score))))

Tetris clojure, opengl.

+6

Clojure , , . .

:

(def state 
  (atom 
    {:game (gamefactory/make-game)
     :scroll [0 0]
     :mouseover [0 0]
     :command-state nil
     :commands (clojure.lang.PersistentQueue/EMPTY)
     :animations {}
     :player-id nil}))

. , . (: game @state) .

+4

C. ( v1.2), deftype/defrecord.

(defn get-game-score [game]
   (:score game))

(defn set-game-store [game new-score]
   (assoc game :score new-score))

Map esp. .
, , clojure , C, .

+2

Source: https://habr.com/ru/post/1754269/


All Articles