我如何在Clojure的运行时序列化函数? [英] How can I serialize functions at runtime in Clojure?
问题描述
例如...
如果我运行 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的运行时序列化函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!