Racket
Starting a Racket Program
Racket development is best done through its own IDE DrRacket. You can start a Racket program using
drracket <filename>.rkt
Expressions
An expression can be thought of as just a line of code in Racket. It can be a number, a string, a boolean and more.
Evaluation
Evaluation is the simplication of expressions.
For example:
1 + 1 = 2
can be written as Racket expression as (+ 1 1)
and Racket simplifies it to 2
.
Strings
A string is a fixed length array of characters. A string can be mutable or immutable.
Two strings are equal when they have the same length and the same sequence of characters.
Constants
You can define constants using define
. For example:
(define pi 3.14)
This defines a constant called pi
that can be referenced later in the code. Define is an expression that gets evaluated during execution and assigns the value to the variable name.
define
can also be used to define a function.
(define (circle-area r)
(* pi (r * r)))
The define
keyword is followed by the function name and then the parameters.
Booleans
Racket has two distinguished constants to represent boolean values #t
for True and #f
for False. Anything other than #f
is evaluated to true.
Test Expressions
(if test-expr then-expr else-expr)
If evaluates test-expr
and if anything other than the #f
boolean value is produced it evaluates the then-expr
. Otherwise, else-expr
is evaluated.
(cond
[(positive? -5) (error "doesn't get here")]
[(positive? 5) "here])
cond
takes a list of expressions and evaluates them in order until a true condition is reached. When this condition is reached, it produces the value.
Lists
list("red", "green", "blue")
Lists in Racket are linked lists and there are two core operations on a non-empty list.
first
- get the first element of the listlast
- get the rest of the list
To create a new node for a linked list in Racket, you can use cons
which is short for "construct".
(cons "head" empty)
To get the first element in the a list and the rest of the elements in a list
(first lst)
(rest lst)
Therefore, to run a recursive algorithm on a list you can use the following template
(define (recurse-lst lst)
(cond [(empty? lst) empty])
[else
(cons (func (first lst)) (recurse-lst (rest lst)))]))
Plai Types
Plai types are a super powerful way in Racket to create data types. They are defined using define-type
and can be referenced using a cond
like function called type-case
which matches the values to do a specific expression.