Clojure: pvalues โ€‹โ€‹vs pcalls

I read the Joy of Clojure , and in the section on the parallelization of functions pvalues, pmapand pcalls, with a brief example of the use of each of them. The following are examples for pvaluesand pcalls:

(defn sleeper [s thing] (Thread/sleep (* 1000 s)) thing)

(pvalues
  (sleeper 2 :1st)
  (sleeper 3 :2nd)
  (keyword "3rd"))

(pcalls
  #(sleeper 2 :1st)
  #(sleeper 3 :2nd)
  #(keyword "3rd"))

I understand the technical difference between the two - it pvaluestakes a variable number of "values" that need to be calculated, while it pcallsaccepts an "arbitrary number of functions that take no arguments" that need to be called in parallel. In both cases, a lazy sequence of results returns.

My question is essentially, when will you use one against the other? It seems that the only semantic difference is that before each argument pcallsyou insert #, turning it into an anonymous function. So, purely in terms of saving keystrokes and simpler code, does it make sense to just use it pvalues? - and if so, why is there even a function pcalls?

I get this with pcalls, you can replace the character with a function reference, but if you want to use such a function with pvalues, you can simply put the function in parentheses so that it is called.

, Clojure 2 , . -, , ? .

+4
1

pvalues โ€‹โ€‹- convienience pcalls, , , , . , pcalls:

user> (defn sleeper [s thing] (Thread/sleep (* 1000 s)) thing)
#'user/sleeper

user> (def actions [#(sleeper 2 :1st) #(sleeper 3 :2nd) #(keyword "3rd")])
#'user/actions

user> (apply pcalls actions)
(:1st :2nd :3rd)

user> (apply pvalues actions)
CompilerException java.lang.RuntimeException: Can't take value of a macro: #'clojure.core/pvalues, compiling:(NO_SOURCE_PATH:1:1)

API clojure, , , .

+6

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


All Articles