Clojure thread operator

Suppose I want to use a streaming operator to stream a card through a series of function calls. All functions accept the mapping as the first parameter (good), but one function does not match the correct signature (say, it takes a map as the last parameter). What is the best way to "fix" a function signature?

+6
source share
3 answers

The reader macro #() for anonymous functions is a good candidate here:

 (-> your-arg (fn1 arg2 arg3) (fn2 arg4 arg5) (#(fn3 arg6 arg7 %)) ) 

It is flexible and adds a bit of visual noise. Of course, you can do many different things, in this case the application with the partial function will also work:

 (-> your-arg (fn1 arg2 arg3) ((partial fn2 arg4 arg5))) 

There is also a macro ->> , which processes the first expression in the last position. Of course, this doesn’t help much in your use case, since you have to adjust some function calls. However, if you chain many functions that should take an expression as the first argument, and then many functions that take an expression as the last argument, you could do something like

 (->> (-> your-arg (fn1 arg2 arg3) (fn2 arg5 arg6)) (fn3 arg7 arg8) (fn4 arg10 arg11)) 

EDIT: In the first example, an extra bracket is added.

+8
source

I think that people tend to underestimate the kind of stream operators available in clojure. So let me introduce you to the as-> threading operator.

In the as-> stream, a variable is created that takes the value of each function call in the streaming stages. Example,

 (as-> 2 x ;; x = 2 (+ 3 x) ;; x = 5 (- x 1) ;; x = 4 (/ x 2) ;; x = 2 (+ xxx)) ;; x = 6 

The output of the above operation is x ie 6.

+4
source
 (-> your-arg (fn1 arg2 arg3) (fn2 arg5 arg6) (->> (fn3 arg7 arg8) (fn4 arg10 arg11))) 

It seems nicer than the version with ->> "before" -> , for me. Another thing you can do is write some basic argument reordering functions and use them to create versions of fn3 and fn4 that take their arguments in the order you want.

+1
source

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


All Articles