2017-05-30 46 views
-1

所以我想口齒不清教我,我目前使用這個網站作爲參考:https://www.tutorialspoint.com/lisp/lisp_if_construct.htm如果有則條款(LISP)語句

我爲什麼執行then子句不太瞭解,儘管if條款是假的?

(setq a 10) 
(if (> a 20) 
    then (format t "~% a is less than 20")) 
(format t "~% value of a is ~d " a) 

輸出是:

a is less than 20 
value of a is 10 

是否then子句只是一直執行,即使if語句是假的? (在這種情況下它是)。

任何幫助將不勝感激,也對不起,如果我的術語是完全不正確的我還是新來的Lisp!

+0

該教程似乎有點垃圾。網上有很多免費的Lisp書籍,比如Peter Seibel的[Practical Common Lisp](http://www.gigamonkeys.com/book/)。 – molbdnilo

回答

4

根據the documentation一個if有3個元素。例如test-expression例如(> a 10)then-expression例如(- a 10)else-expression例如。 a

(if (> a 10) ; if a is larger than 10 
    (- a 10) ; then return the value of a minus 10 
    a)  ; else return the value of a 

看看你的代碼:

(if (> a 20)       ; if a is larger than 20 
    then        ; then return the value of "then" 
    (format t "~% a is less than 20")); else print a is less than 20 to screen 

在這個例子中,他們所提供的條款,然後作爲單個變量then。由於測試是錯誤的,所以總是打印else-expression。

+0

謝謝,但我不太確定我理解你的解釋?爲什麼然後返回一個值,儘管if語句不被滿足? –

+0

'then'不是一個關鍵字,所以它被認爲是在測試結果爲true時執行的代碼。如果測試結果爲真,那麼你會得到'then'不是綁定變量的錯誤。每個被評估的符號都是一個變量,就像你的例子中的'a'。 – Sylwester

+0

你也可以直接在網站上測試lisp代碼,以防你想弄亂它:)但是,我很困惑,看到他們如何使用它們,然後他們得到不同的結果時,他們忽略它。 –