[racket] question about classes
On May 20, 2012, at 11:02 AM, Joe Gilray wrote:
> 1) Is what I've done an abomination? Am I simply abusing inheritance?
You are changing a part of a recursive nest of methods, which is what inheritance is all about.
> 2) To make the code below work, I had to make expand-repeat public as I couldn't override a private function. Is there another way (something like "protected" in C++)?
(define-local-member-name expand-repeat)
Don't export expand-repeat and nobody can run this method from outside.
#lang racket
(require racket/class)
(provide
gencontfrac%
sqrtcontfrac%)
;; ---------------------------------------------------------------------------------------------------
(define-local-member-name expand-repeat)
; 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 repeat)
; create a n-long list of repeat digits in reverse order,
; which facilitates the creation of a rational
(define/public (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%
(inherit-field start)
(init sqrval)
(super-new [start (integer-sqrt sqrval)] [repeat (void)])
(inherit rational-rep show)
(define repeatlst (build-repeatlst sqrval))
; build the repeating sequence (see http://en.wikipedia.org/wiki/Continued_fraction)
(define/private (build-repeatlst n)
(define start (integer-sqrt n))
(let loop ([adder start] [denom (- n (sqr start))] [result '()])
(cond
[(zero? denom)
; perfect square:
'()]
[(= 1 denom)
; found the end of the repeating sequence:
(reverse (cons (+ (integer-sqrt n) adder) result))]
[else
(let* ([nextval (quotient (+ adder start) denom)] [nextadd (- (* nextval denom) adder)])
(loop nextadd (quotient (- n (sqr nextadd)) denom) (cons nextval result)))])))
(define/override (expand-repeat n)
(let lp ([c n] [rl '()] [stock repeatlst])
(cond
[(zero? c) rl]
[else
(define r (rest stock))
(lp (sub1 c) (cons (first stock) rl) (if (empty? r) repeatlst r))])))
; accessor
(define/public (get-repeatlst) repeatlst)))
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.racket-lang.org/users/archive/attachments/20120520/dd9fd6ec/attachment.html>