[racket] question about classes
I'm trying to learn to use classes in Racket. I did some successful simple
experiments then moved on to inheritance. When I try to use the code
below, the following code:
(new sqrtcontfrac% [sqrval i]) leads to the message: sqr: expected
argument of type <number>; given #<undefined>
Why isn't start being inherited properly? Any help is appreciated!
Thanks,
-joe
Here is the class code:
(module contfrac racket
(require racket/class)
(provide gencontfrac%)
(provide sqrtcontfrac%)
; class that represents the continued fraction of a general irrational
number and acts as a base class for continued fractions of other sorts
(define gencontfrac%
(class object%
(super-new)
(init-field start) *; here start is defined*
(init-field repeat)
; create a n-long list of repeat digits (in reverse order - which
makes creation of a rational easier)
(define/private (expand-repeat n)
(let lp ([c n] [rl '()])
(if (zero? c) rl (lp (sub1 c) (cons (repeat) rl)))))
; create a rational representation using the passed number of repeat
digits
(define/public (rational-rep n)
(define rdiglst (expand-repeat n))
(let lp ([rdigs (rest rdiglst)] [res (first rdiglst)])
(if (empty? rdigs) (+ start (/ 1 res)) (lp (rest rdigs) (+ (first
rdigs) (/ 1 res))))))
; display the continued fraction
(define/public (show)
(printf "[~a; ~a]~n" start repeat))
))
; define a class that represents the continued fraction of a square root
(define sqrtcontfrac%
(class gencontfrac%
(init sqrval)
(super-new [start (integer-sqrt sqrval)] [repeat (build-repeat
sqrval)])
(inherit rational-rep show)
(inherit-field start repeat)
; build the repeating sequence (see
http://en.wikipedia.org/wiki/Continued_fraction)
(define/private (build-repeat n)
(let loop ([adder start] [denom (- n (sqr start))] [result '()]) *;
this is where the error is occurring *
(cond [(zero? denom) '()] ; perfect square
[(= 1 denom) (reverse (cons (+ start adder) result))] ;
found the end of the repeating sequence
[else
(let* ([nextval (quotient (+ adder (integer-sqrt n))
denom)] [nextadd (- (* nextval denom) adder)])
(loop nextadd (quotient (- n (sqr nextadd)) denom) (cons
nextval result)))])))
; create a n-long list of repeat digits (in reverse order - which
makes creation of a rational easier)
(define/private (expand-repeat n)
(let lp ([c n] [rl '()] [stock repeat])
(if (zero? c) rl (lp (sub1 c) (cons (first stock) rl) (if (empty?
(rest stock)) repeat (rest stock))))))
))
)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.racket-lang.org/users/archive/attachments/20120520/9ace210a/attachment-0001.html>