Racket Last Structs Lambda Module CSC 270 Pepper
Racket Last Structs, Lambda, Module CSC 270 Pepper major portions credited to http: //learnxinyminutes. com/docs/racket/
Structs ; Define structure: (struct student (name gpa age)) ; structure type definition: (define s 1 (student "amy jones" 3. 0 20)) ; use of one part of struct variable: (student-name s 1) ; check type : (student? s 1 )
Shape Structures • • • (struct circle (radius)) (define c 1 (circle 10)) (define c 2 (circle 12)) (struct rect (length width)) (define r 1 (rect 10 20)) (define r 2 (rect 11 12))
Area Functions (define (area a-shape) (cond [(rect? a-shape) (* (rect-length a-shape) (rect-width a-shape))] [ (circle? a-shape) (* (expt (circle-radius a-shape) 2)pi)])) (area c 1) (area r 1) (area (rect 10 30)
Functions Passing in Functions • First class functions (define (square num) (* num)) (define (pow 3 num) (* num num)) (define (calc numberfunc) (numberfunc 10)) (calc square); (calc pow 3); Plus Remember map: – (define (add 3 x) (+ x 3)) – (map add 3 '(1 2 3))
Lambda Functions (lambda () "Hello") ; surround with parentheses to call (( lambda () "Hello")) ; function with a parm (lambda (num) (+ num 3)) ; surround with parentheses to call ((lambda (num) (+ num 3)) 5) All functions have an implied lambda
Define and Lambda ; assign a lambda function to a symbol (define Lhello-world ( lambda() "Hello")) ; same as (define (Lhello-world) "hello") (Lhello-world) (define Ladd 3 ( lambda (num) (+ num 3))) ; second same as (define (Ladd 3 num) (+ num 3)) (Ladd 3 5) ; see how all functions have an implied lambda?
Functions Passing in Functions (define (triangleperm a b c) (+ a b c)) (define (equi. Triangle a) (triangleperm a a a)); (calc equi. Triangle); Or instead of defining equi. Triangle, create an anonymous function: (calc (lambda (x) (triangleperm x x x)))
Map Lambda functions • Define a function Use it in map – (define (add 3 x) (+ x 3)) – (map add 3 '(1 2 3)) • Define that same function anonymously – (map (lambda (i) (+ i 3)) '(1 2 3))
Adding New Commands EASY (define-syntax-rule (swap! x y) (let ([temp x]) (set! x y) (set! y temp))) (define x 3) (define y 4) (swap! x y) x y
Modules • create it with (module. Name its. Base) example (module cake racket/base) • list functions the importer can use with (provide function. Name) example (provide bake-cake) • no indication of parameters needed • To import a module : (require Module. Name) example (require picturing-programs)
Important Concepts • Define data in parts : structure • Functions can take in functions as parms • On the fly functions give flexibility
- Slides: 12