Question

I have a function that takes a list and then prompts the user for a filename. this list is to be written to the default path, saved as filename

something like (pseudo code):

(define storeme
  (lambda (lst)  
    (write-list lst filename default-path)))

not sure how to get this to work. "write" only takes 2 arguments for write object & [output-port]. thanks

Was it helpful?

Solution 2

You should bind an output port to a variable

Something like

(define storeme
 (lambda (lst)
   (let* ((filename (prompt-for-filename)) ;;the prompt routine should retrun #f
          (output                           ;for invalid filenames or user cancellations
            (open-file-output-port ;;routine may vary be implementation and scheme revision
               (string-append *default-path* filename))))
    (begin (if filename 
               (begin (write lst output) (display-each "List Stored in " filename))
               (display "List not stored"))
           (close-output-port output)))))

OTHER TIPS

You need a full pathname from somewhere, assume you have it. Define your function as:

(define store-me-at
  (lambda (lst path)
    (with-output-to-file path (lambda () (write lst)))))

When using with-output-to-file the current-output-port is set for you so write doesn't need a port argument.

Doing it with with-output-to-file ensures that the port opened for path will always get closed, even if there is a non-local exit (or other subtleties involving call/cc and related use). If you just use open-output-file and then close-ouput-port you don't get any such guarantee.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top