17 Dec 2013

Typed Racket and Classes

posted by Asumu Takikawa

Recently we had our inaugural Racket Salon meetup here in Boston, graciously organized by Dan King. At the meetup I gave a short demo about the upcoming support for classes and object-oriented programming in Typed Racket. In this blog post, I’ll go over the concepts I presented in my demo.

Background


As many readers already know, Typed Racket is a gradually-typed sister language to Racket. That means it’s a statically-typed language that accommodates the idioms of Racket. Programs written in Racket should seamlessly port to Typed Racket with the addition of type annotations here and there. You can even keep some parts of the program dynamically-typed and Typed Racket will make sure those parts won’t break the type invariants via contracts.

Of course, supporting all Racket idioms is quite a lot of work, especially since it’s a constantly evolving language. One of the big pieces missing from Typed Racket right now is support for classes and objects. Since the GUI library heavily uses the class system, it’s important to support the object-oriented subset of Racket.

Supporting classes isn’t trivial though. There are a bunch of issues, but the main ones are: (1) the class system is built as a complex macro and so reconstructing the information needed to type-check is tricky, and (2) we need to make sure that interoperation between Racket and Typed Racket using classes/objects can be done safely.

I won’t go over the technical details about the implementation in this blog post, but contact me if you’re interested. In the rest of the blog post, I’ll show some examples to demonstrate what programming in Typed Racket with classes looks like. Just so you know, these examples won’t work in the current version of Typed Racket but will be supported in a future release.

Side note: If you like to live dangerously, you can track the experimental branch with support for classes here.

Fishes and types

To start out, let’s look at an untyped example from the Racket Guide on classes and objects. The following snippet defines a fish% class. The class has several features: an initialization argument named size, a private field named current-size, three methods get-size, grow, and eat.

(define fish%
  (class object%
    (init size)
    (define current-size size)
    (super-new)
    (define/public (get-size)
      current-size)
    (define/public (grow amt)
      (set! current-size (+ amt current-size)))
    (define/public (eat other-fish)
      (grow (send other-fish get-size)))))

The notation should seem mostly familiar if you’ve programmed in Java or other object-oriented languages. The % suffix is a convention for identifiers that are bound to class values. The object% value is the superclass of fish% and is the root class of all class hierarchies. The initialization argument size is used when constructing an instance of a class:

> (new fish% [size 3])
(object:fish% ...)

Note that in Racket, classes are just values that can be passed around like anything else. For example, you can even do silly things like define nested inheriting classes:

> (new (class (class object% (super-new) (displayln "superclass"))
         (super-new)
         (displayln "subclass")))
superclass
subclass
(object:eval:4:0 ...)

In practice, this feature is quite useful since it lets you define mixins easily. That’s a topic for another blog post.

Side note: In other words, Racket has first-class classes. This is a term you might see used in the programming language literature.

Adding types to the fish program is easy. First, we can introduce a type definition for the fish class.

(define-type Fish%
  (Class (init [size Real])
         [get-size (-> Real)]
         [grow (Real -> Void)]
         [draw (-> Pict)]
         [eat ((Instance Fish%) -> Void)]))

This type definition says that Fish% is a class type with the given initialization argument and methods types. Note that the type of the fish class Fish% is not the same as the type of its instances (Instance Fish%). This is an important distinction to make, since both the fish class value and fish object values may appear in the same program.

Side note: If you’re familiar with Typed Racket, you may be surprised that the recursive reference to Fish% in the type definition works. Future versions of Typed Racket will support implicit recursive type definitions.

With the type definition in hand, we can just annotate the class value with the type:

(: fish% : Fish%)
(define fish%
  (class object%
    (init size)
    (: current-size Real)
    (define current-size size)
    (super-new)
    (define/public (get-size)
      current-size)
    (define/public (grow amt)
      (set! current-size (+ amt current-size)))
    (define/public (eat other-fish)
      (grow (send other-fish get-size)))))

We do need an extra type annotation on the private field because its type isn’t included in the type definition above. This fish definition is a bit boring, so let’s spice it up a bit by making fishes drawable:

