![]() |
![]() |
|
home—lectures—exams—hws—breeze (snow day)
N.B.
But what drawback? Instead of wanting modify/update a single field, (for immutable) I must copy the entire object. move-ship update-world Much more allocation/copying happening -- performance hit. (But: only a factor of 2x extra memory needed, since we can immediately reclaim (garbage-collect) the previous value that might now be inaccessible)
Cf. C vs Java strings, when calling toUpperCase.
Consider the following grammar:
Expr ::= Number | Var | ParenExpr | BinExpr | IfZExpr ParenExpr ::= ( Expr ) BinExpr ::= ( Expr BinOp Expr ) IfZExpr ::= if Expr is0 then Expr else Expr ; BinOp ::= plus | minus | times Number ::= [any numeric literal, a la Java or Racket, your choice] Var ::= [any string with no whitespace, that is not one of the reserved words “plus”, |
Our project will:
How to represent
(define-struct/contract
(bin-expr [left expr?] [op bin-op?] [right expr?]))
(make-bin-expr 3 'plus 4)
(make-bin-expr (make-bin-expr 3 'plus 4)
'minus
5)
; We need data def'ns for our union types;
; we'll make real code out of the union-type-def'n
; (so that we can use it in with 'define/contract', if you want):
(define (expr? any-val)
(or (number? any-val)
(string? any-val)
(paren-expr? any-val)
(bin-op-expr? any-val)
(if-Z-expr? any-val)))1
2
(define (bin-op? any-val)
(member any-val (list 'plus 'minus 'times)))
|
1
Rather than calling each function on
(map (lambda (f) (f any-val))
(list number? string? paren-expr? bin-op-expr? if-Z-expr?)))
|
(foldl or
false
(map (lambda (f) (f any-val))
(list number? string? paren-expr? bin-op-expr? if-Z-expr?)))
|
(ormap (map (lambda (f) (f any-val))
(list number? string? paren-expr? bin-op-expr? if-Z-expr?)))
|
(define (is-expr? any-val)
(ormap (map (lambda (f) (f any-val))
(list number? string? paren-expr? bin-op-expr? if-Z-expr?)))
|
2
Well, if they were concerned about traversing the list
twice (once with
(define (is-expr? any-val)
(foldl (lambda (f found-it) (or found-it (f any-val)))
false
(list number? string? paren-expr? bin-op-expr? if-Z-expr?)))
|
home—lectures—exams—hws—breeze (snow day)
| ©2011, Ian Barland, Radford University Last modified 2011.Oct.28 (Fri) |
Please mail any suggestions (incl. typos, broken links) to ibarland |
![]() |