`
mycream
  • 浏览: 54077 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

Lisp 语言学习--if 语句有问题

阅读更多
为了方便的开发学习,还是回到了 Linux 平台下。毕竟这里安装些古董语言比较方便,怎么说也是类 Unix 系统上发展而来的嘛。第二天了,却仍在为 Lisp 语法奔波。手头上中文资料有限,又要考虑其他,这个进度还是忍受一下吧。好啦,不牢骚啦。下面是我的第一个 Lisp 程序:汉诺塔

(setq a "a")
(setq b "b")
(setq c "c")

(defun move (n x y z)
  (if (> n 0)
    ((move (- n 1) x z y)
     (princ "->")
     (move (- n 1) y x z))))

(defun hanota (n)
  (move n a b c))


可惜这段代码始终通不过编译,总得到如下提示:

*** - SYSTEM::%EXPAND-FORM: (MOVE (- N 1) X Z Y) should be a lambda expression

郁闷了一整天,找了许多的资料,最后得到这一句

COMMON LISP: A Gentle Introduction to Symbolic Computation 写道
IF is the simplest Lisp conditional. Conditionals are always macros or special functions,* so their arguments do not get evaluated automatically.


macros or special functions! 不明白为什么 if 后添加的必须是 macros or special functions(宏或特殊函数)。但这样就是说把 if 的候选区换成函数就能正常运行了。于是试用下面的代码:

(setq a "a")
(setq b "b")
(setq c "c")

(defun move (n x y z)
  (if (> n 0)
    (move-operation n x y z)
    t
  )
)

(defun move-operation (n x y z)
  (move (- n 1) x z y)
  (princ x)
  (princ "->")
  (princ z)
  (princ "  ")
  (move (- n 1) y x z))

(defun hanota (n)
  (move n a b c))

新建了一个 move-operation 函数,编译通过。OK, 测试:

> (hanota 3)
a->c  a->b  c->b  a->c  b->a  b->c  a->c  
T

成功。

表面的问题是解决了,可这不是最终解决方案。marco or special functions 还不完全理解是什么。if 还有什么潜规则不清楚。princ 的回车换行也没找到。所以,这个初成品,只能是现在的一种简易替换方法吧。

分享到:
评论
1 楼 xiao2004 2011-01-02  
定义一个progn就完了。
    
(defun move (n x y z) 
  (if (> n 0) 
     (progn (move (- n 1) x z y) 
      (princ "->") 
      (move (- n 1) y x z))))

相关推荐

Global site tag (gtag.js) - Google Analytics