Racket Flashcards
Write a basic lambda the returns the second element in a list (assume there are more than 2 elms in list)?
((lambda (x) ;; declare params
(cadr x)) ;; expression
(list 1 2 3));; actual values
Define a function that takes list and a value then checks if all the values in the list are greater than the value?
(define (larger ls n)
(andmap
(lambda (x) (> x n))
ls))
Define a function that takes 2 ints as lower and upper bound (inclusive) and should return the largest square that is even?
(define (largestSquare x y) (apply max (filter even? (drop (build-list (+ y 1) (lambda (x) (* x x))) x))))
(largestSquare 1 10)
What is currying?
TBD
What is the general for of Let?
;; general form of let (let ((name1 value1) (name2 value2) ... (nameN valueN)) expression1 expression2 ... expressionQ)
What is the If form?
(if condition true_expression false_expression)
(if (= 0 1) (/ 1 0) (+ 2 3)) => 5
; note that the (/ 1 0) is not evaluated
Define a function that calculates the sum of a list?
(define (sum xs)
(if (null? xs)
0
(+ (car xs) (sum (cdr xs)))))
What is a thunk?
Delay evaluation by putting an expression in a function!
– Thanks to closures, can use all the same variables later
Define a function that squares and returns odd numbers in a list?
(define (square-odd x)
(map (lambda (y) (* y y))
(filter odd? x)))
(square-odd (list 1 2 3 4 5))
Define a function that adds 1 to each element in a list.
(define (add1 x) (if (null? x) '() (cons (+ 1 (car x)) (add1 (cdr x)))))
(add1 (list 1 2 3 4))
What is foldl?
Like map, foldl applies a procedure to the elements of one or more lists. Whereas map combines the return values into a list, foldl combines the return values in an arbitrary way that is determined by proc.
(foldl proc init lst)
> (foldl cons ‘() ‘(1 2 3 4))
‘(4 3 2 1)
(foldl + 0 ‘(1 2 3 4))
10
What does ZIP do?
Zipping combines two lists into a single list of pairs element-wise.
Define a myzip?
(define (myzip ls1 ls2) (cond [(null? ls1) ls2] [(null? ls2) ls1] [else (cons (list (car ls1) (car ls2)) (myzip (cdr ls1) (cdr ls2)))]))
(myzip ‘() ‘(a b c))
(myzip ‘(1 2 3) ‘())
(myzip ‘(1 2 3) ‘(a b c))
Define a myfoldl?
(define (myfoldl func init lst) (cond [(empty? lst) init] [else (myfoldl func (func (car lst) init) (cdr lst))]))
(myfoldl cons ‘() ‘(a b c))
(myfoldl + 0 ‘(1 2 3))
What is the difference between eq? eqv? and equal?
eq? is pointer comparison.
eqv? is like eq? but does the right thing when
comparing numbers. For number use = to compare as it coercses into crest type
equal? returns true if its arguments have the same
structure.