change struct-object state

空扰寡人 提交于 2019-12-24 10:13:33

问题


I would like to change the state of the objects andre and blastoise, adding a new property(attribute/state) to the object... the name of this new property I want to add is "tax". I tryed the code below but didnt work out... help me 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)))
    )
)

(calculate-car-tax car-tax)


回答1:


try

(assoc andre :tax 20)

From the docs:

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=> 

Edit to include function:

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


来源:https://stackoverflow.com/questions/7630474/change-struct-object-state

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!