jean28
jean28

Reputation: 102

Importing strings to Scheme without using open-input-string

I am trying to have my Scheme program import strings without needing to use open-input-string before the string. So for example, right now I can do the following:

> (scheme_lexer (open-input-string "3+4*2"))

However, is there a way for my program to work if I input the string this way?:

> (scheme_lexer ("3+4*2"))

Thank you!

Upvotes: 0

Views: 206

Answers (2)

Jack
Jack

Reputation: 2273

Is there any particular reason you can't just make a scheme_lexer_string function that does this for you when dealing with strings? The extra parentheses just seem like clutter, and they make a macro the only real solution. If you dropped that requirement and made something like (scheme_lexer "3+4*2") acceptable, you can make an ordinary function for handling strings:

(define (scheme_lexer_string s)
  (scheme_lexer (open-input-string s)))

If what you want is a function that handles both input ports and strings, you can make a general function that dispatches based on the type of the argument to the specific functions. In this case, your original scheme_lexer would be renamed to scheme_lexer_input_port and you would have these functions:

(define (scheme_lexer_string s)
  (scheme_lexer_input_port (open-input-string s)))

(define (scheme_lexer in)
  (if (string? in)
      (scheme_lexer_string in)
      (scheme_lexer_input_port in)))

Now scheme_lexer works for both strings and ports and dispatches to the correct function as desired.

> (scheme_lexer some-input-port)
... evaluates the content in the port
> (scheme_lexer "abcd")
... evaluates the string "abcd"

Upvotes: 1

Rptx
Rptx

Reputation: 1189

Here is one option. I have used a testing function lexer just to show the macro. You can adjust it to your needs.

(define (lexer sp) (read sp))

(define-syntax scheme_lexer
  (syntax-rules ()
    ((_ (input))
     (lexer (open-input-string input)))))

And to test:

> (scheme_lexer ("3+4*2"))
'3+4*2

Upvotes: 0

Related Questions