[racket] a little macro exercise
I wrote mine without looking at Elis. I like his and mine better than
the others. And obvs I like mine more. =P
#lang racket
(require racket/stxparam)
(define-syntax-parameter break
(λ (stx) (raise-syntax-error 'break "Used outside cas-cad-e" stx)))
(define-syntax-rule (cas-cad-e e [(n ...) code ...] ...)
(let ([tmp e] [earlier? #f])
(let/ec esc
(syntax-parameterize
([break (make-rename-transformer #'esc)])
(when (or earlier? (equal? tmp n) ...)
(set! earlier? #t)
code ...)
...))))
(require tests/eli-tester)
(define printed "")
(define (cas1 v)
(set! printed "")
(cas-cad-e v
[(1) (set! printed (string-append printed "1"))]
[(2) (set! printed (string-append printed "2")) (break 2)]
[(3) 3]))
(test (cas1 1) => 2
printed => "12"
(cas1 2) => 2
printed => "2"
(cas1 3) => 3
printed => ""
(cas1 4) => (void)
printed => "")
(define (cas3 v)
(let ([w true])
(cas-cad-e v
[(0) (set! w false)]
[(1) (if w (break 1) (break 0))])))
(test (cas3 0) => 0
(cas3 1) => 1)
On Fri, Oct 8, 2010 at 9:18 PM, Neil Van Dyke <neil at neilvandyke.org> wrote:
> Eli Barzilay wrote at 10/08/2010 10:57 PM:
>>
>> Here's a much shorter version that doesn't require goto emulation,
>
> Nice. On principle, I was going to trouble to avoid redundant tests, as
> well as give the compiler a single optimization-friendly "case" form,
> followed by tail calls. In practice, I guess any runtime performance
> difference would likely be in the noise.
>
> --
> http://www.neilvandyke.org/
> _________________________________________________
> For list-related administrative tasks:
> http://lists.racket-lang.org/listinfo/users
>
--
Jay McCarthy <jay at cs.byu.edu>
Assistant Professor / Brigham Young University
http://teammccarthy.org/jay
"The glory of God is Intelligence" - D&C 93