简体   繁体   English

将哈希映射应用于Clojure中的匿名函数的快速方法

[英]quick way to apply hash-map to anonymous function in clojure

My question is whether given a hashmap 我的问题是是否给定哈希图

(def my-map {'x 1 'y 2 'z})

I can apply it to an anonymous function, 我可以将其应用于匿名函数,

(fn [xyz] (+ x (* yz))

so that the arguments match the keys in the map, somthing like 这样参数就匹配了地图中的键,就像

(apply-ish my-map (fn [xyz] (+ x (* yz)))

Is there an easy fix to this problem? 有解决此问题的简便方法吗? I feel like there is but I cant figure it out. 我感觉好像有,但我无法弄清楚。

You can use map destructuring: 您可以使用地图解构:

user> (def my-map {'x 1 'y 2 'z 3})
#'user/my-map

user> ((fn [{x 'x y 'y z 'z}] (+ x (* y z))) my-map)
7

You can simplify a bit with this form of desctructuring: 您可以使用这种解构形式简化一点:

user> ((fn [{:syms [x y z]}] (+ x (* y z))) my-map)
7

or if you use keywords for your map keys: 或者,如果您将关键字用作地图键:

user> (def my-map2 {:x 1 :y 2 :z 3})
#'user/my-map2

user> ((fn [{:keys [x y z]}] (+ x (* y z))) my-map2)
7

personally, i would not modify the function to accept the map as the arg, since it makes the function itself way less generic. 就个人而言,我不会修改该函数以将映射接受为arg,因为它使函数本身的通用性降低。 The alternative (and idiomatic i guess, for any language) solution is to select needed keys from the map before passing them to function. 另一种解决方案(对于任何语言来说都是惯用的解决方案)是在将其传递给功能之前从地图中选择所需的键。 That is quite easy, since both map and symbol (and keyword too) have function semantics in clojure: 这很容易,因为map和symbol(还有关键字)在clojure中都具有函数语义:

user> (apply f (map my-map ['x 'y 'z]))
;;=> 7

user> (apply f ((juxt 'x 'y 'z) my-map))
;;=> 7

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

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