What function should be used if you want to get both a side effect and save the value in Clojure?

People say that avoid using map to perform side effects on a sequence, and that makes sense.

But in the real world I need to both save the result and evaluate the map with impatience, i.e. when pasting in db and returning a record.

Is there (doall (map ..)) my only choice here? Is there a more idiomatic way to do this?

+5
source share
2 answers

I would use (doall (map ..)) , as you stated, since it is clear that the intention is in your code. mapv works, although the intention is a bit more ambiguous.

+3
source

No. (doall (map ..)) not your only choice: mapv not lazy, so it effectively performs (doall (map ..)) , but in one operation.

It’s nice to use either map or mapv with a display function that creates side effects. Instead, try using doseq , which clearly indicates side effects. As you point out, and this concerns the main problem, the problem with doseq is that the return results are not gathered together for you in the sequence as they are with map or mapv .

If you don’t need a lazy sequence, try not to produce it first, not to produce it, and then make it realize how you are doing now. Therefore, we must eliminate the use of map .

Most cases where you do not need laziness are covered with mapv , when your map function does not affect side effects, or doseq when it is, but does not return a result.

If your map function produces a result and is a side effect, and you want these results to be put together, the best option would be to use mapv over the map function, which is called as explicitly creating a side using a name ending in ! . Although it’s not very convenient to use mapv , at least ! clearly emphasizes what is happening.

+5
source

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


All Articles