如何自动创建Clojure`defn`函数? [英] How to Create Clojure `defn` Functions automatically?
问题描述
我重新编写了此代码,以使原来的问题更清晰,并添加了全宏解决方案.请忽略此版本,并参考以下内容:
I re-wrote this to make the original problem clearer and added the all-macro solution. Please ignore this version and refer to the following:
如何在不使用宏的情况下自动创建Clojure`defn`函数?
很遗憾,SO不允许我删除此旧版本.
Unfortunately, SO will not allow me to delete this older version.
最初由以下问题引起:映射到clojurescript宏的调用
Originally motivated by the following question: Mapped calls to clojurescript macro
假设您要自动创建许多相似的功能(即无需全部手写).假设我们有一些预先存在的数据,并且我们想要编写访问器函数,如下所示:
Suppose you want to create many similar functions automatically (i.e. without hand-writing them all). Suppose we have some pre-existing data and we want to write accessor functions like so:
(def foo
{:able "Adelicious!"
:baker "Barbrallicious!"
:charlie "Charlizable"})
(def bar
{:able "Apple"
:baker "Berry"
:charlie "Kumquat"})
(defn manual-my-foo [item] (get foo item))
(defn manual-my-bar [item] (get bar item))
(manual-my-foo :able) => "Adelicious!"
(manual-my-bar :charlie) => "Kumquat"
因此manual-my-foo
是硬接线"的,以使用foo
全局地图.
So manual-my-foo
is "hard-wired" to use the foo
global map.
您可能会认为需要一个宏来创建此功能,这是一种解决方案.但是,宏的缺点是不能将它们作为参数传递给另一个函数,例如map
.因此,我们可以编写一个像这样的宏:
You might think you need a macro to create this function, and that is one solution. However, a weakness of macros is that they cannot be passed as arguments to another function such as map
. Thus, we could write a macro like:
(generate-fn :foo) ;=> creates `my-foo` w/o hand-writing it
,但以下操作将失败:
(map generate-fn [:foo :bar :baz])
我们如何自动生成这些功能?
How can we automate the generation of these functions?
推荐答案
我们如何自动生成这些功能?
How can we automate the generation of these functions?
您不需要. foo
和bar
映射可按您期望的功能运行:
You don't need to. The foo
and bar
maps operate as the functions you desire:
(foo :able) ; "Adelicious!"
(bar :able) ; "Apple"
这篇关于如何自动创建Clojure`defn`函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!