loren
loren

Reputation: 63

Creating an evaluate function in racket

enter image description here Example of what function should do: (list 3 4 6 9 7) ←→ 3x^4 + 4x^3 + 6x^2 + 9x + 7

What I have so far:

(define (poly-eval x numlist)
(compute-poly-tail x numlist 0 0))

(define (compute-poly-tail xn list n acc)
    (cond
      [(null? list) acc]
    [else (compute-poly-tail (first list) (rest list)
                       (+ acc (* (first list) (expt xn n))) (+ n 1))]))



(check-expect(poly-eval 5 (list 1 0 -1)) 24)
(check-expect(poly-eval 0 (list 3 4 6 9 7)) 7)
(check-expect(poly-eval 2 (list 1 1 0 1 1 0))  54)

Expected results:

(check-expect(poly-eval 5(list 1 0 -1)) 24)
(check-expect(poly-eval  0 (list 3 4 6 9 7))7)
(check-expect(poly-eval 2 (list 1 1 0 1 1 0)) 54)

I am getting a run-time error. Can someone spot what I am doing wrong. I don't know why I am getting these results.

Upvotes: 0

Views: 631

Answers (2)

Óscar López
Óscar López

Reputation: 236140

There are a couple of errors in the code:

  • You need to process the coefficient's list in the correct order, corresponding to their position in the polynomial! you can either:
    • reverse the list from the beginning and process the coefficients from right to left (simpler).
    • Or start n in (sub1 (length numlist)) and decrease it at each iteration (that's what I did).
  • The order and value of the arguments when calling the recursion in compute-poly-tail is incorrect, check the procedure definition, make sure that you pass along the values in the same order as you defined them, also the first call to (first list) doesn't make any sense.
  • You should not name list a parameter, this will clash with the built-in procedure of the same name. I renamed it to lst.

This should fix the issues:

(define (poly-eval x numlist)
  (compute-poly-tail x numlist (sub1 (length numlist)) 0))

(define (compute-poly-tail xn lst n acc)
  (cond
    [(null? lst) acc]
    [else (compute-poly-tail xn
                             (rest lst)
                             (- n 1)
                             (+ acc (* (first lst) (expt xn n))))]))

It works as expected:

(poly-eval 5 (list 1 0 -1))
=> 24

(poly-eval 0 (list 3 4 6 9 7))
=> 7

(poly-eval 2 (list 1 1 0 1 1 0))
=> 54

Upvotes: 1

tjorchrt
tjorchrt

Reputation: 702

Build power coefficient and unknown list than use map function.

; 2*3^1+4*3^0
; input is 3 and '(2 4)
; we need '(3 3) '(2 4) '(1 0)
; use map expt build '(3^1 3^0)
; use map * build '(2*3^1 4*3^0)
; use foldr + 0 sum up

(define (poly-eval x coefficient-ls)
  (local ((define power-ls (reverse (build-list (length coefficient-ls) values)))
          (define unknown-ls (build-list (length coefficient-ls) (λ (i) x))))
    (foldr + 0 (map * coefficient-ls (map expt unknown-ls power-ls)))))


Upvotes: 1

Related Questions