Presentation is loading. Please wait.

Presentation is loading. Please wait.

Racket Last Structs, Lambda, Module

Similar presentations


Presentation on theme: "Racket Last Structs, Lambda, Module"— Presentation transcript:

1 Racket Last Structs, Lambda, Module
CSC270 Pepper major portions credited to

2 Structs ; Define structure: (struct student (name gpa age)) ; structure type definition: (define s1 (student "amy jones" )) ; use of one part of struct variable: (student-name s1) ; check type : (student? s1 )

3 Shape Structures (struct circle (radius)) (define c1 (circle 10))
(struct rect (length width)) (define r1 (rect 10 20)) (define r2 (rect 11 12))

4 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)

5 Functions Passing in Functions
First class functions (define (square num) (* num num)) (define (pow3 num) (* num num num)) (define (calc numberfunc) (numberfunc 10)) (calc square); (calc pow3); Plus Remember map: (define (add3 x) (+ x 3)) (map add3 '(1 2 3))

6 Lambda Functions (lambda () "Hello")
; surround with parentheses to call (( lambda () "Hello")) ; function with a parm (lambda (num) (+ num 3)) ((lambda (num) (+ num 3)) 5) All functions have an implied lambda

7 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?

8 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)))

9 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))

10 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

11 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)

12 Important Concepts Define data in parts : structure
Functions can take in functions as parms On the fly functions give flexibility


Download ppt "Racket Last Structs, Lambda, Module"

Similar presentations


Ads by Google