Clojure pmap returns different results than map

I am learning clojure and implementing my standard Tic Tac Toe 10 test project . I have written the same AI in many languages ​​before and I had problems scaling it beyond 6 moves forward in other languages ​​as well.

I got the AI ​​algorithm mostly, but I'm trying to improve the speed with pmap. Since everything is immutable, I should be able to just insert pmap instead of the map and get the same results, but I can't see that.

(defn get-spot
  [board player win-cond levels]
  (def avail (get-available board))
  (def final
    (apply merge
           (map #(array-map % (calc-score board player win-cond levels %)) avail)))
  final)

      

But pmap returns inconsistent results at this point. Not sure where to start looking. I can post more code if needed.

+3


source to share


2 answers


Replacing def everywhere solved the problem. My functions had a lot of inconsistent side effects if I didn't use let.

(defn get-spot
  [board player win-cond levels]
  (let [avail (get-available board)
        final (apply merge
           (pmap #(array-map % (calc-score board player win-cond levels %)) avail))]
  final))

      



I wrote a bunch of clojure code and read a lot of tutorials. I don't know how I missed this very important detail.

+1


source


Please read a book or two about clojure before you even think about performance tuning. The inevitability built into the language doesn't mean you can just replace the map with pmap.

Two other things to consider are the absence of side effects for your code and the fact that the operations must be commutative. If this is not the case, you will have to account for this in the merge algorithm.

As others have already said, don't create def

bindings insider functions , use instead let

. Also, the last expression will be returned from the function anyway, so you don't need to chain final

before returning it.



I'm sorry I didn't give a direct solution to your problem, I just think you need to understand that replacing a card is not as easy as it might seem.

If you still want your problem solved, I think we need to see more code here.

-1


source







All Articles