;; The first three lines of this file were inserted by DrScheme. They record metadata ;; about the language level of this file in a form that our tools can easily process. #reader(lib "htdp-beginner-reader.ss" "lang")((modname 1-3) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ()))) #| ----------------------------------------------------------------------------- PROBLEM: Design a program that renders an Exprs as an image. The main function must consume an Expr and a boolean flag. It produces an image of the given Expr; the boolean determines whether the Expr should be rendered as a prefix or an infix expression. |# (require htdp/image) (define-struct pls (x y)) (define-struct mul (x y)) ;; Expr is one of: ;; -- (make-pls Number Number) ;; -- (make-mul Number Number) ;; interp. a pls struct represents an addition, ;; and a mul struct represents a multiplication (define FTSZ 11) ;; for resizing from one point (define FTCL "black") ;; for recoloring from one point ;; graphical constants (define LFT (text "(" FTSZ FTCL)) (define PLS (text "+" FTSZ FTCL)) (define MLT (text "*" FTSZ FTCL)) (define SPC (text " " FTSZ FTCL)) (define RGT (text ")" FTSZ FTCL)) ;; testing constants (define ONE (text "1" FTSZ FTCL)) ;; ----------------------------------------------------------------------------- ;; Expr Boolean -> Image ;; render e as either a prefix? (true) or infix (false) expression (check-expect (render (make-pls 1 1) true) (text "(+ 1 1)" FTSZ FTCL)) (check-expect (render (make-pls 1 1) false) (text "(1 + 1)" FTSZ FTCL)) (check-expect (render (make-mul 1 1) true) (text "(* 1 1)" FTSZ FTCL)) (check-expect (render (make-mul 1 1) false) (text "(1 * 1)" FTSZ FTCL)) (define (render e prefix?) (cond [(pls? e) (if prefix? (parens PLS (txt (pls-x e)) (txt (pls-y e))) (parens (txt (pls-x e)) PLS (txt (pls-y e))))] [(mul? e) (if prefix? (parens MLT (txt (mul-x e)) (txt (mul-y e))) (parens (txt (mul-x e)) MLT (txt (mul-y e))))])) ;; ----------------------------------------------------------------------------- ;; Image Image Image -> Image ;; create image by adding parens around and SPACE between the three given images (check-expect (parens ONE PLS ONE) (image-append LFT (image-append (image-append ONE SPC PLS) SPC ONE) RGT)) (define (parens one two three) (image-append LFT (image-append (image-append one SPC two) SPC three) RGT)) ;; ----------------------------------------------------------------------------- ;; Number -> Image ;; turn the given number into an FTSZpt black text (check-expect (txt 1) (text "1" FTSZ FTCL)) (define (txt n) (text (number->string n) FTSZ FTCL)) ;; ----------------------------------------------------------------------------- ;; Image Image Image -> Image ;; append images horizontally along top-most line (check-expect (image-append LFT ONE SPC) (text "(1 " FTSZ FTCL)) (define (image-append i j k) (overlay/xy i (image-width i) 0 (overlay/xy j (image-width j) 0 k)))