PasteRack.org
Paste # 17482
2018-11-23 11:35:24

Fork as a new paste.

Paste viewed 838 times.


Embed:

  1. #lang racket
  2. ;slightly modified from https://docs.racket-lang.org/memo/index.html (to use hash-equal?)
  3. (define-syntax-parser define/memoize
  4.                       ([_ (name:id formals:id ...+)
  5.                           (~optional (~seq #:finalize fin:expr) #:defaults [(fin #'(lambda x x))])
  6.                           body:expr ...+]
  7.                        #'(define name (memoize (formals ...) #:finalize fin body ...))))
  8. (define-syntax-parser memoize
  9.                       ([_ (param:id ...)
  10.                           (~optional (~seq #:finalize fin:expr) #:defaults [(fin #'(lambda x x))])
  11.                           body:expr ...+]
  12.                        #'(let ([cache (box (hash))])
  13.                            (case-lambda
  14.                              [() cache]
  15.                              [(param ...)
  16.                               (let ([result (nested-hash-ref (unbox cache) param ... #:default #f)])
  17.                                 (if result
  18.                                   result
  19.                                   (let ([value ((lambda () body ...))])
  20.                                     (set-box! cache (nested-hash-set (unbox cache) param ... value))
  21.                                     (register-finalizer value fin)
  22.                                     value)))]))))
  23.  
  24.  
  25. ; converts a SQL statement string into a prepared SQl statement
  26. (define/memoize (prepared sql) (prepare (sqldb-param) sql))
  27.  
  28. ; example use
  29. (define/memoize (tag-id-lookup t)
  30.   (query-value (sqldb-param) (prepared "SELECT tag_id FROM Tags WHERE tag_name=?") t))

=>

eval:2:0: _: wildcard not allowed as an expression

  in: (_ (name:id formals:id ...+) (~optional (~seq

#:finalize fin:expr) #:defaults ((fin (syntax (lambda x

x))))) body:expr ...+)

eval:3:0: _: wildcard not allowed as an expression

  in: (_ (param:id ...) (~optional (~seq #:finalize

fin:expr) #:defaults ((fin (syntax (lambda x x)))))

body:expr ...+)

define/memoize: undefined;

 cannot reference an identifier before its definition

  in module: 'm

define/memoize: undefined;

 cannot reference an identifier before its definition

  in module: 'm