Damien Gonot
Home Blog Notes About

Racket

Homepage / Notes / Computer Science / Programming Languages / Racket

Modern dialect of Lisp

Language Features

Booleans

#t true or #f false

#lang racket

#t
#t

Numbers

#lang racket
(+ 1 1)
2

Strings

#lang racket
"Damien"
Damien
#lang racket
(list->string (reverse (string->list "Damien")))
neimaD

Characters

#lang racket

#\A
#\A

Variables

#lang racket
(define x 9)
x
9

Pairs

Can use cons to construct a pair:

#lang racket

(car (cons 1 2))
(cdr (cons 1 2))
(pair? (cons 1 2))
1
2
#t

Or the quote with . notation:

#lang racket

(car '(1 . 2))
(cdr '(1 . 2))
(pair? '(1 . 2))
1
2
#t

Lists

https://docs.racket-lang.org/guide/Lists__Iteration__and_Recursion.html

(list i j k) is similar to '(i j k)

#lang racket
(list 1 2 3)
'(1 2 3)
#lang racket
'(1 2 3)
'(1 2 3)

Length

#lang racket
(length '(1 2 3))
3

Sort

#lang racket
(sort '(1 2 3) >)
'(3 2 1)

Take

#lang racket
(take '(1 2 3) 2)
'(1 2)

Map

Can insert lambda in Emacs with C-M-y or racket-insert-lambda

#lang racket
(map (λ (n) (* 2 n)) '(1 2 3))
'(2 4 6)

Foldl

#lang racket
(foldl (λ (acc n) (+ acc n)) 0 '(1 2 3))
6

Actually a way simpler way of writing it:

#lang racket
(foldl + 0 '(1 2 3))
6

Hash Tables

#lang racket

(hash "apple" "red" "banana" "yellow")
'#hash(("apple" . "red") ("banana" . "yellow"))

Get value by key

#lang racket

(define fruit-colours (hash "apple" "red" "banana" "yellow"))
(hash-ref fruit-colours "apple")
red

Set value by key

hash-set returns a new list

#lang racket

(define fruit-colours (hash "apple" "red" "banana" "yellow"))
(hash-set fruit-colours "apple" "red-ish")
'#hash(("apple" . "red-ish") ("banana" . "yellow"))

Functions

https://docs.racket-lang.org/guide/syntax-overview.html

#lang racket
(define (double x) (* x 2))

(double 5)
10

Anonymous Functions

Either lambda or λ can be used

#lang racket
((lambda (n) (* 2 n)) 2)
4
#lang racket
((λ (n) (* 2 n)) 2)
4

Thread Macros

#lang racket
(require threading)
(~> "Damien" string->list reverse list->string)
neimaD

Pattern Matching

#lang racket

(match 9
  [7 'seven]
  [8 'eight]
  [9 'nine])
nine

Eval

racket -e '(+ 1 1)'
2

Typed Racket

Annotations

#lang typed/racket

(: x Number)
(define x 9)
x
9
#lang typed/racket

(define x : Number 9)
x
9

Basic Types

NameExample
String"Hello, world"
Char#|̣
True#t
False#f
Symbol'foo
Integer1
Flonum2.1

Example

#lang typed/racket

(struct pt ([x : Real] [y : Real]))

(: distance (-> pt pt Real))
(define (distance p1 p2)
  (sqrt (+ (sqr (- (pt-x p2) (pt-x p1)))
           (sqr (- (pt-y p2) (pt-y p1))))))

(distance (pt 0 0) (pt 2 2))
2.8284271247461903

Resources

The Racket Guide

https://docs.racket-lang.org/guide/index.html

The Racket Reference

https://docs.racket-lang.org/reference/index.html

Beautiful Racket

https://beautifulracket.com/

Realm of Racket

https://nostarch.com/realmofracket.htm