通过Clojure中的任意函数管道数据 [英] Piping data through arbitrary functions in Clojure
问题描述
我知道 - >
表单可用于将一个函数结果的结果传递给另一个:
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 to the line above
(取自很好的Clojure教程在ociweb )
但是这个表单要求你知道您想在设计时使用的功能。我想做同样的事情,但在运行时有一个任意函数列表。
However this form requires that you know the functions you want to use at design time. I'd like to do the same thing, but at run time with a list of arbitrary functions.
我写了这个循环函数,但我有一个感觉有一个更好的方法:
I've written this looping function that does it, but I have a feeling there's a better way:
(defn pipe [initialData, functions]
(loop [
frontFunc (first functions)
restFuncs (rest functions)
data initialData ]
(if frontFunc
(recur (first restFuncs) (rest restFuncs) (frontFunc data) )
data )
) )
这是最好的方法是什么?
What's the best way to go about this?
推荐答案
我必须承认我真的很新clojure,我可能在这里完全失去了点,但不能这只是使用comp和apply应用?
I must admit I'm really new to clojure and I might be missing the point here completely, but can't this just be done using comp and apply?
user> (defn fn1 [x] (+ 2 x))
user> (defn fn2 [x] (/ x 3))
user> (defn fn3 [x] (* 1.2 x))
user> (defn pipe [initial-data my-functions] ((apply comp my-functions) initial-data))
user> (pipe 2 [fn1 fn2 fn3])
2.8
这篇关于通过Clojure中的任意函数管道数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!