Wednesday, April 16, 2008

A Simple match.ss Example

The match.ss pattern matching library is a terrifically powerful library. It not only reduces the pain of having to destructure objects manually (boy, could Java and the whole getXXX() convention use this), but it actually makes your code more readable.

I only have one tiny, itty-bitty problem with it. I always forget the frigging syntax to use it. And to make matters worse the examples section provides some impressive examples - but nothing simple enough to trigger my memory of the more basic usage of (match ...).

I've also found this recipe on the topic, but it's mostly text. So here, as mostly a reminder to myself, are some trivial examples of how to use match.ss.

I plan to thank myself later for this.

;;
;; Plain old list data (an sexpr).  This data
;; describes an HTML form.
;;
(define form-defn
  '((input name "Your Name" 30)
    (input phone "Your Phone" 30)
    (select occupation "Your Job" ("Programmer" "Bit-Pusher" "Developer" "Keyboard Jockey"))
    (submit "Thanks!")))

;;
;; Convert an individual defn row into HTML
;;
(define (defn->html defn)
  (match defn
    (('input name label width)
     (format "~a: <input name='~a' size='~a'/><br/>\n" label name width))
    (('select name label choices)
     (format "~a: <select name='~a'>~a</select><br/>\n" label name 
             (map (lambda (o)
                    (format "<option>~a</option>" o))
                  choices)))
    (('submit label)
     (format "<input type='submit' value='~a'/><br/>\n" label))))

;; use our functions
(for-each display
          (map defn->html form-defn))

And here's the output:

Your Name: <input name='name' size='30'/><br/>
Your Phone: <input name='phone' size='30'/><br/>
Your Job: <select name='occupation'>(<option>Programmer</option> <option>Bit-Pusher</option> <option>Developer</option> <option>Keyboard Jockey</option>)</select><br/>
<input type='submit' value='Thanks!'/><br/>

No comments:

Post a Comment

LinkWithin

Related Posts with Thumbnails