Skip to content

Racket Basics

Racket Syntax

  • Here is basic syntax to help you get started
See syntax here
#lang racket

;====== TYPES ======; 
"str"               ; String

1                   ; Integer
2.3                 ; Float

#t                  ; True
#f                  ; False

'(1 "str" #t)       ; List


;====== OPERATIONS ======; 
(+ 1 2)             ; Sum of 1 + 2 = 3

(- 10 2)            ; Difference of 10 - 2 = 8

(= 10 10)           ; Equals 10 == 10 = #t

(positive? 10)      ; Is Positive 10 >= 0 = #t

(negative? 10)      ; Is Positive 10 < 0 = #f


;====== DEFINITIONS ======; 

(define a 1)            ; Define variable

(define (sum arg1 arg2) ; Define function
    (+ arg1 arg2)
)    
;;; ;; Another way to write the function above
;;; (define sum 
;;;     (lambda(arg1 arg2) ; lambda is a nameless function
;;;        (+ arg1 arg2)
;;;     )
;;; )

(map (lambda ; map that takes in a list and does an action for each item in the list
    (item)
        (+ item 1))     ; For each item in the list, plus 1
        '(1 2 3 4 5)    ; List that will be incremented through
    )


(sum 10 20) ; Call the function


;====== CONDITIONALS ======;

(if (= 1 1)             ; if condition ex1
    ; then
    "hell yeah this condition is true"
    ; else
    "nah, this B false brudda"
)

(if (positive? -1)      ; if condition ex2
    ; then
    "hell yeah this condition is true"
    ; else
    "nah, this B false brudda"
)


;====== WORKING WITH LISTS ======;

(define li '(1 2 3 4 5))


;---- Indexing The List ----;
(car li)        ; Gets first element of the list in an integer form

(cadr li)       ; Gets the second element of the list
(caddr li)      ; Gets the third element of the list
(cadddr li)     ; Gets the fourth element of the list
(last li)       ; Gets the last element of the list

(list-ref li 2) ; Gets element with index 2 of the list

;---- Fetch Part Of List ----;
(drop li 2)     ; Drops first two elements and returns '(3 4 5)
(take li 3)     ; Takes the first three elements, returns '(1 2 3)

(cdr li)        ; Gets all but first element of the list in a list form

;---- Using the data within the list ----;

(define (list_sum li)
    (if (empty? li)

        0 ; Base case: return 0 when the list is empty

        ; If not empty, then recursively sum up the rest of the list
        (+ (car li) (list_sum (cdr li)) )
    )
)

(list_sum '(1 2 3 4 5)) ; Expected output: 15