将一段 Lisp 代码移植到 Clojure (PAIP)
我正在阅读 Peter Norvig 的人工智能编程范式(PAIP),并且我尝试用 Clojure 而不是普通的 Lisp 编写所有代码。然而我被困在第 39 页的这段代码上:
(defparameter *simple-grammar*
'((sentence -> (noun-phrase verb-phrase))
(noun-phrase -> (Article Noun))
(verb-phrase -> (Verb noun-phrase))
(Article -> the a)
(Noun -> man ball woman table)
(Verb -> hit took saw liked))
"A grammar for a trivial subset of English.")
(defvar *grammar* *simple-grammar*)
如何将其翻译成 Clojure? 谢谢。
I'm reading Paradigms of Artificial Intelligence Programming (PAIP) by Peter Norvig and I'm trying to write all the code in Clojure rather than common Lisp. However I'm stuck on this piece of code on page 39:
(defparameter *simple-grammar*
'((sentence -> (noun-phrase verb-phrase))
(noun-phrase -> (Article Noun))
(verb-phrase -> (Verb noun-phrase))
(Article -> the a)
(Noun -> man ball woman table)
(Verb -> hit took saw liked))
"A grammar for a trivial subset of English.")
(defvar *grammar* *simple-grammar*)
How can I translate this into Clojure?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我是一个 Clojure 新手,不久前经历过这个练习。这里需要考虑的是,您是否想尽可能严格地遵循 Norvig 的代码(例如编写“Common-Lisp 风格”Clojure),或者您是否想编写更接近惯用 Clojure 的代码。这就是我所做的:
defvar 是糖,它允许您更自然地向变量添加文档字符串。在本例中,我使用映射(由 {} 分隔的键值对)来获取从每个规则的左侧到右侧的字典式查找。我还使用向量(由 [] 分隔)而不是列表来表示每个规则的 RHS。一般来说,“惯用的”Clojure 代码很少使用列表来保存顺序数据;除非您代表 Clojure 形式(源代码),否则首选向量。
这些类型的更改将允许您更多地使用该语言的内置功能,而不必编写一些辅助函数来操作嵌套列表。
I'm a relative Clojure newbie that went through this exact exercise a while back. Something to consider here is whether you'd like to adhere as closely as possible to Norvig's code (like writing "Common-Lisp-flavored" Clojure) or if you'd like to write something closer to idiomatic Clojure. Here's what I did:
defvar is sugar that allows you to add docstrings to vars more naturally. In this case I'm using a map (key value pairs delimited by {}) to get dictionary-style lookup from the LHS of each rule to the RHS. I'm also using vectors (delimited by []) instead of lists to represent the RHS of each rule. Generally speaking, "idiomatic" Clojure code rarely uses lists to hold sequential data; vectors are preferred unless you're representing Clojure forms (source code).
These kinds of changes will allow you to use more of the built-in power of the language instead of e.g., having to write little helper functions to manipulate nested lists.
Ken 是对的,只需对 def* 形式进行一些简单的更改,以及不同样式的文档字符串(文档字符串对于函数定义来说比对于普通变量要简单一些):
Ken's right, just a simple few changes to the def* forms, and a different style of docstring (docstrings are a bit simpler for function definitions than for normal vars):