Robert
Robert

Reputation: 2812

Racket: syntax for module to export the public functions of a class

How can I use provide so that the module export all the public functions from a class?

On this website, I found out how to export all the get/set functions from a struct [1]. I didn't find any syntax for classes.

#lang racket
(provide (struct-out foo-struct))
(struct foo-struct (biz bop))

[1] How to provide all functions associated with a struct in Racket

Upvotes: 1

Views: 259

Answers (2)

Sorawee Porncharoenwase
Sorawee Porncharoenwase

Reputation: 6502

TLDR: you simply need to provide the class value.

The struct form defines accessors, setters, predicate, constructor, etc. Therefore, you need to provide them all if you want your client to have a full capability to manipulate structs:

(struct foo (bar) #:mutable)
;; this defines
;; constructor: foo
;; accessors: foo-bar
;; setters: set-foo-bar!
;; predicate: foo?

The class form, on the other hand, returns a first-class class value, and does not define anything at all. The class value then can be utilized by using forms such as new and send (which is provided by #lang racket already).

(class object% (super-new))
;; this defines nothing, but results in a class value

So it suffices to just provide an identifier bound to this class value. Here's an example:

;; lib.rkt

#lang racket

(define human% 
  (class object% (super-new)
    (define/public (speak)
      (displayln "hello world!"))))

(provide human%)
;; client.rkt

#lang racket

(require "lib.rkt")
(send (new human%) speak)
;; display hello world!

Upvotes: 3

Atharva Shukla
Atharva Shukla

Reputation: 2137

book.rkt:

#lang racket

(provide book-class%)

(define book-class%
  (class object%
    (field (pages 5))
    (define/public (letters)
      (* pages 500))
    (super-new)))

In another file:

#lang racket

(require "book.rkt")

(define class-o (new book-class%))

(send class-o letters)
; => 2500

define/public was used to make the method in the class public, when the class is exported, that function can be used with send.

Upvotes: 3

Related Questions