我正在阅读Peter的人工智能编程(PAIP)的范例,我正在尝试用code而不是通用的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?谢谢。
发布于 2011-01-01 03:50:29
一段时间前,我是一位相关的Clojure新手,做过这个练习。这里要考虑的是,您是否希望尽可能严格地遵守Norvig的代码(比如编写“Common风味”Clojure),或者是否希望编写一些更接近习惯Clojure的代码。我所做的是:
(use '[clojure.contrib.def :only [defvar]])
(defvar *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是一种糖,它允许您更自然地向vars添加docstring。在本例中,我使用一个映射(由{}分隔的键值对)从每个规则的LHS到RHS进行字典式查找。我还使用向量(由[]分隔)代替列表来表示每条规则的RHS。一般来说,“惯用”Clojure代码很少使用列表来保存顺序数据;除非表示Clojure表单(源代码),否则向量是首选的。
这些类型的更改将允许您使用语言的更多内置功能,而不需要编写小助手函数来操作嵌套列表。
发布于 2010-12-31 23:31:01
Ken是对的,只是对def*窗体做了一些简单的更改,以及一种不同的docstring风格(函数定义中的docstring比普通的vars要简单一些):
(def ^{:doc "A grammar for a trivial subset of English."}
*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)))
(def *grammar* *simple-grammar*)https://stackoverflow.com/questions/4572608
复制相似问题