How to convert string to variable-name in scheme

后端 未结 2 568
情书的邮戳
情书的邮戳 2021-01-06 21:15

How can I achieve below in Scheme REPL? Create a variable name from a string.

=>(define (string->variable-name "foo") 12)

=>foo

相关标签:
2条回答
  • 2021-01-06 21:43

    Forgetting the syntax for a moment:

    (define string->variable-name string->symbol)
    
    (define name->value-mapping '())
    
    (define (name-set! name value)
      (set! name->value-mapping
            (cons (cons name value)
                  name->value-mapping))
      value)
    
    (define (name-get name)
      (cond ((assoc name name->value-mapping) => cdr)
            (else 'unbound)))
    

    Sure you can't do (+ 5 <my-named-value>) without some other help...

    0 讨论(0)
  • 2021-01-06 21:45

    If what you're passing to string->variable-name is always a string literal (i.e., not a variable that contains a string), you can do that using a syntax-case macro that transforms the string literal to an identifier:

    (define-syntax string->variable-name
      (lambda (stx)
        (syntax-case stx ()
          ((_ str)
           (string? (syntax->datum #'str))
           (datum->syntax #'str (string->symbol (syntax->datum #'str)))))))
    

    and conversely, a variable-name->string macro could look like this:

    (define-syntax variable-name->string
      (lambda (stx)
        (syntax-case stx ()
          ((_ id)
           (identifier? #'id)
           (datum->syntax #'id (symbol->string (syntax->datum #'id)))))))
    

    However, remember: this will only work if you are working with string (in case of string->variable-name) or identifier (in case of variable-name->string) literals.


    If, on the other hand, you want the ability to reflect on names in your current Scheme environment, this is not supported by standard Scheme. Some implementations, like Guile or Racket, do have this capability.

    Here's a Guile example:

    > (module-define! (current-module) 'foo 12)
    > foo
    12
    > (define varname 'bar)
    > (module-define! (current-module) varname 42)
    > bar
    42
    

    and a Racket example:

    > (namespace-set-variable-value! 'foo 12)
    > foo
    12
    > (define varname 'bar)
    > (namespace-set-variable-value! varname 42)
    > bar
    42
    
    0 讨论(0)
提交回复
热议问题