您好我正在尝试在lisp中创建嵌套if,但我们一直收到错误,而且我们不知道如何解决它!
** - EVAL:特殊运算符IF的参数太多:
(defun spread-stones-helper(game-state StoneInHand Player player-index pit-index)
;; Do we have more stones in our hand?
(if (> 0 StoneInHand)
;; Are we above the pit limit?
(if (> pit-index 5)
;; Switch the player and reset the pit-index to 0
(setq player-index (switchplayer player-index))
(setq pit-index '0)
)
;; Add 1 to the pit
(set-pit game-state player-index (GetCorrectPit player-index pit-index) (+ (get-pit game-state player-index (GetCorrectPit player-index pit-index)) 1))
;; Recursive call the function, with one less stone and 1 up in pit-index
(spread-stones-helper game-state (- StoneInHand 1) Player player-index (+ pit-index 1))
)
;; There are no more stones in hand, run capture stones
;; (captureStones game-state StoneInHand Player player-index pit-index)
)
答案 0 :(得分:8)
在lisp中,if
运算符接受三个表达式,条件是条件,值是条件为真,值是条件为假的值...例如
(if (< x 0)
(print "x is negative")
(print "x is greater or equal than zero"))
您也可以省略最后一个表达式,在这种情况下,它假定为NIL。
如果您想在两种情况之一中添加更多表达式,则必须以progn
形式包装它们
(if (< x 0)
(progn
(print "HEY!!!!")
(print "The value of x is negative...")))
发现if
表达式中只有两个分支中只有一个被填充并且有很多表达式的情况非常频繁,因此添加了两个特殊用途的特殊变体:
(when (< x 0)
(do-this)
(do-that)
(do-even-that-other-thing))
(unless (< x 0)
(do-this)
(do-that)
(do-even-that-other-thing))
上面的when
表单相当于
(if (< x 0)
(progn
(do-this)
(do-that)
(do-even-that-other-thing)))
unless
形式具有相同的含义,但条件反转...换句话说,它等同于
(if (not (< x 0))
(progn
(do-this)
(do-that)
(do-even-that-other-thing)))
回顾一下,只有当您需要为两个分支(真假分支)编写代码时,才应使用if
。否则,请使用when
或unless
,具体取决于您的测试更具可读性。
使用if
表单时,您必须在分支中使用progn
,而您需要放置多个表单。
答案 1 :(得分:5)
不要忘记将(progn ...)
用于多个if语句
(defun spread-stones-helper (game-state StoneInHand Player
player-index pit-index)
;; Do we have more stones in our hand?
(if (> 0 StoneInHand)
(progn
;; Are we above the pit limit?
(if (> pit-index 5)
(progn
;; Switch the player and reset the pit-index to 0
(setq player-index (switchplayer player-index))
(setq pit-index '0)))
;; Add 1 to the pit
(set-pit game-state player-index
(GetCorrectPit player-index pit-index)
(+ (get-pit game-state player-index
(GetCorrectPit player-index pit-index))
1))
;; Recursive call the function, with one less stone and 1
;; up in pit-index
(spread-stones-helper game-state
(- StoneInHand 1)
Player
player-index
(+ pit-index 1))))
;; There are no more stones in hand, run capture stones
;; (captureStones game-state StoneInHand Player player-index pit-index)
)
答案 2 :(得分:5)
“if”进行测试和两种形式 -
您已经给出了第一个“if”测试和三个表单
假设(&gt; 0 StoneInHand)为真。
你想同时运行第二个if和set-pit语句吗?
如果是这样,你需要将它们包装在(预测)
中