Using functions as parameter or use them directly in clojure?

Viewed 88

i have this two functions and i use share-card-to-player in share-cards. Should i not rather pass share-card-to-player as argument or use it as anonymous function?

In the way, i am using it, i doubt, that i am using it in a functional way, because i am basically referencing to a global variable namely the function share-card-to-player. Is that assumption correct?

(defn share-card-to-player [game [player cards]]
  (assoc-in game [:players player :cards ]
            cards))

(defn share-cards [{players :players cards :cards :as game}]
  (reduce share-card-to-player game
          (map vector
               (keys players)
               (->>  cards
                     (partition (/ (count cards)
                                   (count players)))))))
2 Answers

i am basically referencing to a global variable namely the function share-card-to-player

assoc-in is a global variable. / is a global variable. count is a global variable. Should you avoid them all? It will be tough to get anything done! The problem with globals is mutation, and functions are not mutable.

You can define share-card-to-player as an anonymous local function if you want. But it's fine as is. Extracting it as a function parameter would make sense only if you expect you would want to pass another function to it at another use site.

Passing in the function as a parameter would only make sense to me if you plan to pass in different functions in other parts of your program to change the behavior of share-cards.

In your particular example, I'd even consider factoring out the call to map if you can give a good name to that thing because it takes longer to read and understand that code.

To summarize:

  • Functions as parameter should change the behavior.
  • Factoring out things to their own functions, even if only used in one place of your program, makes sense if you can give a good name to what the code does.
Related