Homepage / Notes / Computer Science / Programming Languages / Racket
Modern dialect of Lisp
#t
true or #f
false
#lang racket
#t
#t
#lang racket
(+ 1 1)
2
#lang racket
"Damien"
Damien
#lang racket
(list->string (reverse (string->list "Damien")))
neimaD
#lang racket
#\A
#\A
#lang racket
(define x 9)
x
9
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
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)
#lang racket
(length '(1 2 3))
3
#lang racket
(sort '(1 2 3) >)
'(3 2 1)
#lang racket
(take '(1 2 3) 2)
'(1 2)
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)
#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
#lang racket
(hash "apple" "red" "banana" "yellow")
'#hash(("apple" . "red") ("banana" . "yellow"))
#lang racket
(define fruit-colours (hash "apple" "red" "banana" "yellow"))
(hash-ref fruit-colours "apple")
red
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"))
https://docs.racket-lang.org/guide/syntax-overview.html
#lang racket
(define (double x) (* x 2))
(double 5)
10
Either lambda
or λ
can be used
#lang racket
((lambda (n) (* 2 n)) 2)
4
#lang racket
((λ (n) (* 2 n)) 2)
4
#lang racket
(require threading)
(~> "Damien" string->list reverse list->string)
neimaD
#lang racket
(match 9
[7 'seven]
[8 'eight]
[9 'nine])
nine
racket -e '(+ 1 1)'
2
#lang typed/racket
(: x Number)
(define x 9)
x
9
#lang typed/racket
(define x : Number 9)
x
9
Name | Example |
---|---|
String | "Hello, world" |
Char | #|̣ |
True | #t |
False | #f |
Symbol | 'foo |
Integer | 1 |
Flonum | 2.1 |
#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
https://docs.racket-lang.org/guide/index.html
https://docs.racket-lang.org/reference/index.html