Clojure call series of functions and store their return values

帅比萌擦擦* 提交于 2020-05-15 09:33:07

问题


I'm building a datomic schema and have the following at the foot of my clj file which defines and transacts schema and initial data. The functions being called below each call d/transact.

(defn recreate-database []
  "To recreate db after running delete-database in bin/repl"
  (pt1-transact-schema)
  (pt1-transact-data)
  (pt2-transact-schema)
  (pt2-transact-data)
  (pt3-transact-schema)
  (pt3-transact-data))

By default we only see the return value of the last form, but I'd like to see, or save, the result of each of the six function calls.

Wondering what a nice way to do this is.

Thought of something like (map (comp println eval) [functions]), but that's not right.


回答1:


there is also a nice functional composition function called juxt:

user> ((juxt + - * /) 1 2)
;;=> [3 -1 2 1/2]

user> ((juxt (constantly 1) (constantly 2) (constantly 3)))
;;=> [1 2 3]

or in your case:

(def recreate-database (juxt pt1-transact-schema
                             pt1-transact-data
                             pt2-transact-schema
                             pt2-transact-data
                             pt3-transact-schema
                             pt3-transact-data))



回答2:


You could try this:

(defn recreate-database []
  "To recreate db after running delete-database in bin/repl"

  (mapv #(%) [pt1-transact-schema
              pt1-transact-data
              pt2-transact-schema
              pt2-transact-data
              pt3-transact-schema
              pt3-transact-data]))

The expression #(%) is a shorthand notation for a lambda function that takes one argument, representing a function, and calls that function. If you find it more readable, you can replace that expression by (fn [f] (f)).




回答3:


With datomic, all you need is a connection and a list of tx-data. Then you can use map to return the transact result on each step (i.e. each tx-data):

(defn recreate-database [conn & tx-data]
  (->> tx-data
       (map (partial d/transact conn))
       doall))


来源:https://stackoverflow.com/questions/61636534/clojure-call-series-of-functions-and-store-their-return-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!