Lisp/Scheme/Racket question: Convering string to procedure call.

Discussion in 'Programmer's Corner' started by WBahn, Aug 29, 2012.

  1. WBahn

    Thread Starter Moderator

    Mar 31, 2012
    Hopefully there is someone out there that is familiar with one of these functional languanges. In particular, I am working with Racket.

    Let's say that I have an expression that returns a string that is the name of a function. For example:

    (string-append "li" "st")

    I then want to use that expression in place of the literal function name in a procedure call. For instance, instead of saying:

    (list 'A 'B)

    I want to do something like:

    ((string-append "li" "st") 'A 'B)

    The problem I am having is that I can't figure out either how to convert the string to an acceptable procedure call or how to convert it to something that I can use with 'apply' or 'eval' in order to execute it.

    For context, what I am trying to do is have the user enter two words and then combine those words, along with some other text, into a procedure name and then execute that procedure. My understanding is that one of the strengths of these languages is that you can do things like this.
  2. WBahn

    Thread Starter Moderator

    Mar 31, 2012
    Through lots of searching and trial and error, I figured it out. It's actually pretty simple. For anyone else that might ever need this, here is the answer:

    The form for the 'eval' function is

    (eval list-form)

    where list-form is a list representing the function call you want to execute. So you might have:

    (eval '(+ 3 5))

    and this will work.

    If you want to get the '+' symbol from the keyboad, you can use read, like this:


    But you can't go

    (eval '((read) 3 5))

    The trick is to construct the list explicitly, as follows:

    (eval (list (read) 3 5))

    Which works fine.