Search code examples
macrosracket

How to flatten nested lists with syntax templates?


I'm working through the examples in Mythical Macros and am completely stumped on result6.

The goal is to replace the ???-pattern and ???-template in the following snippet in order to make it evaluate to true.

(define result6
  (with-syntax
    ([???-pattern (syntax ((a (1 "alpha") (2 "beta"))
                           (b (3 "gamma") (4 "delta"))))])
    (syntax ???-template)))
 
(equal? (syntax->datum result6)
        '((a b) (1 2 3 4) ("alpha" "beta" "gamma" "delta")))

I think I've got the pattern correct but am lost for how to do the template and probably splicing. My best iteration:

(define result6
  (with-syntax
    ([  ((l (n text) ...) ...)
      #'((a (1 "alpha") (2 "beta"))
         (b (3 "gamma") (4 "delta")))])
    #'( (l ...)  (~@ n ...) ... ) ))

This yields:

`((a b) 1 2 3 4)

I've not gotten the text template to work with anything I try. How do you solve this? What am I missing about this?


Solution

  • Got it!

    I made the pattern to parse more explicit and then fiddled my way through the template.

    (define syntax-example
      #'((a (1 "alpha") (2 "beta")) (b (3 "gamma") (4 "delta"))))
    
    (define result6
      (with-syntax
        ([ ( (l (n1 t1) (n2 t2)) ...) syntax-example])
        #'( (l ...) ((~@ n1 n2) ...) ((~@ t1 t2) ... ))))