Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>It is very possible to do exactly that in Racket, and in a much shorter way than done above. There are two (not-really) tricks involved:</p> <ol> <li><p>Using Racket's <a href="http://docs.racket-lang.org/reference/__top.html#%28form._%28%28quote._~23~25kernel%29._~23~25top%29%29"><code>#%top</code></a> macro makes it possible to create such bindings-out-of-thin-air. This macro is getting used implicitly around any variable reference that is unbound ("top" because these things are references to toplevel variables).</p></li> <li><p>Macros become much simpler if you make them do the necessary minimum, and leave the rest to a function.</p></li> </ol> <p>Here's the complete code with comments and tests (the actual code is tiny, ~10 lines).</p> <pre><code>#lang racket ;; we're going to define our own #%top, so make the real one available (require (only-in racket [#%top real-top])) ;; in case you want to use this thing as a library for other code (provide #%top) ;; non-trick#1: doing the real work in a function is almost trivial (define (c...r path) (apply compose (map (λ(x) (case x [(#\a) car] [(#\d) cdr])) path))) ;; non-trick#2: define our own #%top, which expands to the above in ;; case of a `c[ad]*r', or to the real `#%top' otherwise. (define-syntax (#%top stx) (syntax-case stx () [(_ . id) (let ([m (regexp-match #rx"^c([ad]*)r$" (symbol-&gt;string (syntax-e #'id)))]) (if m #`(c...r '#,(string-&gt;list (cadr m))) #'(real-top . id)))])) ;; Tests, to see that it works: (caadadr '(1 (2 (3 4)) 5 6)) (let ([f caadadr]) (f '(1 (2 (3 4)) 5 6))) ; works even as a value (cr 'bleh) (cadr '(1 2 3)) ; uses the actual `cadr' since it's bound, ;; (cadr '(1)) ; to see this, note this error message ;; (caddddr '(1)) ; versus the error in this case (let ([cr list]) (cr 'bleh)) ; lexical scope is still respected </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload