Lisp HUG Maillist Archive

with-input-from-string reader closure problem

It seems to me that

    CL-USER 1 > (flet ((reader (stream)
                          (lambda ()
                            (read-char stream nil :eof))))
                   (funcall
                    (with-input-from-string (s "abc")
                      (reader s))))
    :EOF

    CL-USER 2 >

ought to evaluate to #\a.  Am I reading the spec wrong somehow?  Sure looks like an error to me.  I 
get the same result if I (defun reader (stream) ...).

Insights, fixes, workarounds much appreciated.

-Klaus.

PS. LWW Pro v4.3.7.


Re: with-input-from-string reader closure problem

Klaus Harbo wrote:
> It seems to me that
> 
>    CL-USER 1 > (flet ((reader (stream)
>                          (lambda ()
>                            (read-char stream nil :eof))))
>                   (funcall
>                    (with-input-from-string (s "abc")
>                      (reader s))))
>    :EOF
> 
>    CL-USER 2 >
> 

When with-input-from-string returns, it closes the stream s.
Thus the stream is closed before your funcall.

Do this instead:
CL-USER 1 > (flet ((reader (stream)
                (lambda ()
                  (read-char stream nil :eof))))
   (with-input-from-string (s "abc")
     (funcall (reader s))))
#\a

CL-USER 2 >

Just to show the stream is closed when the functions is called:
CL-USER 2 > (flet ((reader (stream)
                (lambda ()
                  (princ (open-stream-p stream))
                  (read-char stream nil :eof))))
   (funcall
    (with-input-from-string (s "abc")
      (reader s))))
NIL
:EOF

CL-USER 3 >

Wade






Updated at: 2020-12-10 08:55 UTC