List 从2到n的素数列表(方案)
我试图创建一个过程,它构建一个从2到任意数n的素数列表。当然,这需要反复进行,但我不知道我到底做错了什么List 从2到n的素数列表(方案),list,numbers,scheme,primes,List,Numbers,Scheme,Primes,我试图创建一个过程,它构建一个从2到任意数n的素数列表。当然,这需要反复进行,但我不知道我到底做错了什么 (define (list-2-to-n n) (define (iter n result) (if (= n 0) result (if (< n 2) '() (if (= (remainder n 3) 0) (list-2-to-n (
(define (list-2-to-n n)
(define (iter n result)
(if (= n 0)
result
(if (< n 2)
'()
(if (= (remainder n 3) 0)
(list-2-to-n (- n 1))
(if (even? n)
(list-2-to-n (- n 1))
(iter (- n 1) (cons n result)))))))
(iter n '()))
(定义(列表2-to-n)
(定义(iter n结果)
(如果(=n0)
结果
(如果(
每当测试用例通过过程时,它总是返回()
我做错了什么
让我看看。首先,你的缩进是令人悲哀的误导。它确实应该正确反映代码的结构:
(define (list-2-to-n-0 n) ; a global function
(define (iter n result) ; an internal function
(if (= n 0)
result
(if (< n 2) ; **else**
'()
(if (= (remainder n 3) 0)
(list-2-to-n (- n 1))
(if (even? n) ; **else**
(list-2-to-n (- n 1))
(iter (- n 1) (cons n result)))))))
(iter n '()))
在那里调用全局函数意味着重新启动整个过程-它将使用初始累加器参数()
调用其iter
。对于大于0的n
的任何初始值,您假定返回的n==0
的结果案例实际上是不可访问的,因为将首先遇到案例n<2
,并且将返回()
(正是观察到的行为)
您不应该重新开始,也就是说,您应该始终调用内部函数。你应该修正你的基本情况。最后但并非最不重要的一点是,仅检查2或3的可除性是不够的,已经是5了。因此,让我们在这里编写isPrime
,并在以后实现它:
(define (list-2-to-n-1 n) ; a global function
(define (iter n result) ; an internal function
(cond
((< n 2) result)
((not (isPrime n))
(iter (- n 1) result)) ; calling internal function, without
(else ; altering the accumulator
(iter (- n 1) ; calling internal function,
(cons n result))))) ; altering the accumulator
(iter n '()))
(定义(列表2-to-n-1n);全局函数
(定义(iter n结果);内部函数
(续)
(
isPrime
需要尝试将n
除以2,3,。。。不需要尝试除以2以上的任何偶数,只要赔率就足够了。不需要尝试任何潜在的除数d
,例如d*d>n
,因为如果n=f*d,f为一件事,您只需测试除以2
和3
,当两者都不是时,将结果保留为nil
。还有更多的bug,但这只是一个开始。和你的目标很相似。
(define (list-2-to-n-1 n) ; a global function
(define (iter n result) ; an internal function
(cond
((< n 2) result)
((not (isPrime n))
(iter (- n 1) result)) ; calling internal function, without
(else ; altering the accumulator
(iter (- n 1) ; calling internal function,
(cons n result))))) ; altering the accumulator
(iter n '()))