简体   繁体   中英

Clojure: How to execute a sequence of functions?

I have a sequence of functions (which mutate some objects) I'd like to execute, which works if I do this:

(foo1)
(foo2)
(foo3)

However, I want to put this code in a function so I can execute this sequence whenever I want. If I do this:

(defn run-foos [] (do (foo1) (foo2) (foo3)))

The mutations created by run-foos is not the same as the 3 separate statements earlier. I apologize that I can't concisely summarize the behavior of my program here, but basically I see there is some behavioral differences between the first and second versions of the code above.

What I want to do is have a function run-foos that will execute foo1 , foo2 , and foo3 that runs exactly like I called each one individually in a row. How can I do this?

Without seeing the rest of your code, the difference here is not obvious (in general the two are the same).

The only reason there should be any difference between the two pieces of code you have is if the first one was entered at the repl and foo1 or foo2 returned a lazy result of some sort. In that case the repl will have forced the lazy result while printing it, and run-foos would not have.

If that is your problem, then it would be better to keep using run-foos but refactor your other functions so that they don't mix side-effects and laziness.

This variant will work only with mutable data.

(defn run-foos [] (do (foo1) (foo2) (foo3)))

But standard clojure data structures are immutable. So, every time when your data pass throught function independetly, functions will be work with default data, which with no mutate by function. Furthermore, run-foos will return data from only last expresion, ie (foo3).

«The values of all but the last expression are discarded, although their side effects do occur.» (Emerick, Carper, Grand: Clojure programming, 2012)

I think that you need thread-macro:

(-> data
    foo1
    foo2
    foo3)

It expands to (foo3 (foo2 (foo1 data))) at compile-time. Data will passed to functions along the chain and you will get what you want.

To read about -> macro with examples here: https://clojuredocs.org/clojure.core/-%3E

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM