How do I create a list and return it to clojure?

I am still studying this alien functional paradigm ...

How to write the following code in Clojure and in a functional way? suppose these missing parts are defined elsewhere and behave as described in the comments. Here it is in Python, which I am familiar with.

usernames = []
# just the usernames of all the connections I want to open.
cancelfunctions = {}
# this global contains anonymous functions to cancel connections, keyed by username

def cancelAll():
    for cancel in cancelfunctions.values():
        cancel()

def reopenAll():
    cancelfunctions = {}
    for name in usernames:
        # should return a function to close the connection and put it in the dict.
        cancelfunctions[name] = openConnection()

All I really need to know is to create a new type of callbacks, for example, in the reopenAll function, but I have included a few more contexts in it, because most likely I am committing some kind of cruelty to the functional paradigm and you most likely , want to fix the whole program. :)

+5
source share
2 answers

Clojure reduce, , . , ( ) open-connection.

;; Using reduce directly
(defn reopen-all [usernames]
  (reduce
   (fn [m name] (assoc m name (open-connection)))
   {} usernames))

;; Using into, which uses reduce under the hood
(defn reopen-all [usernames]
  (into {} (for [name usernames]
             [name (open-connection)])))

, , Python. , . , , atom:

(def usernames [...])
(def cancel-fns (atom nil))

(defn init []
  (reset! cancel-fns (reopen-all usernames)))

cancel-all :

(defn cancel-all []
  (doseq [cancel-fn (vals @canel-fns)]
    (cancel-fn)))
+6

python:

def reopen(usernames):
    return dict((name, openConnection()) for name in usernames)

"" python, - .

+2

All Articles