将变量列表单独传递给 clojure 函数 [英] Passing list of variables individually to clojure function

查看:27
本文介绍了将变量列表单独传递给 clojure 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在玩 clojure,并决定制作一个结合 mapcat 和 list 的高阶函数来模拟这种行为:

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 列表"?

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.这将调用一个函数,其参数按序列提供.

You are looking for apply. This calls a function with the arguments supplied in a sequence.

但是您是否知道有一个函数 interleave 可以完全按照您的 mapcatList 尝试执行的操作?

But are you aware that there's a function interleave that does exactly what your mapcatList tries to do?

这篇关于将变量列表单独传递给 clojure 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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