Piping data through arbitrary functions in Clojure

前端 未结 3 1963
长发绾君心
长发绾君心 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-07 23:08

    You can do this with a plain old reduce:

    (defn pipe [x fs] (reduce (fn [acc f] (f acc)) x fs))
    

    That can be shortened to:

    (defn pipe [x fs] (reduce #(%2 %1) x fs))
    

    Used like this:

    user> (pipe [1 2 3] [#(conj % 77) rest reverse (partial map inc) vec])
    [78 4 3]
    

提交回复
热议问题