Racket CSC 270 Pepper major portions credited to










- Slides: 10
Racket CSC 270 Pepper major portions credited to http: //learnxinyminutes. com/docs/racket/
Screen Functions • Read in a variable from the screen (read var) example : (read n) • write a variable to the screen: – just put the variable name – final result of all functions write to the screen – literal alone will write to the screen • Example: "What is your name? " (define n (read )) n (string-append "hello " (symbol->string n))
String Functions Put 2 strings together: (string-append "cat" "dog") Returns "catdog" Pick out one character knowing the index (string-ref "cat" 1) Returns "a" Put a string together in printf fashion: (format " ~a are number ~a " "cats" 1) (printf " ~a are number ~a " "cats" 1) Both return "cats are number 1"
Construct a pair (small list) • Make a pair – (cons 3 4 ) • Pull out the first element of a pair – (car (cons 3 4)) • Pull out the second element of a pair – (cdr (cons 3 4)) • Make one side of pair empty – (cons null ) • Make an empty pair '() or null
Lists • Define a list: linked lists of pairs with one side being the list item and the other being the rest of the list, that ends in null or () • (cons 1 (cons 2 (cons 3 null))) • (list 1 2 3) • quote for the literal value • '(1 2 3) • (build-list 10 values) to get 0 to 10
Add items to a list • add items to a list • (cons 4 '(1 2 3 )) • (append '(1 2) '(3 4))
List Functions • Do the same thing to every item in the list (map add 1 '(1 2 3)) gives '(2 3 4) • Apply one list to another list of the same number of items (map + '(1 2 3) '(10 20 30)) • extract only even (filter even? '(1 2 3 4)) gives '(2 4) • count only even (count even? '(1 2 3 4)) gives 2 • take the first n items (take '(1 2 3 4 ) 2) gives '(1 2 ) • drop the first n items (drop '(1 2 3 4 ) 2) gives '(3 4) • is it a member? (member 'dog '(cat dog rat)) gives #t • first member value (first '(3 4 5)) gives 3 • get number of elements (length '(3 4 5)) gives 3
Define Functions using Lists (define (addlist mylist 2) (cond [ (eq? mylist 2 null) 0] [ else ( + (first mylist 2 ) (addlist (drop mylist 2 1)))])) (define list 1 (list 8 2 5)) (addlist 1) (addlist (cons 1 (cons 2 (cons 3 null))) )
Mapping • Map – run the function for each item in the list – (map sqrt '(4 16 25)) • Apply one list to another list of the same number of items with a function taking in 2 parameters – (map + '(1 2 3) '(10 20 30)) • Use your own functions: – (define (add 3 x) (+ x 3)) – (map add 3 '(1 2 3))
Important Concepts • Create lists • Map against lists • Recurse through lists until empty