gpt4 book ai didi

python - 这个 Python 代码的惯用 Clojure 等价物?

转载 作者:太空宇宙 更新时间:2023-11-03 12:22:11 26 4
gpt4 key购买 nike

我用 Python 编写了一个简单的基于堆栈的虚拟机,现在我正尝试用 Clojure 重写它,事实证明这很困难,因为我对 Lisp 的经验不多。 This Python snippet处理字节码,字节码表示为元组列表,如下所示:

[("label", "entry"),
("load", 0),
("load", 1),
("add",),
("store", 0)]

或者在 Clojure 中:

[[:label :entry]
[:load 0]
[:load 1]
[:add]
[:store 0]]

当 Function 对象加载字节码时,每个“标签”元组都经过特殊处理以标记该位置,而其他所有元组都保留在最终字节码中。我假设此函数的 Clojure 等价物会涉及折叠,但我不确定如何以优雅或惯用的方式做到这一点。有什么想法吗?

最佳答案

阅读该 Python 代码片段,您似乎希望最终输出看起来像

{:code [[:load 0]
[:load 1]
[:add]
[:store 0]]
:labels {:entry 0}}

一旦您对目标有了明确的描述,编写代码就会容易得多,而且这确实是一个非常简单的 reduce。有许多风格不同的方式来编写 reducer ,但对我来说,这种方式似乎最容易阅读。

(defn load [asm]
(reduce (fn [{:keys [code labels]} [op arg1 & args :as instruction]]
(if (= :label op)
{:code code
:labels (assoc labels arg1 (count code))}
{:code (conj code instruction)
:labels labels}))
{:code [], :labels {}},
asm))

编辑

此版本支持 name 参数,并通过不重复未更改的元素来简化缩减步骤。

(defn load [name asm]
(reduce (fn [program [op arg1 :as instruction]]
(if (= :label op)
(assoc-in program [:labels arg1] (count (:code program)))
(update-in program [:code] conj instruction)))
{:code [], :labels {}, :name name},
asm))

关于python - 这个 Python 代码的惯用 Clojure 等价物?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8720073/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com