Search code examples
clojure

What data structure to use for implementing a library management system


I'm new to functional programming and am currently at the end of "Getting Clojure" book. Since most of the examples in the book refer to books/library management, i thought of implementing a library management system as a project to help me learn and clear the concepts. I would like some advise on what would be the best data structure to hold the library - I'm thinking of either a vector of book maps or a map of book maps. Maps are easy to lookup. Vectors can be accessed quickly as well. I'm thinking of

{:ISBN {:title "Book title" :edition 1 :publisher "ABC publishing"}}

this way the lookup will be on ISBN number, but i would also like to lookup using book title ..but not sure how. Any help, suggestions, advise would be greatly appreciated.


Solution

  • You can use the index function in clojure.set:

    (require '[clojure.set :as set])
    
    (def library #{{:title "Book title" :edition 1 :publisher "ABC publishing" :isbn "1234"}
                   {:title "A title" :edition 2 :publisher "123 publishing" :isbn "4321"}})
    
    (def by-isbn (set/index library [:isbn]))
    
    (by-isbn {:isbn "1234"})
    ;; => #{{:title "Book title", :edition 1, :publisher "ABC publishing", :isbn "1234"}}
    
    (def by-title (set/index library [:title]))
    
    (by-title {:title "A title"})
    ;; => #{{:title "A title", :edition 2, :publisher "123 publishing", :isbn "4321"}}