改变struct-object状态

时间:2011-10-03 01:57:18

标签: clojure

我想更改对象andre和blastoise的状态,向对象添加一个新属性(属性/状态)...我要添加的这个新属性的名称是“tax”。我尝试了下面的代码,但没有成功...帮助我PLZ:

(def andre {:owner "Andre" :type "car" :cur-speed 101 :license-plate "ABC"})
(def blastoise {:owner "Blastoise" :type "truck" :cur-speed 120 :license-plate "XYZ"})
(def car-tax[andre blastoise])
(defn calculate-car-tax [v]
    (for [element v] 
        (if (> (element :cur-speed) 100) (dosync (alter element tax :20)))
    )
)

(计算 - 汽车税车税)

1 个答案:

答案 0 :(得分:3)

(assoc andre :tax 20)

来自文档:

user=> (doc assoc)
-------------------------
clojure.core/assoc
([map key val] [map key val & kvs])
  assoc[iate]. When applied to a map, returns a new map of the
    same (hashed/sorted) type, that contains the mapping of key(s) to
    val(s). When applied to a vector, returns a new vector that
    contains val at index. Note - index must be <= (count vector).
nil
user=> 

编辑以包含功能

(defn calculate-car-tax [v]                                                                                                                                                                                                                                                     
  (for [element v]                                                                                                                                                                                                                                                          
    (if (> (element :cur-speed) 100) 
      (dosync (assoc element :tax 20)))))