1

My question is quite similar to this Declaring an array inside a class, and setting its size with the constructor

But i am going to work in racket. So exactly i want to implement a class which represent object polygon (any number of sides). Polygon is exactly determined by number of sides and array of vertices in clockwise order. So my class must contain those attributes. Is there some way to implement this in racket. I am not an expert in racket (i have done only functional programming in racket yet, but i want to use built in classes and vectors in my course project). Also is there any other way of representing polygons in abstract manner

2
  • Why do you need a class? Eg. are you in need of polymorfism? If not, wouldn't a simple struct be enough? Commented Mar 9, 2017 at 21:49
  • Yes, need inheritance as well as private member functions. Commented Mar 9, 2017 at 21:52

1 Answer 1

1

First, I should state that I agree with @Slywester that much of the time you do not actually want to use classes in Racket.

But, sometimes you do, which is why they are provided.

The keyword you are looking for is init-field, this declares a public field in a racket class that is accessible to both members in and out of the class. (If you don't want it to be a public field you're better off just using init, but then its a little harder to use the variable in methods.)

(define polygon%
  (class object%
    (super-new)
    (init-field size)
    (define vec (make-vector size))
    (define/public (get-vector)
      vec)))

Fields initialized with init-field are also available in the scope of the class, and this example creates an array called vec, that has the length of the given field.

From here, you can instantiate the class with new, and get the array with send get-vector:

> (define p (new polygon% [size 10]))
> (send p get-vector)
'#(0 0 0 0 0 0 0 0 0 0)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.