通过 Clojure 中的任意函数传输数据 [英] Piping data through arbitrary functions in Clojure

查看:12
本文介绍了通过 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

(摘自 ociweb 上的优秀 Clojure 教程)

但是,此表单要求您知道在设计时要使用的功能.我想做同样的事情,但在运行时使用任意函数列表.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