scheme - Ascending Numbers in Macro Definition -


i use racket's pattern-matching construct match, , thought way myself debugging programs using match, , learn how racket/scheme macros work, create macro includes information pattern matched.

in other words, i'm looking create macro that, given this:

(match/debug 'two   ['one 1]   ['two 2]) 

outputs this:

case 2 <-- printed 2      <-- returned value 

the main obstacle far has been trying numbers signifying resolved case show correctly.

my target try write expand this:

(match 'two   ['one (displayln "case 1") 1]   ['two (displayln "case 2") 2]) 

but haven't been able figure out way generate "case #" strings.

here attempted macro definition:

(define-syntax-rule (match/debug id [pattern value] ...)   (let ([index 0])     (match id       [(begin          (set! index (add1 index))          pattern)        (printf "case ~a\n" index)        value] ...))) 

it appears though syntax of match won't let me this, way think of. i'm used common lisp's style of macros.

here solution.

the helper function clauses->numbers returns list of numbers 0 1 less number of clauses. used give each clause own number. note solution counts 0 (and not 1 in examples).

#lang racket (require (for-syntax syntax/parse))  (begin-for-syntax   (require racket/list) ; import range   (define (clauses->numbers stx)     (range (length (syntax->list stx)))))  (define-syntax (match/debug stx)   (syntax-parse stx     [(_match/debug id [pattern value] ...)      (with-syntax ([(n ...) (clauses->numbers #'([pattern value] ...))])        (syntax/loc stx          (match id            [pattern (begin (displayln (~a "case: " n)) value)]            ...)))]))  (match/debug 'one   ['one 1]   ['two 2])  (match/debug 'two   ['one 1]   ['two 2]) 

the output:

case: 0 1 case: 1 2 

Comments

Popular posts from this blog

jOOQ update returning clause with Oracle -

java - Warning equals/hashCode on @Data annotation lombok with inheritance -

java - BasicPathUsageException: Cannot join to attribute of basic type -