如何将值应用于Clojure中的多个函数? [英] How to apply values to multiple functions in Clojure?

查看:66
本文介绍了如何将值应用于Clojure中的多个函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我需要做类似 map 的操作,但是我不需要将函数应用于集合中的所有元素,而是需要应用相同的(一组)值(s)到一组功能(此操作是否有名称?)。这似乎是一个简单的问题,但是我在Clojure中还没有找到惯用的方法。例如,在特殊情况下,我只需要对每个函数应用一个值,

Basically, I need to do something like map, but instead of applying a function to all elements in a collection, I need to apply the same (set of) value(s) to a collection of functions (does this operation have a name?). This might seem like a simple question, but I haven't found an idiomatic way to do it in Clojure. For the special case where I need to apply only one value to each function, for example, I have used

(for [f funs] (f value))

其中当然是我需要每个函数作为参数的值,而 funs 是需要用调用的函数的集合。 value 作为参数。

where value is, of course, the value I need each function to take as an argument, and funs is the collection of functions which need to be called with value as the argument.

那么我的问题是,Clojure中是否有一个函数可以做到这一点,但也可以泛化为任意数量的参数?还是上面的确是惯用的Clojure?

My question is, then, is there a function in Clojure that does this, but is also generalised for arbitrary numbers of arguments? Or is the above indeed idiomatic Clojure?

推荐答案

您在寻找 juxt


juxt

采用一组函数并返回一个fn,该fn与这些fns并置
。返回的fn具有可变数量的args,
返回一个向量,其中包含将每个fn应用于
args(从左到右)的结果。
((juxt a b c)x)=> [(a x)(b x)(c x)]

Takes a set of functions and returns a fn that is the juxtaposition of those fns. The returned fn takes a variable number of args, and returns a vector containing the result of applying each fn to the args (left-to-right). ((juxt a b c) x) => [(a x) (b x) (c x)]

这篇关于如何将值应用于Clojure中的多个函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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