将函数序列应用于值序列 [英] Applying sequence of functions to a sequence of values

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

问题描述

我想成对地将函数列表应用于值列表.

I want to pairwise apply a list of functions to a list of values.

这里有一个例子来说明.

Here's an example to illustrate.

user=> (defn a [f x] (f x))
#'user/a
user=> (map a [inc dec] '(98 8))
(99 7)

注意我必须定义一个函数 a ,它接受一个函数并将其应用于一个值.基本上是抽象函数应用.

Notice I had to define a function a that takes a function and applies it to a value. Basically abstracting function application.

有没有更自然的方法来做到这一点?我真的很想使用 map 来定义一个辅助函数.

Is there a more natural way to do this? I would really just like to use map with defining a helper function.

推荐答案

你总是可以匿名定义函数,内联:

You can always define functions anonymously, inline:

(map (fn [f x] (f x)) [inc dec] '(98 8))

或更短,使用#() 阅读器宏:

or shorter, using the #() reader macro:

(map #(%1 %2) [inc dec] '(98 8))

尽管这是一个相当尴尬的用例,所以我怀疑您是否可以仅使用核心 clojure 或 clojure.contrib 将其缩短为更短的内容,但您可以轻松编写自己的抽象:

It's a fairly awkward use case though, so I doubt you can reduce it to something shorter using just core clojure or clojure.contrib, but you can easily write your own abstraction:

(defn mapfs [fs coll] (map #(%1 %2) fs coll))
(mapfs [inc dec] [98 8])
> (99 7)

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

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