;; CSE 413 21sp ;; 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 (comfort temp) (cond [(> temp 80) 'too-hot] [(> temp 60) 'nice] [(< temp 40) 'too-cold] [else 'seattle])) ;; examples ; (comfort 70) => 'nice ; (comfort 55) => 'seattle ;; list data for examples below (define animals '(lion tiger bear)) (define nums '(5 17 3 12)) (define ab '(a b)) (define xyz '(x y z)) (define stuff '(1 banana (2 3) 4 (5))) ;; Functions on lists ;; list construction - all three of these produce the same result: ;; quoted list: '(a b c) ;; list constructor function: (list 'a 'b 'c) ;; explicit construction: (cons 'a (cons 'b (cons 'c '()))) ;; sum of numbers in a list (define (sum lst) (if (null? lst) 0 (+ (car lst) (sum (cdr lst))))) ;; examples ; (sum nums) => 37 ; (sum animals) => error 'bear is not a number ;; new version - sum numbers in a list but ignore list elements that are not numbers (define (numsum lst) (cond [(null? lst) 0] [(number? (car lst)) (+ (car lst) (numsum (cdr lst)))] [else (numsum (cdr lst))])) ;; examples ; (numsum nums) => 37 ; (numsum animals) => 0 ; (numsum stuff) => 5 ;; = length of lst (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 (define (badapp lst1 lst2) (cons lst1 lst2)) ;; bug is that it returns new list with lst1 as first element consed onto front of lst2 ; (badapp ab xyz) => '((a b) x y z) ;; proper append (define (app lst1 lst2) (if (null? lst1) lst2 (cons (car lst1) (app (cdr lst1) lst2)))) ;; Examples ; (app '() '()) => '() ; (app ab '()) => '(a b) ; (app '() ab) => '(a b) ; (app ab xyz) => '(a b x y z)