Racket features
≈ 11 min read
Names in other languages
No names in other languages are held for this entry yet.
Article bodies are English and are not machine-translated. A name in another language is not a translation of the article.
Racket has been under active development as a vehicle for programming language research since the mid-1990s, and has accumulated many features over the years. This article describes and demonstrates some of these features. Note that one of Racket's main design goals is to accommodate creating new programming languages, both domain-specific languages and completely new languages. Therefore, some of the following examples are in different languages, but they are all implemented in Racket. Please refer to the main article for more information. The core Racket implementation is highly flexible. Even without using dialects, it can function as a full-featured scripting language, capable of running both with and without windows-native graphical user interface (GUI), and capable of tasks from web server creation to graphics.
Racket has been under active development as a vehicle for programming language research since the mid-1990s, and has accumulated many features over the years. This article describes and demonstrates some of these features. Note that one of Racket's main design goals is to accommodate creating new programming languages, both domain-specific languages and completely new languages. Therefore, some of the following examples are in different languages, but they are all implemented in Racket. Please refer to the main article for more information.
The core Racket implementation is highly flexible.
Even without using dialects, it can function as a full-featured scripting language, capable of running both with and without windows-native graphical user interface (GUI), and capable of tasks from web server creation to graphics. lang racket (define listener (tcp-listen 12345)) (let echo-server () ;; create a TCP server (define-values (in out) (tcp-accept listener)) ;; handle an incoming connection in a (green) thread (thread (λ () (copy-port in out) (close-output-port out))) ;; and immediately loop back to accept more clients (echo-server)) The combination of dynamic compilation and a rich system interface makes Racket a capable scripting language, similar to Perl or Python.
The following example demonstrates walking a directory tree, starting at the current directory. It uses the in-directory function to construct a sequence that walks the tree.
The for form binds path to each path in the sequence, and regexp-match? tests these paths against the given regexp pattern. lang racket Finds Racket sources in all subdirs (for ([path (in-directory)]) ; iterate over the current tree (when (regexp-match? #rx"[.]rkt$" path) (printf "source file: ~a\n" path))) The next example uses a hash table to record previously seen lines and print only unique ones. lang racket Report each unique line from stdin (let ([saw (make-hash)]) (for ([line (in-lines)]) (unless (hash-ref saw line #f) (displayln line)) (hash-set! saw line #t))) Both of these programs can be run in DrRacket, or on the command line, via the racket executable.
Racket ignores an initial shebang line, making it possible to turn such programs into executable scripts. The following script demonstrates this, in addition to using Racket's library for command-line argument parsing: !/usr/bin/env racket lang racket (command-line #:args (base-dir ext re) (for ([p (in-directory)] #:when (regexp-match? (string-append "[.]" ext "$") p) [(line num) (in-indexed (file->lines p))]) (when (regexp-match?
(pregexp re) line) (printf "~a:~a: ~a~n" p (+ num 1) line)))) The script is a grep-like utility, expecting three command-line arguments: a base directory, a filename extension, and a (perl-compatible) regular expression.
It scans the base directory for files with the given suffix, and prints lines matching the regexp pattern. lang racket (define listener (tcp-listen 12345)) per-connection handler (define (handler in out) (copy-port in out) (close-output-port out)) (let echo-server () (define-values (in out) (tcp-accept listener)) (thread (λ () (let ([c (make-custodian)]) (parameterize ([current-custodian c]) (handler in out) (custodian-shutdown-all c))))) (echo-server)) Custodians, combined with the memory accounting feature of the 3m garbage collector, and several added runtime parameters that control more aspects of the runtime, make it possible to create fully safe sandboxed execution contexts.
The racket/sandbox library provides this kind of functionality in a simple way. The following example creates a read–eval–print loop (REPL) server on the specified port; connecting to this port will look like a plain Racket REPL, except that the evaluation is subject to the various protection aspects of the sandbox. For example, it is not possible to access the file system from this REPL, create network connection, run subprocesses, or use too much time or memory.
(In fact, this REPL is safe enough to be given out publicly.) lang racket (require racket/sandbox) (define e (make-evaluator 'racket/base)) (let-values ([(i o) (tcp-accept (tcp-listen 9999))]) (parameterize ([current-input-port i] [current-output-port o] [current-error-port o] [current-eval e] [current-read-interaction (λ (x in) (read in))]) (read-eval-print-loop) (fprintf o "\nBye...\n") (close-output-port o))) lang web-server/insta A tiny "hello world" web server (define (start request) (response/xexpr '(html (body "Hello World")))) Racket also includes the functions needed to write scrapers and robots.
As an example, the following function lists the Google results for a search string. lang racket Simple web scraper (require net/url net/uri-codec) (define (let-me-google-that str) (let* ([g "http://www.google.com/search?q="] [u (string-append g (uri-encode str))] [rx #rx"(? ).*?(?= )"]) (regexp-match* rx (get-pure-port (string->url u))))) The library also includes support for protocols other than http: lang racket Sending a timed email alert from racket (require net/sendmail) (sleep (* (- (* 60 4) 15) 60)) ; wait 3h 45m (send-mail-message (getenv "EMAIL") "Parking meter alert!" (list (getenv "EMAIL")) null null '("Time to go out and move the car.")) lang racket A picture (require 2htdp/image) (let sierpinski ([n 8]) (if (zero? n) (triangle 2 'solid 'red) (let ([t (sierpinski (- n 1))]) (freeze (above t (beside t t)))))) DrRacket editors can contain images, and DrRacket displays image values just like any other type of value (such as integers or lists).
Running the above program, for example, actually displays a Sierpinski triangle, which can be cut and pasted into another program. The plot library constructs image values for more mature audiences and needs.
For example, the following program plots the sum of two \mathbb{R} \times \mathbb{R} \times \mathbb{R} \rightarrow \mathbb{R} (three-dimensional) Gaussians, as concentric, partially transparent surfaces: lang racket Visualize a sum of two 3D Gaussians as concentric isosurfaces Note: this example requires Racket 5.2 or later (require plot) Returns an R x R x R -> R Gaussian function centered at (cx,cy,cz) (define ((gaussian cx cy cz) x y z) (exp (- (+ (sqr (- x cx)) (sqr (- y cy)) (sqr (- z cz)))))) Lifts + to operate on three-argument functions (define ((f3+ g h) x y z) (+ (g x y z) (h x y z))) Constructs an image value representing the sum of two Gaussians (plot3d (isosurfaces3d (f3+ (gaussian 0 0 0) (gaussian 1.5 -1.5 0)) -1 2.5 -2.5 1 -1 1 #:label "g")) ; labeling adds a legend Here, the isosurfaces3d function requires a three-argument function for its first argument, which the curried f3+ supplies.
Besides constructing image values, plot can also write files in Portable Network Graphics (PNG), Portable Document Format (PDF), PostScript and Scalable Vector Graphics (SVG) formats. lang racket/gui A GUI guessing game (define secret (random 5)) (define f (new frame% [label "Guessing game"])) ; toplevel window (define t (new message% [parent f] [label "Can you guess the number I'm thinking about?"])) (define p (new horizontal-pane% [parent f])) ; horizontal container (define ((make-check i) btn evt) (message-box "." (cond [( i secret) "Too big"] [else "Exactly!"])) (when (= i secret) (send f show #f))) ; success => close window (for ([i (in-range 10)]) ; create all buttons (make-object button% (format "~a" i) p (make-check i))) (send f show #t) ; show the window to start the application The GUI can be hand-coded in this way or with the help of a GUI designer program available on PLaneT. lang slideshow (slide (text "Slideshow" 'roman 56) (text "Making presentations in Racket" 'roman 40)) (slide #:title "Some pictures" (apply vc-append (for/list ([i 5]) (define (scale+color p c) (colorize (scale p (/ (add1 i) 5)) c)) (hc-append (scale+color (filled-rectangle 100 50) "darkblue") (scale+color (disk 100) "darkgreen") (scale+color (arrow 100 (/ pi 6)) "darkred") )))) Extension packages also exist on PLaneT, for example to include LaTeX elements. lang racket/base Simple use of the FFI (require ffi/unsafe) (define mci-send-string (get-ffi-obj "mciSendStringA" "Winmm" (_fun _string [_pointer = #f] [_int = 0] [_pointer = #f] -> [ret : _int]))) (mci-send-string "play sound.wav wait") lang scribble/base @; Generate a PDF or an HTML document using `scribble' @(require (planet neil/numspell)) @title{99 Bottles of Beer} In case you need some @emph{blah blah} in your life. @(apply itemlist (for/list ([n (in-range 99 0 -1)]) (define N (number->english n)) (define N-- (number->english (sub1 n))) @item{@string-titlecase[N] bottles of beer on the wall, @N bottles of beer.
Take one down, pass it around, @N-- bottles of beer on the wall.})) The most striking feature of the Scribble languages is their use of a new syntax, which is designed specifically for textually rich code. The syntax allows free-form text, string interpolation, customizable quotations, and is useful in other applications such as preprocessing text, generating text, and HTML template systems.
Note that the syntax extends plain S-expressions, and is implemented as an alternative input for such expressions. lang scribble/text Hi, I'm a text file -- run me. @(define (thrice . text) @list{@text, @text, @text}) @thrice{SPAM}! @thrice{HAM}! lang typed/racket Using higher-order occurrence typing (define-type Str-or-Num (U String Number)) (: tog ((Listof Str-or-Num) -> String)) (define (tog l) (apply string-append (filter string? l))) (tog (list 5 "hello " 1/2 "world" (sqrt -1))) lang lazy An infinite list: (define fibs (list* 1 1 (map + fibs (cdr fibs)))) Print the 1000th Fibonacci number: (print (list-ref fibs 1000)) lang datalog ancestor(A, B) :- parent(A, B). ancestor(A, B) :- parent(A, C), D = C, ancestor(D, B). parent(john, douglas). parent(bob, john). ancestor(A, B)? lang htdp/bsl Any key inflates the balloon (require 2htdp/image) (require 2htdp/universe) (define (balloon b) (circle b "solid" "red")) (define (blow-up b k) (+ b 5)) (define (deflate b) (max (- b 1) 1)) (big-bang 50 (on-key blow-up) (on-tick deflate) (to-draw balloon 200 200)) lang algol60 begin integer procedure SIGMA(x, i, n); value n; integer x, i, n; begin integer sum; sum := 0; for i := 1 step 1 until n do sum := sum + x; SIGMA := sum; end; integer q; printnln(SIGMA(q*2-1, q, 7)); end
Plai and plai-typed
- lang plai #lang plai-typed Another supported language is plai which like racket can be typed or untyped. "Modules written in plai export every definition (unlike scheme)." "The Typed PLAI language differs from traditional Racket most importantly by being statically typed. It also gives some useful new constructs: define-type, type-case, and test." lang racket (provide (except-out (all-from-out racket) #%top #%app) (rename-out [top #%top] [app #%app])) (define-syntax-rule (top . x) 'x) (define-syntax-rule (app f . xs) (if (hash? f) (hash-ref f . xs) (f . xs))) This language: provides everything from the racket language, so it is a somewhat similar variant, except for two special "hook macros" that implement unbound variable lookup and function calls, instead of these, new forms are provided to implicitly quote all unknown variables allow hash tables to be used as functions, where the arguments are used for hash-table lookup. If this code is stored in a mylang.rkt file, it can be used as follows: lang s-exp "mylang.rkt" ; sexpr syntax, using mylang semantics (define h (make-hasheq)) (hash-set! h A B) ; A and B are self-evaluating here (h A) ; the hash table is used as a function
External links
docs.racket
Text derived from https://en.wikipedia.org/w/index.php?oldid=1376575098 under CC BY-SA 4.0; modifications have been made.