;; CSE 413 23sp ;; Lecture 3 function definitions and examples #lang racket (define magic 42) (define xvii 17) (define pi 3.1415926535) ;; Simple functions on numbers ;; = 2*x using convenient (double n) function definition syntax (define (double n) (* 2 n)) ;; same but showing explicit function value (lambda) binding to name (define twice (lambda (x) (+ x x))) ;; = n! (define (fact n) (if (< n 2) 1 (* n (fact (- n 1))))) ;; cond - multiway conditional expression (define (weather temp) (cond [(> temp 80) 'too-hot] [(> temp 60) 'nice] [(< temp 40) 'too-cold] [else 'seattle])) ;; examples ; (weather 70) => 'nice ; (weather 55) => 'seattle ;; list data for new examples below (define animals '(lion tiger bear)) (define nums '(1 2 3 4)) (define colors '(red green blue)) (define ab '(a b)) (define xyz '(x y z)) (define stuff '(1 banana (2 3) 4 (5))) ;; Functions on lists ;; sum of numbers in a list (define (sum lst) (if (null? lst) 0 (+ (car lst) (sum (cdr lst))))) ;; examples ; (sum nums) => 10 ; (sum animals) => error 'bear is not a number ; sum numbers in the list ignoring non-numbers (define (numsum lst) (cond [(null? lst) 0] [(number? (car lst)) (+ (car lst) (numsum (cdr lst)))] [else (numsum (cdr lst))])) ;; examples ; (numsum nums) => 10 ; (numsum animals) => 0 ; (numsum stuff) => 5 ;; length of list (define (len lst) (if (null? lst) 0 (+ 1 (len (cdr lst))))) ;; examples ; (len '()) => 0 ; (len xyz) => 3 ; (len stuff) => 5 ;; Attempt to append one list to another ;; first (buggy) attempt ;; append list x and y (define (app1 x y) (cons x y)) ;; example ; (app1 ab xyz) => '((a b) x y z) ;; proper append ;; append list x and y (define (app x y) (if (null? x) y (cons (car x) (app (cdr x) y)))) ;; examples ; (app '() '()) => '() ; (app ab '()) => '(a b) ; (app '() ab) => '(a b) ; (app ab xyz) => '(a b x y z)