Skip to content

Instantly share code, notes, and snippets.

@saludes
Created December 18, 2014 09:08
Show Gist options
  • Save saludes/5eb1550657b29e527045 to your computer and use it in GitHub Desktop.
Save saludes/5eb1550657b29e527045 to your computer and use it in GitHub Desktop.
#lang racket
(require rackunit racket/generator)
(define (poly->pairs p)
(let ([cs (poly-coefs p)])
(foldl
(λ (k c xs)
(if (zero? c)
xs
(cons (cons c k) xs)))
'()
(range (length cs))
(reverse cs))))
(define (pterm r port k c)
(unless (= c 1) (r c port) (write-string " * " port))
(case k
[(1) (write-string "x" port)]
[(0) void]
[else (write-string "x" port) (write-string "^" port) (r k port)]))
(define (poly-print poly port mode)
(let* ([cs (poly-coefs poly)]
[string-var "x"]
[ecs (filter (λ (ec) (not (zero? (cdr ec))))
(map cons (range (length cs)) (reverse cs)))]
[recur (case mode
[(#t) write]
[(#f) display]
[else (λ (x port) (print x port mode))])]
[recur-term
(λ (e c)
(unless (= c 1) (recur c port))
(case e
[(0) (void)]
[(1) (write-string string-var port)]
[else (write-string (string-append string-var "^") port) (recur e port)]))])
(let loop ([ec (reverse ecs)])
(match ec
['() (recur 0 port)]
[(list (cons e c)) (recur-term e c)]
[(list-rest (cons e1 c1) (cons e2 c2) rest)
(recur-term e1 c1)
(write-string (if (positive? c2) " + " " ") port)
(loop (cons (cons e2 c2) rest))]))))
(struct poly [coefs]
#:methods gen:custom-write
[(define write-proc poly-print)])
;; Evaluate polynomial
(define (eval-poly poly x [s +] [p *])
(foldl (λ (c y) (s (p y x) c)) 0 (poly-coefs poly)))
;; Recall the polynomial
(define recall
(generator ()
(let* ([display/yield
(λ (k) (yield (displayln (format "Give the value of p at ~a" k))))]
[p1 (display/yield 1)]
[N (add1 p1)]
[pN (display/yield N)])
(recall-polynomial N pN))))
(define (recall-polynomial N pN)
(let loop ([y pN] [coefs '()])
(cond
[(zero? y) coefs]
[else
(let-values ([(y a) (quotient/remainder y N)])
(loop y (cons a coefs)))])))
;; testing
(test-begin
(let* ([p (poly '(1 2 0 2 1))]
[p1 (eval-poly p 1)]
[pN (eval-poly p (add1 p1))])
(recall)
(recall p1)
(check-equal? (recall pN) (poly-coefs p))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment