Skip to content

Instantly share code, notes, and snippets.

@clartaq
Created February 21, 2021 18:38
Show Gist options
  • Save clartaq/d0651636deb6e5e24168aac393d8d0e4 to your computer and use it in GitHub Desktop.
Save clartaq/d0651636deb6e5e24168aac393d8d0e4 to your computer and use it in GitHub Desktop.
File Operations in Scheme
;;;
;;; subset-dictionary.ss
;;;
;;; Build a dictionary of text words, one word per line, by taking
;;; every "skip-by"th word from the ENABLE_word_list.txt (available at
;;;https://www.wordgamedictionary.com/word-lists/words-with-friends/)
;;; file and writing it to subset_list.txt. Only save words that are at
;;; least three characters long but less than 10.
;;;
;;; Setting "skip-by" to one will process and save all of the words in
;;; the input, only filtering out the words outside of theacceptable
;;; size range.
;;;
;; Only write every "skip-by"th word.
(define skip-by 1000)
(define input-list-file-name "./word-lists/ENABLE_word_list.txt")
(define output-list-file-name "./word-lists/subset_list.txt")
;; Convenience procedure to display a series of arguments followed by a
;; newline.
(define (println . args)
(for-each display args)
(newline))
;; Process one line of the file. Note that this will skip writing words
;; even if they are a multiple of "skip-by" if they do not meet the
;; length requirements.
(define (process-line out-port line inp-cntr out-cntr)
(if (and (zero? (mod inp-cntr skip-by))
(< (string-length line) 10)
(> (string-length line) 2))
(begin
(display line out-port) (newline out-port)
(+ 1 out-cntr))
out-cntr))
;; Process the input file to the output file.
(define (process-files in-port out-port)
(let loop ((line (get-line in-port))
(inp-cntr 0)
(out-cntr 0))
(if (eof-object? line)
(begin
(println "Done!")
(println "Words in input file: " inp-cntr)
(println "Words in output file: " out-cntr))
(loop (get-line in-port) (+ 1 inp-cntr)
(process-line out-port line inp-cntr out-cntr)))))
;; Make a word list by processing the contents of the input file and
;; writing the results to the output file. It is assumed that the input
;; and the output are both text files with one word per line.
;;
;; NOTE: Any earlier version of the output file will be overwritten
;; without warning.
(define (make-word-list)
(let ((inp (open-input-file input-list-file-name))
(outp (open-output-file output-list-file-name '(replace))))
(dynamic-wind
(lambda () #f)
(lambda () (process-files inp outp))
(lambda ()
(close-port inp)
(close-port outp)))))
(make-word-list)
@clartaq
Copy link
Author

clartaq commented Feb 21, 2021

This is just a reminder to myself showing how to do simple file operations in (Chez) Scheme. You can find a blog file describing it in more detail here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment