【问题标题】:SCHEME - Count number of procedures that are not primitiveSCHEME - 计算非原始程序的数量
【发布时间】:2014-10-02 04:28:40
【问题描述】:

我必须创建一个函数来计算列表中非原始过程的数量。 以下是一些示例:

(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)
   )
)

此代码不起作用,希望有人能提供帮助。 提前致谢!

【问题讨论】:

  • 第一个是带引号的列表,所以+* 是符号而不是过程。第二个您尝试评估表达式并将结果传递给nprocs,而最后一个示例使用list,以便可以将+ 和其他符号评估为过程。只有最后一个是正确的。或者,您可以使用`(,+ (,curado 1) (,* 2 (,inc1 3)))

标签: list scheme procedure primitive


【解决方案1】:

列表由 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

【讨论】:

    【解决方案2】:

    nprocs 过程必须遍历列表列表,测试每个原子是否是原语的过程,并将所有子列表的结果相加。如果我们使用cond 作为条件,这会更简单,并使用标准模板来遍历列表:

    (define (nprocs fun)
      (cond ((null? fun) 0)
            ((not (pair? fun))
             (if (and (procedure? fun) (not (primitive? fun))) 1 0))
            (else (+ (nprocs (car fun))
                     (nprocs (cdr fun))))))
    

    只要我们在列表中传递实际过程(不仅仅是符号),它就可以工作:

    (nprocs (list + (list cuadrado 1) (list * 2 (list inc1 3))))
    => 2
    

    如果相同的非原始过程出现多次,则会被计算多次。如果这是一个问题,如果我们使用更惯用的解决方案,利用内置的高阶过程,删除重复项会更容易。例如,在球拍中:

    (define (nprocs fun)
      (count (lambda (e) (and (procedure? e) (not (primitive? e))))
             (remove-duplicates (flatten fun))))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-06
      • 1970-01-01
      • 2019-10-25
      • 1970-01-01
      • 2012-11-15
      • 1970-01-01
      • 2014-03-02
      • 1970-01-01
      相关资源
      最近更新 更多