Vector – clojure – define a data structure for a person
•
Java
In other languages, how to create structures is very self - evident How would you do such a thing in clojure?
For example, I want to add a person's name, address and phone number (home and mobile)
I guess I want to make a carrier?
Thank you in advance!
Solution
In clojure, you usually use maps to represent this data You can use a flat map:
{:first-name "Jeremy" :last-name "Martinson" :street "455 Larkspur Dr." :city "Baviera" :state "California" :zip 22611 :home-phone "(555) 555-5555" :mobile-phone "(666) 666-6666"}
Or nested:
{:name {:first "Jeremy" :last "Martinson"} :address {:street "455 Larkspur Dr." :city "Baviera" :state "California" :zip 22611} :phones {:home "(555) 555-5555" :mobile "(666) 666-6666"}}
If your data has more or less static schema and you want to use clojure's polymeric features, you can use records:
(defrecord Name [first last]) (defrecord Address [street city state zip]) (defrecord Phones [home mobile]) (defrecord Person [name address phones]) (map->Person {:name (map->Name {:first "Jeremy" :last "Martinson"}) :address (map->Address {:street "455 Larkspur Dr." :city "Baviera" :state "California" :zip 22611}) :phones (map->Phones {:home "(555) 555-5555" :mobile "(666) 666-6666"})})
However, in this case, you may only want to use the map Especially the phone records are very ugly
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码