Racket


Quite similar to lisp.

An advantage of s-expr:

General

Defining new language

Examples

; Factorial of whole numbers
(define (fact n)  
  (if (<= n 0)
      1
      (* n {fact [- n 1]})))

let expressions

let for 'subcomputation':

Syntax:

let <list of binding> <expr>

(define foobar
  (let* ([foo 10]
         [bar 20])
    (* foo bar)))

(define (fact n) (if (<= n 0) 1 (let* [foo (fact (- n 1))])

let* use => no recursion???

eval

eval:

we can e

; assuming fact is function doing factorial
(define foo '(fact 5))
(eval foo)
; 120

Bindings not assignments

We can't redefine an identifer.

(define pi 3.14)
(define pi (/ 22 7))
module: identifier already defined

∵ it's immutable.

They're bindings not value assignments.

Modulus operation

> (quotient/remainder 17 2)
8
1

> (quotient 17 2)
8

> (remainder 17 2)
1

Boolean values

; pair? checks if its argument is a pair
> (pair? '())
#f
> (pair? (cons 2 3))
#t

Lists

(list 1 2 3)
; is same as
'(1 2 3)

The single quote sort of asks the interpreter to stop evaluating from that point.

> (list -1 2.3 "hi")
'(-1 2.3 "hi")

> (car '(1 2 3 4 5))
1

> (cdr '(1 2 3 4 5))
'(2 3 4 5)

car and cdr for elisp is similar:

Pairs

See https://docs.racket-lang.org/reference/pairs.html.

> (cons 1 2)
'(1 . 2)

> '(1 . 2)
'(1 . 2)

> '(1 . 2 . 3)
'(2 1 3)

> (car '(1 . 2))
1

> (cdr '(1 . 2))
2

Etymology of car and cdr (for pairs and lists) in the lisp world is historical.

Loops

See https://docs.racket-lang.org/guide/for.html

(for ([i 3])
  (display i))

; Above is syntactic sugar for

(for ([i (in-range 0 3)])
  (display i))

; because in-range's first argument defaults to 0

drracket

emacs

racket-mode: emacs mode for racket

Info