(define-type Fish%
  (Class (init [size Real])
         (get-size (-> Real))
         [grow (Real -> Void)]
         ; a type for the new method
         [draw (-> Pict)]
         [eat ((Instance Fish%) -> Void)]))
(: fish% : Fish%)
(define fish%
  (class object%
    (init size)
    (: current-size Real)
    (define current-size size)
    (super-new)
    (define/public (get-size)
      current-size)
    ; new draw method
    (define/public (draw)
      (standard-fish (* current-size 10)
                     (* current-size 5)))
    (define/public (grow amt)
      (set! current-size (+ amt current-size)))
    (define/public (eat other-fish)
      (grow (send other-fish get-size)))))

The new draw method that’s been added to the fish relies on some functions from the pict library. Since that’s not currently included in Typed Racket’s standard libraries, we need to give its exports some types:

; this would go at the top of the file before fish%
(require/typed pict
               [#:opaque Pict pict?]
               [standard-fish (Real Real [#:color String] -> Pict)])

The #:opaque import form in Typed Racket lets you create a new type that corresponds to some predicate, in this case pict?. It’s useful for bringing in datatypes from dynamically-typed Racket libraries. With that new type, we can give a type for the standard-fish function.

In the end, you can interact with some fish and draw them:

> (define dory (new fish% [size 5]))
> dory
- : (Instance Fish%)
(object:fish% ...)
> (send dory draw)
- : Pict
image
> (send dory eat dory)
> (send dory draw)
- : Pict
image

Conclusion: At Racket Salon, I talked about a few other things including mixins and converting a slightly larger program that uses the GUI library. They didn’t translate well to a blog setting so I didn’t include them here. Racket Salon was a fun event, so I encourage anyone in the Boston area to attend!

Typed Racket’s support for classes will land in a future version of Racket, possibly the release after v6.0.

more →

10 Aug 2013

Racket v5.3.6

posted by Eli Barzilay

Racket version 5.3.6 is now available from http://racket-lang.org/ Racket v5.3.6 is a bug-fix release. It eliminates errors from v5.3.5 that people have found over the summer.

more →

31 Jul 2013

RacketCon 2013 Signup

posted by Asumu Takikawa

RacketCon sign up is now open! http://bit.ly/racketconsignup2013

RacketCon will be held at Northeastern University in Boston on September 29. The details of the event can be found on the website: http://con.racket-lang.org

We also have a page on Lanyrd for the event: http://lanyrd.com/2013/racketcon/

More information about the schedule will be posted in the upcoming weeks.

more →

18 Jun 2013

Racket v5.3.5

posted by Eli Barzilay

Racket version 5.3.5 is now available from http://racket-lang.org/ This is a special-purpose release to match the arrival of “Realm of Racket” in bookstores. Racket v5.3.5 adds a single realm collection to the v5.3.4 release. The new collection contains the source code that readers of Realm may wish to use for experiments.

more →

29 May 2013

Marketplace: A language for network-aware programming

posted by Sam Tobin-Hochstadt

We are happy to announce the release of Marketplace, a new programming language for building functional network programs. Marketplace combines two fundamental ideas in a new way: nested virtual machines and publish/subscribe messaging. Nesting allows programs to isolate processes and to delimit conversations. While publish/subscribe generalizes point-to-point and broadcast messaging, it smoothly turns the appearance and disappearance of participants and resources into presence and absence messages. Such messages make it particularly easy to start and stop services and to manage resources based on demand.

Here is a simple TCP echo server written in Marketplace: 

#lang marketplace

(endpoint #:subscriber (tcp-channel ? (tcp-listener 5999) ?)
          #:conversation (tcp-channel from to _)
          #:on-presence (spawn #:child (echoer from to)))

;; echoer: TcpAddress TcpAddress -> Transition
(define (echoer from to)
  (transition stateless
    (endpoint #:subscriber (tcp-channel from to ?)
              #:on-absence (quit)
              [(tcp-channel _ _ data)
               (send-message (tcp-channel to from data))])))

The initial endpoint subscribes to TCP messages on port 5999. When a conversational partner appears, the endpoint spawns a new process that runs an echoer process. The latter is stateless and subscribes to TCP messages. When it gets messages with payload data, it sends them back out with the opposite addressing; when the TCP conversation disappears, it quits.

Thus far, we have built several real systems using Marketplace: a DNS server, a DNS proxy, and an SSH server.

The DNS proxy has handled DNS traffic for ourselves and other members of our lab for the last several months.

You can read an overview along with detailed documentation for Marketplace at http://tonyg.github.io/marketplace/.

To get the sources for Marketplace as well as the applications point your browser to https://github.com/tonyg/marketplace.

Enjoy!

Tony Garnock-Jones

Sam Tobin-Hochstadt

Matthias Felleisen

more →

08 May 2013

Racket v5.3.4

posted by Eli Barzilay

Racket version 5.3.4 is now available from http://racket-lang.org/

  • Extflonums (80-bit floating-point numbers) are supported on some x86/x86_64 platforms — including Windows, and including platforms where Racket is compiled to use SSE instructions for flonum arithmetic. Thanks to Michael Filonenko.

  • OS X: DrRacket and all of the other apps are now signed with an official key.

  • Tally Maze: a new game based an enumeration of 2d mazes.

  • The Optimization Coach, a DrRacket plugin, has been moved from the Racket distribution to the Racket package repository. Install it with: raco pkg install optimization-coach.

  • Redex: define-union-language now merges productions when languages define the same nonterminals. Thanks to William Bowman.

  • The srfi/19 library is now compatible with the date structure type exported by racket/base.

more →

08 May 2013

RacketCon 2013

posted by Asumu Takikawa

We are pleased to announce that (thirdRacketCon) will take place on September 29, 2013 at Northeastern University in Boston. This year, we plan to bring in several speakers from industry, as well as host talks from Racket developers and users.

Lunch will be provided.

On the Saturday (28th) before RacketCon, we plan to hold a hackathon to work on various Racket projects.

Registration will open during the summer, and we will post a detailed schedule of events around the same time. The conference website is at

http://con.racket-lang.org/

more →

25 Mar 2013

200!

posted by Asumu Takikawa

About a month ago, inspired by a mailing list post by Tim Brown, Racketeers started to write more solutions to Rosetta Code tasks for Racket. Just today, we’ve reached 200 entries in the Racket category!

This is a nice milestone, but we still have a ways to go. At 200 entries, Racket comes in at around 54th in the popularity rankings. So if you’re looking to practice your Racketeering skills, don’t hesitate to work on some of the remaining tasks.

To give you a taste of the kinds of solutions we have so far, here are some examples.

Mandelbrot:

(define (iterations a z i)
  (define z′ (+ (* z z) a))
  (if (or (= i 255) (> (magnitude z′) 2))
      i
      (iterations a z′ (add1 i))))

(define (iter->color i)
  (if (= i 255)
      (make-object color% "black")
      (make-object color% 
        (* 5 (modulo i 15)) (* 32 (modulo i 7)) 
          (* 8 (modulo i 31)))))

(define (mandelbrot width height)
  (define target (make-screen-bitmap width height))
  (define dc (new bitmap-dc% [bitmap target]))
  (for* ([x width] [y height])
    (define real-x (- (* 3.0 (/ x width)) 2.25))
    (define real-y (- (* 2.5 (/ y height)) 1.25))
    (send dc set-pen 
      (iter->color 
        (iterations 
          (make-rectangular real-x real-y) 0 0)) 1 'solid)
    (send dc draw-point x y))
  target)

> (mandelbrot300200)

Yin and Yang:

(define (yin-yang d)
  (define base
    (hc-append (inset/clip (circle d) 0 0 (- (/ d 2)) 0)
               (inset/clip (disk d) (- (/ d 2)) 0 0 0)))
  (define with-top
    (ct-superimpose
     base
     (cc-superimpose (colorize (disk (/ d 2)) "white")
                     (disk (/ d 8)))))
  (define with-bottom
    (cb-superimpose
     with-top
     (cc-superimpose (disk (/ d 2))
                     (colorize (disk (/ d 8)) "white"))))
  (cc-superimpose with-bottom (circle d)))


> (yin-yang 200)

Animate a pendulum:

#lang racket

(require 2htdp/image
         2htdp/universe)

(define (pendulum)
  (define (accel θ) (- (sin θ)))
  (define θ (/ pi 2.5))
  (define θ′ 0)
  (define θ′′ (accel (/ pi 2.5)))
  (define (x θ) (+ 200 (* 150 (sin θ))))
  (define (y θ) (* 150 (cos θ)))
  (λ (n)
    (define p-image 
      (underlay/xy 
        (add-line 
          (empty-scene 400 200) 200 0 (x θ) (y θ) "black")
            (- (x θ) 5) (- (y θ) 5) 
              (circle 5 "solid" "blue")))
    (set! θ (+ θ (* θ′ 0.04)))
    (set! θ′ (+ θ′ (* (accel θ) 0.04)))
    p-image))

(animate (pendulum))


Jensen's Device:

```racket
#lang algol60
begin
   integer i;
   real procedure sum (i, lo, hi, term);
      value lo, hi;
      integer i, lo, hi;
      real term;
      comment term is passed by-name, and so is i;
   begin
      real temp;
      temp := 0;
      for i := lo step 1 until hi do
         temp := temp + term;
      sum := temp
   end;
   comment note the correspondence between 
   the mathematical notation and the call to sum;
   printnln (sum (i, 1, 100, 1/i))
end

Thanks to all of the people who have contributed solutions so far!

more →

15 Feb 2013

Racket v5.3.3

posted by Eli Barzilay

Racket version 5.3.3 is now available from http://racket-lang.org/

This is a bug-fix release to address a flaw in DrRacket v5.3.2 concerning interactions between the contour window and the syntax coloring.

more →

31 Jan 2013

Racket v5.3.2

posted by Eli Barzilay

Racket version 5.3.2 is now available from http://racket-lang.org/ Core Libraries::

  • The new math library provides functions and data structures for working with numbers and collections of numbers. Functions include non-elementary (such as gamma, zeta, Lambert’s W), number-theoretic (factorization, modular arithmetic), linear algebra (arithmetic, decompositions), and statistical (expected values, order statistics, binning). Data structures include arbitrary-precision bigfloats, probability distributions, and multidimensional arrays.

  • The new file/untar, file/untgz, and file/unzip libraries support unpacking widely used archive formats.

  • The new lazy-require form allows programs to delay the loading and instantiation of helper modules until they are needed.

  • The new data/bit-vector library provides an implementation of bit vectors (a mutable sequence of booleans) supporting popcount.

  • The racket/generic library allows the specification of default method implementations for core datatypes.

  • The openssl library can verify hostnames and use the operating system’s certificate store to verify certificates.

Package System::

  • A new package system is in beta release. This system will become Planet’s successor. It differs significantly from the latter. For details, please read the documentation at http://docs.racket-lang.org/planet2/ and list your packages on the new index at https://pkg.racket-lang.org/.

  • The raco test command supports testing by collection and package, in addition to by directory and file, with the -c and -p options.

Teaching Libraries::

  • batch-io: the read and write functions work on Unix-style standard input and output.

DrRacket::

  • DrRacket’s GUI is more responsive.

  • The automatic parenthesis insertion mode is improved.

Scribble::

  • Scribble renders Markdown format files via the --markdown command-line flag. Example use case: Generate documentation hosted on GitHub or BitBucket.

  • Documentation cross-reference information is stored in an SQLite3 database, which means that SQLite3 is required for building Racket documentation on Unix/Linux machines (but SQLite3 is included in Racket distributions for Windows and Mac OS X).

Using a database for cross-reference information significantly reduces the initial footprint of DrRacket, since DrRacket no longer needs to load all cross-reference information.

Typed Racket::

  • Typed Racket programs can require plot/typed to draw plots. List- and vector-accepting functions accept general sequences.

  • Typed Racket supports Racket’s delimited continuation and continuation mark operators.

Redex::

  • Added more support for define-judgment-form, including random generation for well-formed judgments and visualization of judgments.

Deprecation:: The following have been removed in this release:

  • the planet command-line tool; use raco planet instead.

The following has been deprecated and will be removed in the August 2013 release:

  • the mzlib/class100 library; use racket/class instead.
more →

Made with Frog, a static-blog generator written in Racket.
Source code for this blog.