[racket] Compile-time evaluation

From: Roman Klochkov (kalimehtar at mail.ru)
Date: Mon Jul 29 20:48:59 EDT 2013

#. calcuclates its argument and place it in the program code.
Now I have to write something like 

(case state-number
  ((0 1) ; state in init, stage1
     (initialize))
   ((2) ; state = process
       (function1)
   ((3) ; state = abort
       (function2)))

I want to have

(define (state x)
  (let rec ([states '(init stage1 process fail)]
            [pos 0])
    (cond
      [(null? states) #f]
      [(eq? (car states) x) pos]
      [else (rec (cdr states) (add1 pos))])))

(case state-number
  ((#.(state 'init) #.(state 'stage1))
     (initialize))
   ((#.(state 'process))
       (function1)
   ((#.(state 'fail))
       (function2)))

So the code becomes self-documenting. Like using enum values in C or Pascal.

Понедельник, 29 июля 2013, 13:32 -04:00 от Asumu Takikawa <asumu at ccs.neu.edu>:
>On 2013-07-29 06:25:21 +0400, Roman Klochkov wrote:
>> Is there simple way to calculate during compilation. Something like #.
>> in Common Lisp.
>
>Can you tell us what #. means in Common Lisp?
>
>I am guessing that you want to do something like the following:
>
>  #lang racket
>  (require (for-syntax syntax/parse))
>
>  ;; functions to compute costly constants
>  ;; at compile-time
>  (begin-for-syntax
>    (define (compute-x) ...)
>    (define (compute-y) ...)
>    (define (compute-z) ...))
>
>  ;; macro that defines x, y, z assuming
>  ;; suitable definitions of compute-x, etc.
>  (define-syntax (define-constants stx)
>    (syntax-parse stx
>      [(_ x:id y:id z:id)
>       #`(begin (define x #,(compute-x))
>                (define y #,(compute-y))
>                (define z #,(compute-z)))]))
>
>  (define-constants my-x my-y my-z)
>
>This will work if the `compute-` functions produce flat data that can be
>embedded in syntax, like numbers.
>
>Cheers,
>Asumu


-- 
Roman Klochkov

----------------------------------------------------------------------

-- 
Roman Klochkov
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.racket-lang.org/users/archive/attachments/20130730/bbd2d634/attachment.html>

Posted on the users mailing list.