“application: not a procedure” while computing binomial

后端 未结 3 479
别跟我提以往
别跟我提以往 2021-01-26 15:09

I am defining a function binomial(n k) (aka Pascal\'s triangle) but am getting an error:

    application: not a procedure;
    expected a procedure          


        
相关标签:
3条回答
  • 2021-01-26 15:48

    In Scheme (and Lisps in general), parentheses are placed before a procedure application and after the final argument to the procedure. You've done this correctly in, e.g.,

    (= n 0)
    (= n k)
    (- k 1)
    (binomial(- n 1) (- k 1))
    

    However, you've got an error in one of your arguments to one of your calls to binomial:

    (define (binomial n k)
      (cond  ((or (= n 0) (= n k)) 1)
          (else (+ (binomial(n) (- k 1))(binomial(- n 1) (- k 1)))))) 
                            ***
    

    Based on the syntax described above (n) is an application where n should evaluate to a procedure, and that procedure will be called with no arguments. Of course, n here actually evaluates to an integer, which is not a procedure, and can't be called (hence “application: not a procedure”). You probably want to remove the parentheses around n:

    (binomial n (- k 1))
    

    It's also worth pointing out that Dr. Racket should have highlighted the same portion of code that I did above. When I load your code and evaluate (binomial 2 1), I get the following results in which (n) is highlighted:

    error in dr racket

    0 讨论(0)
  • 2021-01-26 15:58

    Your error is here:

    binomial(n)
    

    n is an integer, not a function. If you put parentheses around it like that, scheme tries to invoke an integer as a function, which naturally produces an error.

    0 讨论(0)
  • 2021-01-26 16:06

    This is the correct code:

     (define (binomial n k)
              (cond  ((or (= n 0) (= n k)) 1)
                  (else (+ (binomial n (- k 1))(binomial(- n 1) (- k 1)))))) 
    

    Problem is at here:

    (binomial (n) (- k 1))
    
    0 讨论(0)
提交回复
热议问题