HOME

TheInfoList



OR:

Racket has been under active development as a vehicle for
programming language research Programming language theory (PLT) is a branch of computer science that deals with the design, implementation, analysis, characterization, and classification of formal languages known as programming languages. Programming language theory is clos ...
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 languages, both
domain-specific language A domain-specific language (DSL) is a computer language specialized to a particular application domain. This is in contrast to a general-purpose language (GPL), which is broadly applicable across domains. There are a wide variety of DSLs, ranging f ...
s 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 GUI, and capable of tasks from web server creation to graphics.


Runtime support


Garbage collection, tail calls, and space safety

Racket can use three different garbage collectors: * Originally, the conservative
Boehm garbage collector The Boehm–Demers–Weiser garbage collector, often simply known as Boehm GC, is a Tracing_garbage_collection#Precise_vs._conservative_and_internal_pointers, conservative Garbage collection (computer science), garbage collector for C (programming ...
was used. However, conservative collection is impractical for long-running processes such as a web server—such processes tend to slowly leak memory. In addition, there are pathological cases where a conservative collector leaks memory fast enough to make certain programs impossible to run. For example, when traversing an infinite list, a single conservative mistake of retaining a pointer leads to keeping the complete list in memory, quickly overflowing available memory. This collector is often referred to as "CGC" in the Racket community. * SenoraGC is an alternative conservative garbage collector that is intended mainly for debugging and memory tracing. * The moving memory manager (aka "3m") is a precise garbage collector, and it has been Racket's default collector since 2007. This collector is a generational one, and it supports memory accounting via custodians (see below). The collector is implemented as a C source transformer that is itself written in Racket. Therefore, the build process uses the conservative collector for
bootstrapping In general, bootstrapping usually refers to a self-starting process that is supposed to continue or grow without external input. Etymology Tall boots may have a tab, loop or handle at the top known as a bootstrap, allowing one to use fingers ...
. Like all implementations in the
Scheme A scheme is a systematic plan for the implementation of a certain idea. Scheme or schemer may refer to: Arts and entertainment * ''The Scheme'' (TV series), a BBC Scotland documentary series * The Scheme (band), an English pop band * ''The Schem ...
family, Racket implements full
tail call elimination In computer science, a tail call is a subroutine call performed as the final action of a procedure. If the target of a tail is the same subroutine, the subroutine is said to be tail recursive, which is a special case of direct recursion (computer s ...
. Racket takes this further: the language is made fully safe-for-space, via
live variable analysis In compilers, live variable analysis (or simply liveness analysis) is a classic data-flow analysis to calculate the variables that are ''live'' at each point in the program. A variable is ''live'' at some point if it holds a value that may be neede ...
. This complements the precise garbage collector and in some cases, like in the implementation of Lazy Racket, the two features are crucial for proper execution. This is in addition to additional compiler optimizations such as
lambda lifting Lambda lifting is a meta-process that restructures a computer program so that functions are defined independently of each other in a global scope. An individual "lift" transforms a local function into a global function. It is a two step process, ...
and
just-in-time compilation In computing, just-in-time (JIT) compilation (also dynamic translation or run-time compilations) is a way of executing computer code that involves compilation during execution of a program (at run time) rather than before execution. This may cons ...
.


System interface and scripting

Racket's system interface includes asynchronous
non-blocking I/O In computer science, asynchronous I/O (also non-sequential I/O) is a form of input/output processing that permits other processing to continue before the transmission has finished. A name used for asynchronous I/O in the Windows API is overlappe ...
,
green thread In computer programming, a green thread is a thread that is scheduled by a runtime library or virtual machine (VM) instead of natively by the underlying operating system (OS). Green threads emulate multithreaded environments without relying on an ...
s, synchronization channels, semaphores, sub-processes, and TCP sockets. The following program starts an "echo server" on port 12345. #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 additional clients (echo-server)) The combination of dynamic compilation and a rich system interface makes Racket a capable scripting language, similar to
Perl Perl is a family of two high-level, general-purpose, interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it also referred to its redesigned "sister language", Perl 6, before the latter's name was offici ...
or
Python Python may refer to: Snakes * Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia ** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia * Python (mythology), a mythical serpent Computing * Python (pro ...
. 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 A regular expression (shortened as regex or regexp; sometimes referred to as rational expression) is a sequence of characters that specifies a search pattern in text. Usually such patterns are used by string-searching algorithms for "find" or ...
pattern. #lang racket ;; Finds Racket sources in all subdirs (for ( ath (in-directory) ; iterate over the current tree (when (regexp-match? #rx" kt$" 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 ( aw (make-hash) (for ( ine (in-lines) (unless (hash-ref saw line #f) (displayln line)) (hash-set! saw line #t))) Both of these programs can be run in
DrRacket Racket is a general-purpose, multi-paradigm programming language and a multi-platform distribution that includes the Racket language, compiler, large standard library, IDE, development tools, and a set of additional languages including Typed R ...
, or on the command line, via the racket executable. Racket ignores an initial shebang line, making it possible to turn such programs to 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 ( (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 A filename extension, file name extension or file extension is a suffix to the name of a computer file (e.g., .txt, .docx, .md). The extension indicates a characteristic of the file contents or its intended use. A filename extension is typically d ...
, and a (perl-compatible) regular expression. It scans the base directory for files with the given suffix, and print lines matching the regexp pattern.


Resource management and sandboxing

Racket features the concept of a "custodian": a kind of value that acts as a resource manager. This is often used in network servers, where each connection is dealt with in a new custodian, making it easy to "clean-up" all resources that might have been left open by the handler (e.g., open ports). The following extends the "echo server" example with such a custodian use: #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 ( (make-custodian) (parameterize ( urrent-custodian c (handler in out) (custodian-shutdown-all c))))) (echo-server)) Custodians, combined with the memory accounting feature of the 3m garbage collector, and a number of additional runtime parameters that control additional aspects of the runtime, make it possible to create completely safe sandboxed execution contexts. The racket/sandbox library provides this kind of functionality in a simple way. The following example creates a "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 filesystem 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 ( urrent-input-port i urrent-output-port o urrent-error-port o urrent-eval e urrent-read-interaction (λ (x in) (read in)) (read-eval-print-loop) (fprintf o "\nBye...\n") (close-output-port o)))


Web and network programming

The next example implements a
web server A web server is computer software and underlying hardware that accepts requests via HTTP (the network protocol created to distribute web content) or its secure variant HTTPS. A user agent, commonly a web browser or web crawler, initiate ...
using the web-server/insta language. Each time a connection is made to the server, the start function is called to get the
HTML The HyperText Markup Language or HTML is the standard markup language for documents designed to be displayed in a web browser. It can be assisted by technologies such as Cascading Style Sheets (CSS) and scripting languages such as JavaScri ...
to send back to the client. #lang web-server/insta ;; A tiny "hello world" web server (define (start request) (response/xexpr '(html (body "Hello World")))) Racket also includes the functions you would need to write scrapers and robots. As an example, the following function would list the Google results for a search string. #lang racket ;; Simple web scraper (require net/url net/uri-codec) (define (let-me-google-that-for-you str) (let* ( "http://www.google.com/search?q=" (string-append g (uri-encode str)) ).*?(?=)".html" ;"title="x #rx"(?<=

).*?(?=

)"">x #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 your car."))


Graphics

Graphic capabilities come in several different flavors that are intended for different audiences. The 2htdp/image library provides convenient functions for constructing images. This library is mainly used by students in
HtDP ''How to Design Programs'' (''HtDP'') is a textbook by Matthias Felleisen, Robert Bruce Findler, Matthew Flatt, and Shriram Krishnamurthi on the systematic design of computer programs. MIT Press published the first edition in 2001, and the seco ...
-based courses. In the following example, a sierpinski function is defined and called (at the same time) to generate a Sierpinski triangle of depth 8. #lang racket ;; A picture (require 2htdp/image) (let sierpinski ( 8 (if (zero? n) (triangle 2 'solid 'red) (let ( (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 \times \mathbb \times \mathbb \rightarrow \mathbb (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 PNG,
PDF Portable Document Format (PDF), standardized as ISO 32000, is a file format developed by Adobe in 1992 to present documents, including text formatting and images, in a manner independent of application software, hardware, and operating systems. ...
,
PostScript PostScript (PS) is a page description language in the electronic publishing and desktop publishing realm. It is a dynamically typed, concatenative programming language. It was created at Adobe Systems by John Warnock, Charles Geschke, Doug Br ...
and SVG formats.


GUI programming

Racket implements a portable
GUI The GUI ( "UI" by itself is still usually pronounced . or ), graphical user interface, is a form of user interface that allows users to interact with electronic devices through graphical icons and audio indicator such as primary notation, inste ...
layer which the libraries mentioned above build on. It is implemented via the native
Windows Windows is a group of several proprietary graphical operating system families developed and marketed by Microsoft. Each family caters to a certain sector of the computing industry. For example, Windows NT for consumers, Windows Server for serv ...
API, via
Cocoa Cocoa may refer to: Chocolate * Chocolate * ''Theobroma cacao'', the cocoa tree * Cocoa bean, seed of ''Theobroma cacao'' * Chocolate liquor, or cocoa liquor, pure, liquid chocolate extracted from the cocoa bean, including both cocoa butter and ...
on
Mac OS X macOS (; previously OS X and originally Mac OS X) is a Unix operating system developed and marketed by Apple Inc. since 2001. It is the primary operating system for Apple's Mac (computer), Mac computers. Within the market of ...
, and via
GTK+ GTK (formerly GIMP ToolKit and GTK+) is a free and open-source cross-platform widget toolkit for creating graphical user interfaces (GUIs). It is licensed under the terms of the GNU Lesser General Public License, allowing both free and proprie ...
on Linux and others. The Racket API is a class-based toolkit, somewhat related to
wxWidgets wxWidgets (formerly wxWindows) is a widget toolkit and tools library for creating graphical user interfaces (GUIs) for cross-platform applications. wxWidgets enables a program's GUI code to compile and run on several computer platforms with mini ...
which was used originally. The following simple guessing game demonstrates coding with the GUI toolkit. The frame% class implements a top-level window, and button% implements a button. The check function defined here produces a function that is used for the button's callback action. #lang racket/gui ;; A GUI guessing game (define secret (random 5)) (define f (new frame% abel "Guessing game") ; toplevel window (define t (new message% arent f abel "Can you guess the number I'm thinking about?") (define p (new horizontal-pane% arent f) ; horizontal container (define ((make-check i) btn evt) (message-box "." (cond < i secret) "Too small" > i secret) "Too big" lse "Exactly!") (when (= i secret) (send f show #f))) ; success => close window (for ( (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.PLaneT
Racket's centralized package distribution system


Slideshow

Slide Slide or Slides may refer to: Places * Slide, California, former name of Fortuna, California Arts, entertainment, and media Music Albums * ''Slide'' (Lisa Germano album), 1998 * ''Slide'' (George Clanton album), 2018 *''Slide'', by Patrick Glees ...
-based
presentation A presentation conveys information from a speaker to an audience. Presentations are typically demonstrations, introduction, lecture, or speech meant to inform, persuade, inspire, motivate, build goodwill, or present a new idea/product. Presenta ...
s can also be developed in Racket using the slideshow language, much like
Beamer Beamer may refer to: * Beamer (cricket), a type of ball delivery * Beamer (LaTeX), a document class for creating presentation slides * Beamer (occupation), in the cotton industry * Beamer (surname), including a list of people with the name * ...
, but with Racket's programmatic facilities. Elements of the slides are pictures that can be combined. For example, the following program displays in full-screen a title slide, followed by a slide with some pictures. The vc-append and hc-append functions combine pictures vertically and horizontally, respectively, and centered on the other axis. #lang slideshow (slide (text "Slideshow" 'roman 56) (text "Making presentations in Racket" 'roman 40)) (slide #:title "Some pictures" (apply vc-append (for/list ( 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 Latex is an emulsion (stable dispersion) of polymer microparticles in water. Latexes are found in nature, but synthetic latexes are common as well. In nature, latex is found as a milky fluid found in 10% of all flowering plants (angiosperms ...
elements.


Foreign function interface

Racket features a
foreign function interface A foreign function interface (FFI) is a mechanism by which a program written in one programming language can call routines or make use of services written in another. Naming The term comes from the specification for Common Lisp, which explicit ...
that is based on
libffi libffi is a foreign function interface library. It provides a C programming language interface for calling natively compiled Subroutine, functions given information about the target Subroutine, function at Run time (program lifecycle phase), run ...
. The interface allows writing unsafe low-level C-like code, that can allocate memory, dereference pointers, call out to functions in
shared libraries In computer science, a library is a collection of non-volatile resources used by computer programs, often for software development. These may include configuration data, documentation, help data, message templates, pre-written code and subr ...
, and send out callbacks to Racket functions (using libffi closures). The core implementation is a thin layer atop libffi (written in C), and the full interface is then implemented via Racket code. The interface uses macros extensively, resulting in an expressive Racket-based
interface description language interface description language or interface definition language (IDL), is a generic term for a language that lets a program or object written in one language communicate with another program written in an unknown language. IDLs describe an inter ...
. This language has a number of useful features, such as uniform representation for higher-order functions (avoiding the pitfalls when callbacks and callouts are different), struct definitions that are similar to plain Racket structs, and custom function types that can represent input and output pointers, implicit arguments (e.g., an argument that provides the number of elements in a vector that is passed as another argument). By using this interface to access underlying GUI toolkits, Racket implements its own GUI layer completely in Racket. The FFI can be used in a number of different ways: from writing a complete glue layer for a library (as done for Racket's
OpenGL OpenGL (Open Graphics Library) is a cross-language, cross-platform application programming interface (API) for rendering 2D and 3D vector graphics. The API is typically used to interact with a graphics processing unit (GPU), to achieve hardwa ...
binding), to quickly pulling out a single foreign function. An example of the latter approach: #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 -> et : _int)) (mci-send-string "play sound.wav wait")


Language extensions

Racket's most notable feature is its ability to build new
domain-specific Domain specificity is a theoretical position in cognitive science (especially modern cognitive development) that argues that many aspects of cognition are supported by specialized, presumably evolutionarily specified, learning devices. The positi ...
and general-purpose languages. This is the result of combining a number of important features: * a flexible module system that is used for linking code and for namespace management, * an extensive macro system—functioning as a compiler-API—that can create new syntactic forms, * a rich runtime system, providing features that language implementors can use, like (composable, delimited) continuations, resource management, etc., * a way to specify (and implement) parsers for new language syntaxes. The module system plays an important role in combining these features, and making it possible to write code that spans across a number of modules, where each can be written in a different language. Such languages are used extensively in the Racket distribution and in user libraries. In fact, creating a new language is so straightforward, that there are some languages that have less than a handful of uses. Racket comes with a number of useful languages, some are very different from Racket's default language.


Scribble

Scribble, Racket's documentation system, comes in the form of a number of languages that are used to write prose. It is used for Racket's documentation, as well as writing books and articles. Actually, rather than a single "scribble" language, it is a family of (very similar) dialects, each for a different purpose. To run the following example, copy it into DrRacket and click one of the two scribble rendering buttons that will appear (PDF rendering requires
pdfTeX __NOTOC__ The computer program pdfTeX is an extension of Knuth's typesetting program TeX, and was originally written and developed into a publicly usable product by Hàn Thế Thành as a part of the work for his PhD thesis at the Faculty of In ...
). Alternatively, use the scribble executable on the file. #lang scribble/base @; Generate a PDF or an HTML document using `scribble' @(require (planet neil/numspell)) @title In case you need some @emph in your life. @(apply itemlist (for/list ( (in-range 99 0 -1) (define N (number->english n)) (define N-- (number->english (sub1 n))) @item)) 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) @thrice! @thrice!


Typed Racket

Typed Racket is a
statically typed In computer programming, a type system is a logical system comprising a set of rules that assigns a property called a type to every "term" (a word, phrase, or other set of symbols). Usually the terms are various constructs of a computer progra ...
variant of Racket. The
type system In computer programming, a type system is a logical system comprising a set of rules that assigns a property called a type to every "term" (a word, phrase, or other set of symbols). Usually the terms are various constructs of a computer progra ...
that it implements is unique in that the motivation in developing it was accommodating as much idiomatic Racket code as possible—as a result, it includes subtypes, unions, and much more. Another goal of Typed Racket is to allow migration of parts of a program into the typed language, so it accommodates calling typed code from untyped code and vice versa, generating dynamic
contracts A contract is a legally enforceable agreement between two or more parties that creates, defines, and governs mutual rights and obligations between them. A contract typically involves the transfer of goods, services, money, or a promise to tran ...
to enforce type invariants. This is considered a desirable feature of an application's lifetime stages, as it matures from "a script" to "an application", where static typing helps in maintenance of a large body of code. #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)))


Lazy Racket

The lazy language is a language with
lazy evaluation In programming language theory, lazy evaluation, or call-by-need, is an evaluation strategy which delays the evaluation of an expression until its value is needed (non-strict evaluation) and which also avoids repeated evaluations (sharing). The b ...
semantics, similar to
Haskell Haskell () is a general-purpose, statically-typed, purely functional programming language with type inference and lazy evaluation. Designed for teaching, research and industrial applications, Haskell has pioneered a number of programming lang ...
. In the following example, fibs is an infinite list whose 1000th element will not be computed until its value is needed for the printout. #lang lazy ;; An infinite list: (define fibs (list* 1 1 (map + fibs (cdr fibs)))) ;; Print the 1000th Fibonacci number: (print (list-ref fibs 1000))


Logic programming

Racket comes with three
logic programming Logic programming is a programming paradigm which is largely based on formal logic. Any program written in a logic programming language is a set of sentences in logical form, expressing facts and rules about some problem domain. Major logic prog ...
languages: Racklog, a
Prolog Prolog is a logic programming language associated with artificial intelligence and computational linguistics. Prolog has its roots in first-order logic, a formal logic, and unlike many other programming languages, Prolog is intended primarily ...
-like language; a
Datalog Datalog is a declarative logic programming language. While it is syntactically a subset of Prolog, Datalog generally uses a bottom-up rather than top-down evaluation model. This difference yields significantly different behavior and properties ...
implementation; and a miniKanren port. Unlike the Scribble syntax, the first two of these languages use a completely new syntax rather than an extension of S-expressions. If you use it in DrRacket, you'll see that it provides proper highlighting, the usual host of tools check syntax, and a Prolog/Datalog REPL. #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)?


Educational tools

The PLT group which develops Racket has traditionally been involved in education at all levels. One of the earliest research ideas that the group promoted is the use of language levels, which restrict new students while providing them with helpful error messages that fit the student's level of knowledge. This approach is heavily used in
How to Design Programs ''How to Design Programs'' (''HtDP'') is a textbook by Matthias Felleisen, Robert Bruce Findler, Matthew Flatt, and Shriram Krishnamurthi on the systematic design of computer programs. MIT Press published the first edition in 2001, and the secon ...
, the textbook that several PLT developers have authored, as well as in the
ProgramByDesign The ProgramByDesign (formerly TeachScheme!) project is an outreach effort of the PLT research group. The goal is to train college faculty, high school teachers, and possibly even middle school teachers, in programming and computing. History Matt ...
project. The following program uses the htdp/bsl—the "beginning student language". It uses the 2htdp/image library for creating pictures in the teaching languages, and the 2htdp/universe library for interactive animations. #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))


Algol

Racket comes with a complete implementation of the
ALGOL 60 ALGOL 60 (short for ''Algorithmic Language 1960'') is a member of the ALGOL family of computer programming languages. It followed on from ALGOL 58 which had introduced code blocks and the begin and end pairs for delimiting them, representing a k ...
language. #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 you some useful new constructs: define-type, type-case, and test."


Additional languages

Finally, the following example is an implementation of a new language: #lang racket (provide (except-out (all-from-out racket) #%top #%app) (rename-out op #%top pp #%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.Note that #%app is a macro that is used in all function calls, making this language not too efficient, as every function call incurs an additional condition. In addition, the macro evaluates the function expression twice, so it should not be taken as an example of good macro-programming. If this code is stored in a mylang.rkt file, you can use it 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


References

*


External links

* {{Official website, http://racket-lang.org
docs.racket
Articles with example Racket code Software development Language workbench