我如何在Clojure的运行时序列化函数?

编程入门 行业动态 更新时间:2024-10-28 06:30:46
本文介绍了我如何在Clojure的运行时序列化函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 有没有办法在Clojure的运行时序列化函数?我希望能够通过串行格式发送无状态(但不是纯粹的)函数(可能是edn,但我对任何东西都是开放的)。


例如...

如果我运行 prn-str 在一个函数上,我没有得到我预期的/想要的。

user => (def fn1(fn [x](* x 2)))#'user / fn1 user => (def data {:test 1:keyvalue})#'user / data user => (defn fn2 [x](* x 2))#'user / fn2 user => (prn-str fn1)#object [user $ fn1 0x28b9c6e2 \user $ fn1 @ 28b9c6e2\] \\\ user => (prn-str数据){:test 1,:key \value \} \\\ user => (prn-str fn2)#object [user $ fn2 0x206c48f5 \user $ fn2 @ 206c48f5\] \\\ user =>

我会希望/期望如下所示:

user => (prn-str fn2)(fn [x](* x 2))\\\

或者也许是

user => (prn-str fn2)(defn fn2 [x](* x 2))\\\

<在某些时候它不再是Clojure,所以期望我们可以任意地从源代码到机器指令的往返行程回退一点点。

>

我们应该能够将一个函数序列化为一个字节数组,然后通过线路发送。我怀疑你需要获取函数的java.lang.Class对象,然后通过 java.lang.instrument.ClassFileTransformer 来获取字节。一旦你有了这些,你可以将它们传递给友好的 java .lang.ClassLoader 在远程jvm上。

Is there a way to serialize functions at runtime in Clojure? I'd like to be able to send stateless (but not pure) functions over the wire in a serialized format (probably edn, but I'm open to anything).

For example...

If I run prn-str on a function, I don't get what I expected/wanted.

user=> (def fn1 (fn [x] (* x 2))) #'user/fn1 user=> (def data {:test 1 :key "value"}) #'user/data user=> (defn fn2 [x] (* x 2)) #'user/fn2 user=> (prn-str fn1) "#object[user$fn1 0x28b9c6e2 \"user$fn1@28b9c6e2\"]\n" user=> (prn-str data) "{:test 1, :key \"value\"}\n" user=> (prn-str fn2) "#object[user$fn2 0x206c48f5 \"user$fn2@206c48f5\"]\n" user=>

I would have wanted/expected something like this:

user=> (prn-str fn2) "(fn [x] (* x 2))\n"

or, maybe,

user=> (prn-str fn2) "(defn fn2 [x] (* x 2))\n"

解决方案

At some point it ceases to be Clojure, so the expectation that we can arbitrarily round trip from source to machine instructions and back is a little bit off.

We should be able to serialize a function to a byte array and send that across the wire though. I suspect you'd need to grab the function's java.lang.Class object and then pass that through a java.lang.instrument.ClassFileTransformer to get the bytes. Once you have those you can pass them through to the friendly java.lang.ClassLoader on the remote jvm.

更多推荐

我如何在Clojure的运行时序列化函数?

本文发布于:2023-11-09 20:10:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1573306.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:时序   函数   如何在   Clojure

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!