2010-06-08 18 views
5

का एक वेक्टर में कुंजी का उपयोग करते हैं मैं है structs के निम्नलिखित वेक्टर:Clojure में - मैं कैसे structs

(defstruct #^{:doc "Basic structure for book information."} 
    book :title :authors :price) 

(def #^{:doc "The top ten Amazon best sellers on 16 Mar 2010."} 
    best-sellers 
    [(struct book 
      "The Big Short" 
      ["Michael Lewis"] 
      15.09) 
    (struct book 
      "The Help" 
      ["Kathryn Stockett"] 
      9.50) 
    (struct book 
      "Change Your Prain, Change Your Body" 
      ["Daniel G. Amen M.D."] 
      14.29) 
    (struct book 
      "Food Rules" 
      ["Michael Pollan"] 
      5.00) 
    (struct book 
      "Courage and Consequence" 
      ["Karl Rove"] 
      16.50) 
    (struct book 
      "A Patriot's History of the United States" 
      ["Larry Schweikart","Michael Allen"] 
      12.00) 
    (struct book 
      "The 48 Laws of Power" 
      ["Robert Greene"] 
      11.00) 
    (struct book 
      "The Five Thousand Year Leap" 
      ["W. Cleon Skousen","James Michael Pratt","Carlos L Packard","Evan Frederickson"] 
      10.97) 
    (struct book 
      "Chelsea Chelsea Bang Bang" 
      ["Chelsea Handler"] 
      14.03) 
    (struct book 
      "The Kind Diet" 
      ["Alicia Silverstone","Neal D. Barnard M.D."] 
      16.00)]) 

I would like to sum the prices of all the books in the vector. What I have is the following: 

(defn get-price 
    "Same as print-book but handling multiple authors on a single book" 
    [ {:keys [title authors price]} ] 
    price) 

तब मैं:

(reduce + (map get-price best-sellers)) 

वहाँ मानचित्रण के बिना ऐसा करने का एक रास्ता है वेक्टर पर "गेट-प्राइस" फ़ंक्शन? या क्या इस समस्या के करीब आने का एक बेवकूफ तरीका है?

+0

आपकी विधि इस समस्या के करीब आने का बेवकूफ तरीका है। –

+0

'defstruct' को शायद 'defrecord' /' deftype', FYI द्वारा बहिष्कृत/अतिरंजित किया जा रहा है। http://groups.google.com/group/clojure/msg/330c230e8dc857a9 –

उत्तर

6

क्लोजर 101-संबंधित प्रश्न देखने के लिए अच्छा लगा! :-)

आप :pricebest-sellers पर मानचित्र कर सकते हैं; यह संभवतया उस अंतर को अधिक से अधिक नहीं बनायेगा जब तक यह कोड बेवकूफ है। अधिक जटिल परिदृश्यों में, get-price जैसे कुछ का उपयोग करना बेहतर शैली हो सकता है और रखरखाव में मदद कर सकता है।

कोड में संभवतः अधिक गहरा परिवर्तन के लिए, यह वास्तव में इसे लिखने का सबसे साफ तरीका है। एक वैकल्पिक एक कस्टम कमी समारोह लिखने के लिए होगा:

(reduce (fn [{price :price} result] (+ price result)) 
     0 
     best-sellers) 

यह मूलतः map और एक साथ reduce विलीन हो जाती है; कभी-कभी यह उपयोगी होता है, लेकिन आम तौर पर, अलग-अलग, अच्छी तरह से परिभाषित चरणों में अनुक्रम के परिवर्तन को तोड़ने में पठनीयता & रखरखाव में मदद करता है और जाने का डिफ़ॉल्ट तरीका होना चाहिए। इसी तरह की टिप्पणियां मेरे दिमाग में आने वाले सभी अन्य विकल्पों पर लागू होती हैं (loop/recur सहित)।

सब कुछ, मैं कहूंगा कि आपने इसे खींचा है। यहां कोई बदलाव नहीं किया जाना चाहिए। :-)

+0

आपकी त्वरित प्रतिक्रिया मीकल के लिए धन्यवाद। – Nick