是否有反向映射函数? [英] Is there a reverse-map function?
问题描述
在clojure中,您可以将函数映射到值序列。是否有内置函数将单个值映射为函数序列的参数?
In clojure you can map a function to a sequences of values. Is there an inbuilt function to map a single value as parameter to a sequence of functions?
(map inc [1 2 3 4])
; -> (2 3 4 5)
(reverse-map [inc dec str] 1)
; -> (2 0 "1")
(reverse-map [str namespace name] :foo/bar/baz)
; -> (":foo/bar/baz" "foo/bar" "baz")
推荐答案
有 juxt
这有点类似。它需要一些函数,并返回一个将其参数传递给每个函数,并返回一个返回值的向量。所以:
There's juxt
which is a bit similar. It takes a number of functions and returns one that passes its argument(s) to each of the functions and returns a vector of return values. So:
> ((apply juxt [inc dec str]) 1)
[2 0 "1"]
主要的区别是它创建了一个向量,当然是热切的(即不是惰性的)。 map
创建一个延迟的序列。
The main difference is that it creates a vector, which is of course eager (i.e. not lazy.) The original map
creates a sequence which is lazy.
juxt
也适用于有多个参数的函数:
juxt
also works on functions that have more than 1 argument:
> ((apply juxt [* / -]) 6 2)
[12 3 4]
这篇关于是否有反向映射函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!