How to convert string to variable-name in scheme

后端 未结 2 587
情书的邮戳
情书的邮戳 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: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
    

提交回复
热议问题