简体   繁体   English

使用哈希映射中的命名参数调用Clojure函数

[英]Calling a Clojure function with named parameters from a hash map

I would like to be able to pass named parameters to a function from a hash map. 我希望能够将命名参数传递给哈希映射中的函数。 Let's say I have a function like this: 假设我有这样的函数:

(defn foo [a & {:keys [b]}] (println a b))

I want to be able to call it with parameters coming from a map. 我希望能够使用来自地图的参数来调用它。 I know I can do it like this: 我知道我可以这样做:

(apply foo 1 (mapcat identity {:b 2}))

But surely there must be a more idiomatic and less clunky way to do this, right? 但肯定必须有更惯用,更少笨重的方法来做到这一点,对吧?

Nope, there is no other less clunky way. 不,没有其他不那么笨重的方式。 It would be better to make your foo to take a hash-map as parameter and pattern match on it for keys: 最好让你的foo将hash-map作为参数和模式匹配来获取键:

(defn foo [a {:keys [b]}] (println a b))
(foo 1 {:b 2})

No, there isn't. 不,没有。 But you may use concat directly instead of doing it through mapcat : 但是你可以直接使用concat而不是通过mapcatmapcat

(apply foo 1 (apply concat {:b 2}))

You may also use ->> macro to make it clearer (though not shorter): 您也可以使用->>宏来使它更清晰(尽管不会更短):

(->> {:b 2}
     (apply concat)
     (apply foo 1))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM