Ceelos
Ceelos

Reputation: 1126

Writing out to a file in scheme

The goal of this is to check if the character taken into account is a number or operand and then output it into a list which will be written out to a txt file. I'm wondering which process would be more efficient, whether to do it as I stated above (writing it to a list and then writing that list out into a file) or being writing out into a txt file right from the procedure. I'm new with scheme so I apologize if I am not using the correct terminology

(define input '("3" "+" "4"))

(define check
   (if (number? (car input))
    (write this out to a list or directly to a file)
    (check the rest of file)))

Another question I had in mind, how can I make it so that the check process is recursive? I know it's a lot of asking but I've getting a little frustrated with checking out the methods that I have found on other sites. I really appreciate the help!

Upvotes: 4

Views: 4146

Answers (1)

Óscar López
Óscar López

Reputation: 235994

It's a good idea to split the functionality in two separate procedures, one for generating a list of strings and the other for writing them to a file. For the first procedure, I'll give you the general idea so you can fill-in the blanks (this is a homework after all), it follows the standard structure of a recursive solution:

(define (check input)
  (cond ((null? input) ; the input list is empty
         <???>)        ; return the empty list
        ((string->number (car input)) ; can we convert the string to a number?
         (cons "number"  <???>)) ; add "number" to list, advance the recursion
        (else                    ; the string was not a number
         (cons "operand" <???>)))) ; add "operand" to list, advance recursion

For the second part, the general idea goes like this:

(define (write-to-file path string-list)
  (call-with-output-file path
    (lambda (output-port)
      (write <???> output-port)))) ; how do you want to write string-list ?

Of course, in the above procedure you can fiddle with the body of the lambda to produce the output as you expect it from the list of strings, for instance - as a list of strings, or a string in each line, or as a single line with a series of strings separated by spaces, etc. You'll invoke both procedures like this:

(write-to-file "/path/to/output-file"
               (check input))

Upvotes: 3

Related Questions