简体   繁体   English

Lisp函数有什么问题?

[英]What is wrong with this Lisp Function?

This function is a CLisp function, this is part of a homework problem, but which is supposed to be written in this different format (the second function). 此函数是CLisp函数,它是家庭作业问题的一部分,但应该以这种不同的格式编写(第二个函数)。

(defun range (m M) (cond
((> m M) '() )
((= m M) '() )
((< m M) (cons m (range (+ m 1) M ) ) )  
)
)


(define (range m M) (cond
    ((> m M) '() )
    ((= m M) '() )
    ((< m M) (cons m (range (+ m 1) M ) ) )
)
)

These should both take a min value (m) and a max value (M) and return the list of integers from min to max (exluding the max value / M-1) 它们都应采用最小值(m)和最大值(M),并返回从最小值到最大值的整数列表(不包括最大值/ M-1)

I have traced this over and over and I can't see why it is just returning NIL it must be a very dumb logic mistake. 我已经一遍又一遍地追踪了这一点,但我看不出为什么它只是返回NIL,这肯定是一个非常愚蠢的逻辑错误。

(range 1 4)  => result (1 2 3)

m=1 | M=4 ==> return (cons 1 (2 3) )
m=2 | M=4 ==> return (cons 2 (3) )
m=3 | M=4 ==> return (cons 3 () )
m=4 | M=4 ==> return ()
    v         ^
    ---------/

I'm going crazy trying to figure out WHY this is not performing like I trace it. 我发疯了,试图弄清楚为什么它没有像我追踪到的那样表现良好。

Again, when I execute the function it results in NIL. 同样,当我执行该函数时,结果为NIL。

I ran this using SBCL and it complained that the variable M appears twice in the parameter list. 我使用SBCL运行此程序,它抱怨变量M在参数列表中出现两次。 Lisp is not case-sensitive for variable names. Lisp对变量名不区分大小写。

On changing it to 在将其更改为

(defun range (m MM) 
  (cond
      ((> m MM) '() )
      ((= m MM) '() )
      ((< m MM) (cons m (range (+ m 1) MM)))))

It worked fine. 工作正常。

> (trace range)
> (range 1 4)
  0: (RANGE 1 4)
    1: (RANGE 2 4)
      2: (RANGE 3 4)
        3: (RANGE 4 4)
        3: RANGE returned NIL
      2: RANGE returned (3)
    1: RANGE returned (2 3)
  0: RANGE returned (1 2 3)
-> (1 2 3)

I checked with CLISP. 我检查了CLISP。 With different variable names it works OK. 使用不同的变量名可以正常工作。 CLISP does not pick up the error, unlike SBCL. 与SBCL不同,CLISP不会收到错误。

<[1]> (defun range (m MM) (cond ((>= m MM) '())((< m MM) (cons m (range (+ m 1) MM )))))
RANGE

[2]> (range 1 4)
(1 2 3)

Here is your version: 这是您的版本:

[3]> (defun range (m M) (cond ((>= m M) '())((< m M) (cons m (range (+ m 1) M)))))

RANGE

[4]> (range 1 4)
Nil

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM