Racket

Racket grew out of Scheme. It began as PLT Scheme in 1995 and was renamed Racket in 2010. Its hybrid nature is deliberate: paradigms are libraries, and you can even define a new language and use it with #lang.

Paradigm: Popular Hybrid Languages

What Makes Racket Special

  • A language for making languages. Every file starts with #lang, which selects the language of that module. Racket, Typed Racket, Scribble and Datalog are all #langs.
  • Powerful macros. define-syntax-rule adds new syntax, and hygiene stops macros from capturing your variables by accident. See Lisp for the origin of the idea.
  • Functional core. Functions are first-class, lists are the main data structure, and tail calls do not grow the stack, as in Scheme.
  • Objects when you want them. The racket/class library gives classes, interfaces and mixins, built with macros rather than added to the core.
  • Pattern matching and contracts. match destructures data, and contracts check function arguments and results at run time.
  • Typed Racket. A separate #lang typed/racket adds static types to code that is otherwise the same, so you can migrate gradually.

Example: Functions, objects, pattern matching and a new macro

#lang racket

;; functional
(define (square x) (* x x))
(map square '(1 2 3 4))                 ; '(1 4 9 16)

;; object-oriented
(define counter%
  (class object%
    (init-field [n 0])
    (super-new)
    (define/public (next!) (set! n (add1 n)) n)))
(define c (new counter%))
(send c next!)                          ; 1
(send c next!)                          ; 2

;; pattern matching
(define (describe v)
  (match v
    [(list 'point x y) (format "point at ~a,~a" x y)]
    [(? number? n)     (format "number ~a" n)]
    [_                 "unknown"]))
(describe '(point 3 4))                 ; "point at 3,4"

;; a new piece of syntax
(define-syntax-rule (swap! a b)
  (let ([t a]) (set! a b) (set! b t)))
(define x 1)
(define y 2)
(swap! x y)
(list x y)                              ; '(2 1)

How It Works

  • #lang racket loads the full language. In a module, each top-level expression prints its value, which is what the comments show.
  • counter% is a class. send calls a method, and the object keeps its own n.
  • match tries each pattern in order, binding x and y when the list has the shape (point x y).
  • swap! is not a function. The macro rewrites (swap! x y) into the let form before the program runs, so it can assign to x and y, which a function could not do.

History and Where It Is Used

Racket is used in teaching (the How to Design Programs curriculum), programming language research, and to implement domain-specific languages. Scribble, the documentation language, and the DrRacket editor are written in Racket. It is a good language for learning how languages work.

Learn More