Translate X-Expressions to Keyword Procedure Applications
1 Reference
apply-xexpr-element
make-xexpr-proc
kwargs->attributes
7.7

Translate X-Expressions to Keyword Procedure Applications

Sage Gerard

 (require dynamic-xml) package: dynamic-xml

This small library provides the means to apply keyword procedures using X-expressions. This is useful for XML-based document processors that either want to support custom elements, or transform existing elements.

Beware: While I mention the xexpr? predicate below, my contracts don’t actually use it. The cost of checking element trees add up quickly, so I don’t impose it.

1 Reference

procedure

(apply-xexpr-element x    
  [#:recurse? recurse?    
  lookup])  xexpr?
  x : xexpr?
  recurse? : boolean? = #t
  lookup : (-> symbol? procedure?) = make-xexpr-proc
Let this element be bound to E:

'(p ((id "my-paragraph") (class "colorized"))
    (b "I am bold") "and I am bland.")

(apply-xexpr-element E #:recurse? #f) is equivalent to the following expression:

((lookup 'p) #:id "my-paragraph"
             #:class "colorized"
             '(b ((style "color: #f00")) "I am bold")
             "and I am bland.")

When #:recurse? is set to a true value, then the same treatment applies to all descendent elements.

((lookup 'p) #:id "my-paragraph"
             #:class "colorized"
             ((lookup 'b) #:style "color: #f00" "I am bold")
             "and I am bland.")

(apply-xexpr-element #:recurse? #t E make-xexpr-proc) will return an X-expression equivalent to E, except attributes will match the keyword<? ordering imposed by an internal use of keyword-apply, and empty attribute lists will be removed from the output. To adjust the latter behavior, bind lookup to a different use of make-xexpr-proc.

procedure

(make-xexpr-proc t    
  [#:always-show-attrs? show-attrs])  procedure?
  t : symbol?
  show-attrs : any/c = #f
Returns a procedure that creates X-expressions with tag t.

Keyword arguments turn into the attribute list of the output element. Formal arguments turn into children of said element.

If the element has no attributes, then no attribute list will appear in the output X-expression unless show-attrs is a true value.

> ((make-xexpr-proc 'script) #:type "text/javascript" "function foo() { return 1 + 1; }")

'(script ((type "text/javascript")) "function foo() { return 1 + 1; }")

> ((make-xexpr-proc #:always-show-attrs? #t 'p) "hi")

'(p () "hi")

procedure

(kwargs->attributes kws kw-args)  list?

  kws : (listof keyword?)
  kw-args : list?
A helper procedure that translates keyword arguments into an X-expression attribute list. The attributes follow the order of kws and kw-args.

> (kwargs->attributes '(#:id #:style) '("ID" "color: #fff"))

'((id "ID") (style "color: #fff"))