[plt-scheme] Re: Text-contents to a function variable

From: Thomas Chust (chust at web.de)
Date: Wed Jan 13 10:48:42 EST 2010

2010/1/13 Avi <n4alpaca at gmail.com>:
> I'm sorry for being vague. What I want to do is take a letter that is
> typed into a text-field in a GUI (the letter has a pre-defined number)
> and plug the letter into a function.
> [...]

Hello Avi,

text fields contain strings, so probably you want to extract a single
letter first using string-ref and maybe normalize the case of that
character, somewhat like this:

  (define (get-first-entered-char)
    (char-upcase (string-ref (get-the-text-field-contents-somehow) 0)))

Now, the canonical solution to map one set of objects to another is a
hash table, for example:

  (define (letter->number l)
    (hash-ref '#hasheqv([#\H . 1] [#\X . 42]) l))

  (do-something (letter->number (get-first-entered-char)))

However, what you say sounds like you might want to dispatch on
different characters in the function that gets called eventually,
which can be done directly rather than mapping them to numbers first —
mapping them first will gain you nothing unless you want to perform
some computation on these numbers. So you could try something along
these lines:

  (define (do-something l)
    (case l
      [(#\H) (display "H was entered") (newline)]
      [(#\X) (display "X was entered") (newline)]
      [else (display "something else was entered") (newline)]))

  (do-something (get-first-entered-char))


When C++ is your hammer, every problem looks like your thumb.

Posted on the users mailing list.