【问题标题】:Is there a nested if in lisp?lisp中有嵌套的if吗?
【发布时间】:2021-04-30 16:20:22
【问题描述】:
(if (> 10 5)
    (format t "First number is greater ~%"))
    
    (if (> 10 15) 
        (format t "First number is greater ~%")
        (format t "Second number is greater ~%"))
        
        (if (= 10 10)
        (format t "Both numbers are equal"))

【问题讨论】:

  • cond 是您要找的吗?
  • 我不确定,因为语法很混乱。我将它与 C 语言的嵌套 if 进行比较,我想知道 LISP 中是否有替代或等价物
  • Lisp 嵌套 IF 就像 C 嵌套 if。你可以在任何允许任何表达式的地方使用if,包括在另一个if中。
  • 为什么在10不大于15的第二种情况下打印First number is greater
  • 顺便说一句,您没有嵌套问题中的问题,只是缩进它们以使它们看起来嵌套。

标签: if-statement nested lisp structure


【解决方案1】:

if 在大多数 Lisps 中的语法是 (if <test> <then> [<else>]),尽管可能会有一些变化:有时<else> 是强制性的,在一些较旧的 lisp 中,<else> 可以有多种形式(我认为 elisp 是现在唯一常用的lisp)。所以嵌套的if 很简单:

(if a
    ...
  (if b
      ...
    (if c
        ...
      ...)))

这在缩进方面很烦人,所以有一种叫做cond的形式,上面的表达式在Common Lisp中是:

(cond
 (a ...)
 (b ...)
 (c ...)
 (t ...))

或在方案中

(cond
 (a ...)
 (b ...)
 (c ...)
 (else ...))

cond 有一个很好的功能,所有的...s 可以是多种形式。

如果你没有cond,你可以写成if:这是一个使用Scheme宏的版本(实际上Racket的:void我认为是Racket),称为kond

(define-syntax kond
  (syntax-rules (else)
    [(_)
     (void)]
    [(_ (else form ...))
     (begin form ...)]
    [(_ (test form ...)
        more ...)
     (if test
         (begin form ...)
         (kond more ...))]))

同样,如果你没有if,你可以将它写成cond:这里有一个叫做yf的写成kond,再次使用Scheme宏:

(define-syntax yf
  (syntax-rules ()
    [(_ test result)
     (kond (test result))]
    [(_ test result otherwise)
     (kond (test result)
           (else otherwise))]))

这两者都可能存在各种错误。

从历史上看,cond 是我认为的原始人。

【讨论】:

  • 在您陈述的第一个语法/示例中,如果嵌套 if 中的所有条件都为真,是否应该打印所有语句?
  • @Zel:不,只是第一件事是正确的,就像在 C 中的 if (...) ...; else if (...) ...; else ...; 中一样(除了 if 是 Lisp 中的表达式,因为 Lisp 是一种表达式语言:有没有声明,所以(+ (if x 1 2) 3) 很好,比如说)。
【解决方案2】:

我终于想通了。

(cond ((> 10 5)
    (format t "First numbers is greater. ~%")
    (< 10 15)
         (format t "Second number is greater. ~%")
         (= 10 10)
             (format t "Both numbers are equal. ~%")))

【讨论】:

  • 这里有一些放错位置的括号。你应该有(cond (test1 exp1 ...) (test2 exp2 ...)),测试就像(&gt; 10 5)。如果需要,您还可以添加 (else exp3 ...) 子句。
猜你喜欢
  • 1970-01-01
  • 2014-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多