ProgrammingLanguagesB Flashcards
Why do you need to write #lang racket at the top of all your Racket files?
It is so DrRacket will interpret the code as Racket code.
Simple racket file
lang racket
(provide (all-defined-out))
(define s “hello”)
Define variable x and assign it 3
(define x 3)
Define variable y and assign it x+5
(define y (+ x 5))
Define function that gets number and returns it’s square
(define square1
(lambda (x)
(* x x)))
; OR
(define (square1 x) (* x x))
Example of pow function(RECURSIVE)
(define (pow1 x y)
(if (= y 0)
1
(* x (pow1 x (- y 1)))))
Example of Currying
(define pow2
(lambda (x)
(lambda (y)
(pow1 x y))))
(define three-to-the (pow2 3))
(three-to-the 5)
List processing
;Empty list: null ;Cons constructor: cons ;Access head of list: car ;Access tail of list: cdr ;Check for empty: NULL? ;Lists without cons: (list a1 a2 a3 a4 ... an)
Racket syntax. A term is either a:
- an atom, e.g. #t, #f, 34, “hi”, null, 4.0, x…
- a special form, e.g., define, lambda, if
- a sequence of terms in parens: (t1 t2 … tn)
Cond operator syntax
(cond [e1a e1b] [e2a e2b] [e3a e3b] ... [eNa eNb])
- Good style: eNa should be #t
True and False in Racket
#t - True #f - False
Local bindings in Racket
let
let*
letrec
define
Let
can bind any number of local variables
Let example
(define (silly-double x)
(let ([x (+ x 3)]
[y (+ x 2)])
(+ x y -5)))
;> (silly-double 2)
;9
Let*
The expressions are evaluated in the environment produced from previous bindings