Racket basics<!-- --> | LearnFP

Racket basics

Skills: comments prefix syntax data types variables functions

Comments

Single-line comments start with a semicolon:

; This is a comment

Multi-line comments are in between #| and |#

#| This is
a
multi-line
comment |#

Prefix syntax

Usually, when we write mathematical expressions, we use infix syntax.

For example, we might write 3 + 2, where the operator is between the numbers. This is just a human convention; we could also use postfix syntax such as writing 3 2 +

However, Racket uses a prefix syntax. The operator comes at the beginning in expressions. To find 3 + 2, you would write (+ 3 2) in Racket. By using parenthesis, nesting becomes possible. If we wanted to find 3 + 5 * 2, for example, we could write (+ 3 (* 5 2)). The (* 5 2) would evaluate to 10, and the expression would become (+ 3 10) which evaluates to 13.

More data types

We introduced some basic arithmetic functions already like + and *. Booleans (true or false values) and Strings (text) also can have functions applied to them.

Booleans are written as #t for true and #f for false.

Some functions on booleans:

(not #t) => #f
(or #t #f) => #t
(and #t #f) => #f

Strings are blocks of text. You can print them using using the printf function

(printf "Hello Racket") => "Hello Racket"

Variables

Variables allow you to assign a value to something which can be used again in your code.

You create a variable using the define keyword:

(define x 3) ; assigns the number 3 to x
(* x 2) => 6

Functions

Functions take in an input and use them to produce an output.

You can create functions using the define keyword with the list of parameters going in parenthesis.

Example:

(define (greeting name)
(string-append "Greetings, " name))


(greeting "Bob") => "Greetings, Bob"