Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #lang racket
- (require "ast.rkt")
- (provide (all-defined-out))
- (require rackunit)
- ;; Exercise 1.a
- ;; There is one solution with 1 line of code.
- (define p:empty (delay null))
- ;; Exercise 1.b
- ;; There is one solution with 1 line of code
- (define (p:empty? l)
- (empty? (force l )))
- ;; Exercise 1.d
- ;; There is one solution with 1 line of code.
- (define (p:first l)
- (car (force l)))
- ;; Exercise 1.e
- ;; There is one solution with 1 line of code
- (define (p:rest l)
- (cdr (force l)))
- ;; Exercise 1.f
- ;; There is one solution with 4 lines of code.
- (define (p:append l1 l2)
- (cond
- [(and (p:empty? l1) (p:empty? l2)) p:empty]
- [(p:empty? l1) (cons (p:first l2) (p:append l1 (p:rest l2)))]
- [else (delay (cons (p:first l1) (p:append (p:rest l1) l2)))]))
- ;; Exercise 2.a
- ;; Auxiliary functions;;
- (define (tree-left self)(p:first self))
- (define (tree-value self) (p:first (p:rest self)))
- (define (tree-right self) (p:first (p:rest (p:rest self)) ))
- ;; There is one solution with 10 lines of code.
- ;;(define (bst->p:list self) 'todo)
- (define (bst->p:list self)
- (cond [(p:empty? self) self]
- [else
- (p:append
- (bst->p:list (tree-left self))
- (delay (cons (tree-value self)
- (bst->p:list (tree-right self)))))]))
- ;; Exercise 3
- ;; Auxiliary functions
- (define (naturals)
- (define (naturals-iter n)
- (thunk
- (cons n (naturals-iter (+ n 1)))))
- ( (naturals-iter 0)))
- (define (stream-get stream) (car stream))
- (define (stream-next stream) ((cdr stream)))
- ;; There is one solution with 6 lines of code.
- #|(define (stream-foldl f a s)
- (define (foldl-aux aux stream)
- (thunk
- (cons (f (stream-get s) a)
- (foldl-aux (stream-next stream)))))
- ((foldl-aux s)))
- |#
- (define (stream-foldl f a s)
- (define (foldl-aux aux stream)
- (thunk
- (cons
- aux
- (foldl-aux (f (stream-get stream) aux) (stream-next stream))) ))
- ( (foldl-aux a s)))
- ;; Exercise 4
- ;; There is one solution with 3 lines of code.
- (define (stream-skip n s) 'todo)
- ;; Exercise 5
- (define (r:eval-builtin sym)
- (cond [(equal? sym '+) +]
- [(equal? sym '*) *]
- [(equal? sym '-) -]
- [(equal? sym '/) /]
- [else #f]))
- (define r:bool 'todo)
- (define r:bool? 'todo)
- (define r:bool-value 'todo)
- (define (r:eval-exp exp)
- (cond
- ; 1. When evaluating a number, just return that number
- [(r:number? exp) (r:number-value exp)]
- ; 2. When evaluating an arithmetic symbol,
- ; return the respective arithmetic function
- [(r:variable? exp) (r:eval-builtin (r:variable-name exp))]
- ; 3. When evaluating a function call evaluate each expression and apply
- ; the first expression to remaining ones
- [(r:apply? exp)
- ((r:eval-exp (r:apply-func exp))
- (r:eval-exp (first (r:apply-args exp)))
- (r:eval-exp (second (r:apply-args exp))))]
- [else (error "Unknown expression:" exp)]))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement