scheme - 方案 if 表达式返回 '#' 如果正文包含表达式
问题描述
所以我目前正在阅读 SICP 并且我被困在练习 1.22,因为我不明白为什么我的程序没有按照我想要的方式运行。这是代码
#lang sicp
; the given function to time the search for a prime
(define (timed-prime-test n)
(newline)
(display n)
(start-prime-test n (runtime)))
(define (start-prime-test n start-time)
(if (prime? n)
(report-prime (- (runtime) start-time))))
(define (report-prime elapsed-time)
(display " *** ")
(display elapsed-time))
; finds the smallest natural number that can divide n without any remainder
(define (smallest-divisor n)
(define (square x)
(* x x))
(define (divides? a b)
(= (remainder a b) 0))
(define (find-divisor n test-divisor)
(cond ((> (square test-divisor) n) n)
((divides? n test-divisor) test-divisor)
(else (find-divisor n (+ test-divisor 1)))))
(find-divisor n 2))
; returns true if the given number n is prime
(define (prime? n)
(= n (smallest-divisor n)))
; start searching at start and found keeps track of the amount of
; primes found, if it equals 3 return found
(define (search-for-primes start found)
(if (= found 3)
found ; after finding 3 primes above start return
((timed-prime-test start) ; if not continue search with start + 1
(search-for-primes (+ start 1) (if (not (prime? start))
found
(+ found 1))))))
(search-for-primes 1000 0)
问题是当我运行这个程序时它工作正常,直到它找到一个素数。我使用的解释器是球拍,程序以:
application: not a procedure;
expected a procedure that can be applied to arguments
given: #<void>
arguments...:
3
1019 *** 0
如果我正确理解解释器,它应该根据应用顺序评估原则评估这个表达式,对吗?那么为什么将if
表达式作为过程传递给我的search-for-primes
过程呢?我在这里想念什么?
解决方案
问题在于search-for-primes
,如果您在 an 的一条腿中有多个表达式if
,那么您需要将它们放在一个begin
块内 - 用它包围它是()
行不通的。这应该可以解决问题:
(define (search-for-primes start found)
(if (= found 3)
found
(begin ; add this!
(timed-prime-test start)
(search-for-primes (+ start 1) (if (not (prime? start))
found
(+ found 1))))))
推荐阅读
- awk - 使用awk将字符串添加到文件中的数字末尾?
- python - 如何在您自己的类上覆盖或执行 python 中的最小值/最大值?
- c# - 完成后台任务队列后重定向到操作
- c# - Stream 通过 .NET MVC 控制器动态创建文件内容
- java - servlet session-timeout(0) 不工作
- sql - 将多张表合并为一张表 SQL Server
- r - 使字符串集合成为按组排序的数据框,包含序列信息
- elasticsearch - 如何使用 go 在弹性搜索中按嵌套对象对文档进行排序?
- database - 在 Oracle Developer 中创建一个新数据库
- firebase - firebase 函数管理单个数据库触发器上的多个操作