Explain the core.reducers library to a layman

I am currently studying clojure for fun, and today I come across this article about gearboxes . I find it not only interesting, but also difficult for me. As a beginner:

  • I know how to use core map , filter , reduce

  • I understand that core/map , core/filter ... returns a sequable col

  • Rick Hickey mentioned core.reducers/map ... return a reducible col

Since the implementation of core/map ... and core.reducers/map ... looks very identical. My question is:

  • How does reducible col make a difference in a non- reducible term?

  • Can someone give me trivial examples of reducible function?

Thank you very much

+6
source share
1 answer

For me, the main idea of ​​reducers is that they are actually smaller than map / filter / reduce . Gearboxes do not indicate whether they are executed lazily or impatiently, sequentially or in parallel, in a collection or in another type of data structure, and what they produce may be a collection or something else. Examples:

  • map / filter / reduce you must pass the collection and produce the Collection ; gearbox should not do either. This idea of ​​reducers is extended to transducers so that the same converter can be applied to the collection or channel core.async .

  • Gearboxes also do not indicate how they are performed. map / filter / reduce always executed sequentially through the collection; never in parallel. If you want to execute in parallel, you must use another function: pmap . You could assume that if you want to filter in parallel, you can also create a pfilter function (this does not exist, but you can write it). Instead of creating a parallel version of each function, the reducers simply say “I don't care how I execute”, and to another function ( fold in the case of reducers) to decide whether execution should run in parallel or not. fold is more general than pmap , because the reducers to which it applies can do filtering or matching (or are designed for both).

In general, since gearboxes make fewer assumptions about what they apply to , what they produce or how they are applied , they are more flexible and therefore can be used in a wide variety of situations. This is useful because reducers focus on "what your program does," rather than "how it is done." This means that your code can evolve (for example, from one thread to a multi-threaded or even to a distributed application) without having to touch the part of the program that forms the main logic of what your code does.

+2
source

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


All Articles