example.rkt (2014B)
1 #lang typed/racket 2 ;; phc-adt sets registers some information in its support files when it 3 ;; encounters new structure types, so this file has to be compiled twice 4 ;; in DrRacket (not on the command-line). The first compilation will fail, 5 ;; it is normal and expected (but it should soon give a better error message) 6 (require type-expander multi-id phc-adt typed/rackunit) 7 (adt-init) 8 9 ;; This internally does 10 ;; (define-multi-id s1 11 ;; #:type-expander (λ (stx) …) 12 ;; #:match-expander (λ (stx) …) 13 ;; #:call (λ (stx) …) 14 ;; #:id (λ (stx) …)) 15 (define-structure s1 [a : Number] [b : String]) 16 17 ;; The "structure" identifier is also a multi-id, for on-the-fly usage of a 18 ;; structure as a type, match pattern, constructor function or instance creation 19 20 (: foo (→ (U 21 ;; type-expander: s1 22 s1 23 ;; type-expander: (structure [field : type] …) 24 (structure [a : Number] [c : Symbol])) 25 Number)) 26 (define (foo s) 27 (match s 28 ;; match-expander: (s1 pat ...) 29 [(s1 (? number? the-a) the-b) (+ the-a (string-length the-b))] 30 ;; match-expander: (structure field-name …) 31 [(structure a c) (+ a (string-length (symbol->string c)))])) 32 33 (define instances 34 (append 35 ;; identifier macro: s1, to pretend it's a function 36 (map s1 37 (range 5) 38 '("x" "xx" "xxx" "xxxx" "xxxxx")) 39 ;; macro: (s1 args …), to pretend it's a function call 40 (list (s1 42 "Why does six times nine equal forty two?")) 41 ;; macro: (structure [field : type] …), produces a bulder function 42 (map (structure [a : Number] [c : Symbol]) 43 (reverse (range 5)) 44 '(x xx xxx xxxx xxxxx)) 45 ;; macro: (structure [field value] …) or (structure [field : type value]), 46 ;; produces an instance 47 (list (structure [a pi] [c 'three-fourteen])))) 48 49 (check-equal? (map foo instances) 50 (append '(1 3 5 7 9) 51 '(82) 52 '(5 5 5 5 5) 53 '(17.141592653589793)))