[gambit-list] Bashing in scheme?

Marc Feeley feeley at iro.umontreal.ca
Wed Apr 23 12:18:03 EDT 2008


On 23-Apr-08, at 11:26 AM, David St-Hilaire wrote:

> Hello all!
>
> I'd like a little help with some bash style scripting that I would  
> like to do in
> my gambit repl.
>
> How can I do in scheme what I would do in bash like f1 < input-file  
> | f2, where
> f1 and f2 are 2 scheme functions reading and writing to stdin and  
> stdout
> respectively.
>
> I know that the < input-file part is done with
> (with-input-from-file input-file (lambda () f1)
> put it is the pipe part that remains obscur to me...


You don't need to create files, or execute shell commands.  It can all  
be done within Gambit using threads and "pipe" string ports:

(define (producer)
   (for-each (lambda (x)
               (thread-sleep! 0.5) ;; simulate heavy computation
               (pretty-print (* x x x))
               (force-output))
             '(1 2 3))
   (if (not (tty? (current-output-port)))
       (close-output-port (current-output-port))))

(define (consumer)
   (let loop ()
     (let ((x (read)))
       (if (not (eof-object? x))
           (begin
             (pretty-print (sqrt x))
             (force-output)
             (loop)))))
   (if (not (tty? (current-output-port)))
       (close-output-port (current-output-port))))

(define (pipe p c)
   (receive (out in) (open-string-pipe '(direction: output))
     (let ((t
            (thread-start!
             (make-thread
              (lambda ()
                (with-output-to-port out p))))))
       (with-input-from-port in c))))

(display "------------------------\n")

;; try it with producer outputting to console
(producer)

(display "------------------------\n")

;; now, pipe producer's output to consumer's input
(pipe producer consumer)

(display "------------------------\n")

;; a more complex pipe...
(pipe (lambda () (pipe producer consumer)) consumer)




More information about the Gambit-list mailing list