Piping data through arbitrary functions in Clojure

前端 未结 3 1965
长发绾君心
长发绾君心 2021-01-07 22:10

I know that the -> form can be used to pass the results of one function result to another:

(f1 (f2 (f3 x))) 
(-> x f3 f2 f1) ; equivalent          


        
3条回答
  •  独厮守ぢ
    2021-01-07 23:09

    If functions is a sequence of functions, you can reduce it using comp to get a composed function. At a REPL:

    user> (def functions (list #(* % 5) #(+ % 1) #(/ % 3)))
    #'user/my-list
    user> ((reduce comp functions) 9)
    20
    

    apply also works in this case because comp takes a variable number of arguments:

    user> (def functions (list #(* % 5) #(+ % 1) #(/ % 3)))
    #'user/my-list
    user> ((apply comp functions) 9)
    20
    

提交回复
热议问题