120 likes | 134 Views
Racket Last Structs, Lambda, Module. CSC270 Pepper. major portions credited to http://learnxinyminutes.com/docs/racket/. Structs. ; Define structure: (struct student (name gpa age)) ; structure type definition: (define s1 (student "amy jones" 3.0 20))
E N D
Racket Last Structs, Lambda, Module CSC270 Pepper major portions credited to http://learnxinyminutes.com/docs/racket/
Structs ; Define structure: (struct student (name gpa age)) ; structure type definition: (define s1 (student "amy jones" 3.0 20)) ; use of one part of struct variable: (student-name s1) ; check type : (student? s1 )
Shape Structures • (struct circle (radius)) • (define c1 (circle 10)) • (define c2 (circle 12)) • (structrect (length width)) • (define r1 (rect 10 20)) • (define r2 (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 c1) (area r1) (area (rect 10 30)
Functions Passing in Functions • First class functions (define (square num) (* numnum)) (define (pow3 num) (* numnumnum)) (define (calcnumberfunc) (numberfunc 10)) (calc square); (calc pow3); Plus Remember map: • (define (add3 x) (+ x 3)) • (map add3 '(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 Ladd3 ( lambda (num) (+ num 3))) ; second same as (define (Ladd3 num) (+ num 3)) (Ladd3 5) ; see how all functions have an implied lambda?
Functions Passing in Functions (define (triangleperm a b c) (+ a b c)) (define (equiTriangle a) (triangleperm a a a)); (calc equiTriangle); Or instead of defining equiTriangle, create an anonymous function: (calc (lambda (x) (triangleperm x x x)))
Map Lambda functions • Define a function Use it in map • (define (add3 x) (+ x 3)) • (map add3 '(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 moduleName itsBase) example (module cake racket/base) • list functions the importer can use with (provide functionName) example (provide bake-cake) • no indication of parameters needed • To import a module : (require ModuleName) example (require picturing-programs)
Important Concepts • Define data in parts : structure • Functions can take in functions as parms • On the fly functions give flexibility