Dynamic variables in Clojure libraries

TL DR: Is the following template a good library?

(def ^{:dynamic true} *var*)
(defn my-fn [{:keys [var]}]
  (do-smth (or var *var*)))

-

Let's say I want to write a mood analysis library.

Is it a good construction in get-sentimentfn to accept additional mood labels, but provide the default one as a dynamic var?

(def ^:dynamic *sentiment-level-labels*
  ["Very Negative" "Negative" "Neutral" "Positive" "Very Positive"])

;;...

(defn get-sentiment-scores
  "Takes text and gives back a 0 to 4 sentiment score for each sentences."
  [text]
  ;;...)

(defn get-sentiment 
  "Gives back a sentiment map with sentences scores, 
   average score, rounded score and labeled score.
   Can accepts custom sentiment level labels under :labels opt."
  [text & {:keys [labels]}]
  (let [scores (get-sentiment-scores text)
        average-score (get-average scores)
        rounded-score (Math/round average-score)
        label (get (or labels *sentiment-level-labels*) rounded-score)]
    {:scores scores
     :average-score average-score
     :rounded-score rounded-score
     :label label}))

Clojure The official library coding standards page states:

If you imagine an interface that implicitly passes a parameter through dynamic binding (e.g. db in sql), they also provide an identical interface but with an explicitly passed parameter.

https://dev.clojure.org/display/community/Library+Coding+Standards

In my example, I provided only one interface, but with the argument opt.

This is normal? Are there any better ways to handle this?

Thank!

+4
1

. API (binding ...), , , . , .

params:

(def default-sentiment-level-labels
  ["Very Negative" "Negative" "Neutral" "Positive" "Very Positive"])

(defn get-sentiment 
  "Gives back a sentiment map with sentences scores, 
   average score, rounded score and labeled score.
   Can accepts custom sentiment level labels under :labels opt."
  [text {:as params, :keys [labels] :or {labels default-sentiment-labels}}]
  ...))

, , : , params , .

+3
source

Source: https://habr.com/ru/post/1689316/


All Articles