我们怎样才能创建“实例”?动态类型或记录

发布于 2024-09-24 06:38:31 字数 511 浏览 2 评论 0原文

这个问题与这个问题密切相关,但我认为是更一般。

最近,我尝试基于元数据标签使用多种方法(或者如果可能的话使用唯一的函数构造函数)动态创建类型“实例”。我用这个标签链接了一个类型(底层的 java 类),然后我不知道如何以优雅的方式继续(没有 eval 或 java 反射和字符串); new 是一种特殊的形式,虽然使用了宏,但处理起来还是很困难。

在伪代码中它将是:

(def my-tagged-data (with-meta my-data {:my-type-tag my-ns.My-Type}))
(def factory-function [tagged-data] 
     (create (:my-type-tag (meta tagged-data)) tagged-data))

This question is closely related to this one but i think is more general.

Recently i try to create type "instances" on the fly with multimethods (or with a unique function constructor if possible), based in a metadata tag. I linked a type (a java class under the hood) with this tag and then i didnt know how to continue in a elegant way (without eval or java reflection and strings); new is a special form and it's difficult to handle although you use macros.

In seudo-code it would be:

(def my-tagged-data (with-meta my-data {:my-type-tag my-ns.My-Type}))
(def factory-function [tagged-data] 
     (create (:my-type-tag (meta tagged-data)) tagged-data))

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

时常饿 2024-10-01 06:38:31

您可以为您的类型提供工厂函数。

(def my-tagged-data (with-meta my-data {:my-type-factory `my-type-factory}))

(defn factory-function
  [tagged-data] 
  (@(resolve (:my-type-factory (meta tagged-data))) tagged-data))

这可能可行,也可能不可行。

You can provide factory functions for your types.

(def my-tagged-data (with-meta my-data {:my-type-factory `my-type-factory}))

(defn factory-function
  [tagged-data] 
  (@(resolve (:my-type-factory (meta tagged-data))) tagged-data))

This may or may not be feasible.

影子的影子 2024-10-01 06:38:31

我认为你必须使用反射。 (我认为比 eval 更好的主意)。

I think that you have to use reflection. (Better idea than eval, I think).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文