将变量列表单独传递给clojure函数 [英] Passing list of variables individually to clojure function
问题描述
我一直在玩clojure,并决定做一个更高阶的函数,结合mapcat和列表来模拟这种行为:
I have been playing around with clojure, and decided to make a higher order function that combines mapcat and list to emulate this behavior:
Clojure> (mapcat list '(1 2 3 4) '(5 6 7 8))
(1 5 2 6 3 7 4 8)
我的第一个尝试是定义mapcatList如下:
my first attempt was defining mapcatList as follows:
Clojure> (defn mapcatList[& more](mapcat list more))
#'sandbox99/mapcatList
Clojure> (mapcatList '(1 2 3 4) '(5 6 7 8))
((1 2 3 4) (5 6 7 8))
很明显,这个函数并不是我想要的,我认为这是因为两个列表被放入一个列表中,并作为一个参数传递,而不是两个。
我可以用以下方法补救这种情况:
Obviously the function does not behave how I would like it, and I think this is because the two lists are being put into one list and passed as a single argument, not two. I was able to remedy the situation with the following,
Clojure> (defn mapcatList[x y & more](mapcat list x y))
#'sandbox99/mapcatList
Clojure> (mapcatList '(1 2 3 4) '(5 6 7 8))
(1 5 2 6 3 7 4 8)
这个解决方案适用于两个列表,但我希望函数使用可变数量的参数。
This solution works well with two lists, but I would like the function to work with a variable number of arguments.
我的问题:如何传递一个可变数量的参数到一个函数,然后解构它们,使它们作为单独的参数一起传递到'mapcat list' p>
My question: How can I pass a variable number of argument to a function, then destructure them so they are passed as individual arguments together to 'mapcat list'?
推荐答案
您正在寻找 apply
。
但是你知道有一个函数 interleave
您的 mapcatList
尝试做什么?
But are you aware that there's a function interleave
that does exactly what your mapcatList
tries to do?
这篇关于将变量列表单独传递给clojure函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!