Tarun Maganti
Tarun Maganti

Reputation: 3086

How to use console as input and output for Guile Scheme?

I understand that Scheme uses ports to perform Input and Output. While trying to learn how to get console input and output, I have come across MIT-Scheme's console-i/o-port variable.

But, the guile interpreter says it is an Unbound Variable. I would like to know how we can use ports to get input from and output to the console (Terminal in Unix) in a Guile Scheme Script. I am still a rookie in Scheme and Linux, a clear step-by-step is appreciated.

Also, how does (display <object>) work? Does it use ports inherently or is there another way.

P.S. If there is another way without using ports please let me know how to use that too.

Upvotes: 3

Views: 3480

Answers (2)

dercz
dercz

Reputation: 962

If you want to read and write SExps, in guile you have (read), (write), (display) etc., if you want to read characters only use (read-char) and (write-char) -- they all use the input/output ports resp. you picked, by default they are stdin and stdout. Everything is rather straightforward (https://www.gnu.org/software/guile/manual/html_node/Input-and-Output.html#Input-and-Output).

You might also be interested in guile-ncurses (https://www.gnu.org/software/guile-ncurses/).

Of some more goodies check out pretty-print module from ice-9 (on very long sexps it's slow but outputs them really nicely formatted, great for e.g. code generation):

  (use-modules (ice-9 pretty-print))
  (pretty-print `(super cool stuff (+ 2 3) => ,(+ 2 3)))

And if you need your own parser, check out the lalr module (system base lalr).

edit a small example which reads a number, multiplies by itself and prints out the result:

#!/usr/bin/guile -s
!#

(let ((x (read)))
  (display (* x x))
  (newline))

(remember to chmod +x this script).

edit changed the expression to let form as Chris suggested, indeed the fewer parentheses the better

Upvotes: 3

jcubic
jcubic

Reputation: 66650

In guile you have 2 functions: current-input-port and current-output-port (the docs)

to read and put text into string (if you don't want to read s-expressions) you can use this function:

(define (read-port port)
    (let iter ((result '()) (chr (read-char port)))
        (if (eof-object? chr)
            (list->string result)
            (iter (append result (list chr)) (read-char port)))))

reading from stdin will be:

(read-port (current-input-port))

to write to stdout you can use display it also accept second argument which is port relevant docs

Upvotes: 2

Related Questions