数字x和系数列表,并返回应用于第一个参数的多项式1 + 2 +⋯+的结果

时间:2017-04-13 07:43:30

标签: recursion racket

这是我的功能:

(: compute-poly : Number (Listof Number) -> Number)
(define (compute-poly x numlist)
  (: compute-poly-tail : Number (Listof Number) Number Number -> Number)
  (define (compute-poly-tail xn list n acc)
    (if (null? list) acc
    (compute-poly-tail (first list) (rest list) (+ acc (* (first list) (expt xn n))) (+ n 1))))
  (compute-poly-tail x numlist 0 0))

我收到以下错误:

. Type Checker: type mismatch
  expected: Integer
  given: Number in: n
>

2 个答案:

答案 0 :(得分:0)

这个程序

#lang typed/racket

(: compute-poly : Number (Listof Number) -> Number)
(define (compute-poly x numlist)
  (: compute-poly-tail : Number (Listof Number) Number Number -> Number)
  (define (compute-poly-tail xn list n acc)
    (if (null? list) acc
    (compute-poly-tail (first list) (rest list) (+ acc (* (first list) (expt xn n))) (+ n 1))))
  (compute-poly-tail x numlist 0 0))

在版本6.7上运行时没有任何错误。

您使用的是哪个版本?

答案 1 :(得分:0)

第6行有两个问题:

(compute-poly-tail (first list) ... (+ acc (* (first list) (expt xn n))) (+ n 1))))

首先,您已在递归调用中将xn替换为(first list)。由于x用于添加的每个字词,因此对于每次递归调用,您应该拥有(compute-poly-tail xn ...)

其次,此函数的最后两个参数的顺序是(compute-poly-tail ... n acc),因此在递归调用中,您应该重新排列最后两个参数以与定义参数顺序对应。

所以第6行应该成为:

(compute-poly-tail xn ... (+ n 1) (+ acc (* (first list) (expt xn n))))))

以下是修订示例:

(: compute-poly (-> Number (Listof Number) Number Number))
(define (compute-poly x lst n)
  (if (null? lst)
      0
      (+ (* (car lst) (expt x n))
         (compute-poly x (cdr lst) (add1 n)))))

然后,

> (compute-poly 1 '(1 2 3 4 5) 0)
- : Number
15