我必须创建一个函数,在其中必须计算列表中非原始过程的数量。 以下是一些示例:
(nprocs '(+ (cuadrado 1) (* 2 (inc1 3)))) => 0
(nprocs (+ (cuadrado 1) (* 2 (inc1 3)))) => ERROR
(nprocs (list + (list cuadrado 1) (list * 2 (list inc1 3)))) => 2
我尝试过这个:
(define (cuadrado x) (* x x))
(define inc1 (lambda (x) (+ x 1)))
(define nprocs
(lambda (fun)
(if (list? fun)
(if(procedure? (car fun))
(+ 1 (nprocs (cdr fun)))
(nprocs (cdr fun)))
0)
)
)
此代码不起作用,希望有人能提供帮助。 提前致谢!
最佳答案
列表由 cons 单元和原子组成。这是处理列表的规范方法,计算途中的非原始过程:
(define (nprocs sxp)
(cond
; cons cell -> process car and cdr
((pair? sxp) (+ (nprocs (car sxp)) (nprocs (cdr sxp))))
; atom -> is it a procedure that is not a primitive?
((and (procedure? sxp) (not (primitive? sxp))) 1)
; atom, not or procedure or a primitive
(else 0)))
测试:
> (nprocs '(+ (cuadrado 1) (* 2 (inc1 3))))
0
> (nprocs (list + (list cuadrado 1) (list * 2 (list inc1 3))))
2
关于list - SCHEME - 计算非原始过程的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26154490/