Racket

Racket is a language for making languages: #lang lines select different languages (Typed Racket, Scribble for docs, #lang datalog, #lang slideshow, teaching languages like #lang htdp/bsl). It comes with batteries: a GUI toolkit, web server, plotting, package manager (raco pkg install), and the DrRacket IDE.

Book: *How to Design Programs* (HtDP), *Realm of Racket*, *Beautiful Racket* (making languages).

#lang racket                              ; every file declares its language

(provide greet)                           ; export from this module
(require racket/string net/url)           ; import libraries

(define (greet name) (string-append "Hello, " name "!"))

;; Structs
(struct point (x y) #:transparent)
(define p (point 3 4))
(point-x p)                               ; 3

;; Pattern matching
(define (area shape)
  (match shape
    [(list 'circle r) (* pi r r)]
    [(list 'rect w h) (* w h)]
    [_ (error "unknown shape")]))
(area '(rect 2 3))                        ; 6

;; Contracts
(define/contract (safe-div a b)
  (-> number? (and/c number? (not/c zero?)) number?)
  (/ a b))
;; (safe-div 1 0) raises a contract violation blaming the caller

;; Comprehensions
(for/list ([x '(1 2 3)] #:when (odd? x)) (* x 10))   ; '(10 30)
(for/hash ([k '(a b)] [v '(1 2)]) (values k v))      ; '#hash((a . 1) (b . 2))

;; Exceptions
(with-handlers ([exn:fail? (lambda (e) (exn-message e))])
  (error "boom"))                         ; "boom"

;; Hygienic macros with syntax-parse (better errors)
(require (for-syntax syntax/parse))
(define-syntax (my-when stx)
  (syntax-parse stx
    [(_ test:expr
…
#lang typed/racket                        ; gradual static typing
(: add (-> Integer Integer Integer))
(define (add a b) (+ a b))
(struct point ([x : Real] [y : Real]))