(use 'inheritance.grid) (def grid (make-grid-hierarchy)) (defmulti canFly " " (grid-dispatch1) :hierarchy #'grid) (defmulti canFireball " " (grid-dispatch1) :hierarchy #'grid) (defmulti canFire " " (grid-dispatch1) :hierarchy #'grid) (defmethod canFly (get-grid-node {} #'grid) [p] false) ; (defmethod canFly (get-grid-node {:magic :air} #'grid) [p] true) ; - (defmethod canFly (get-grid-node {:limbs :wings} #'grid) [p] true) ; (defmethod canFireball (get-grid-node {} #'grid) [p] false) ; (defmethod canFireball (get-grid-node {:magic :fire, :limbs :hands} #'grid) [p] (> (:mana p) 0)) ; - , . (defmethod canFire (get-grid-node {} #'grid) [p] false) ; , , (defmethod canFire (get-grid-node {:limbs :hands} #'grid) [p] true) ; (defmethod canFire (get-grid-node {:magic :fire} #'grid) [p] (> (:mana p) 0)) ; (defmethod canFire (get-grid-node {:magic :fire, :limbs :hands} #'grid) [p] true) ; - Clojure , (def mage ((with-grid-node {:magic :fire, :limbs :hands :race :mage} #'grid) {:mana 100, :power 5})) (def barbar ((with-grid-node {:magic :none, :limbs :hands :race :human} #'grid) {:power 500})) (def phoenix ((with-grid-node {:magic :fire, :limbs :wings :race :mage} #'grid) {:mana 200, :power 4})) (def elf ((with-grid-node {:magic :air, :limbs :hands :race :elf} #'grid) {:mana 300, :power 13})) (canFire elf) ; true (canFireball elf) ; false (canFly elf) ; true (canFly mage) ; false (canFire mage) ; true
(defn make-grid-hierarchy " " [] (let [h (make-hierarchy)] ; (with-meta h (assoc (or (meta h) {}) :grid-hierarchy-cache {})))) ;
(defn register-grid-node " " [ho] (let [nl (get (meta h) :grid-hierarchy-cache {})] (if-let [s (nl o)] ; [hs] ; (let [s (symbol (str o)) ; - hn (reduce (fn [h [tr n]] ; (if (and (subobj? tr o) ; (not (isa? hsn))) ; Clojure , ; (derive hsn) (if (and (subobj? o tr) (not (isa? hns))) ; (derive hns) h))) h nl)] [(with-meta hn ; (assoc (or (meta h) {}) :grid-hierarchy-cache (assoc nl os))) s])))) ;
(defn with-grid-node " , " [nh] (let [s (get-grid-node nh)] (fn [v] (with-meta v (assoc (or (meta v) {}) :grid-node s)))))
(defn grid-dispatch " " [] (fn [& v] (vec (map (fn [a] (:grid-node (meta a))) v)))) (defn grid-dispatch1 " " [] (fn [v & _] (:grid-node (meta v))))
Source: https://habr.com/ru/post/242649/
All Articles