Writing Files in Standard ML
Here’s the translation of the Go code to Standard ML, along with explanations in Markdown format suitable for Hugo:
Writing files in Standard ML follows similar patterns to the ones we saw earlier for reading.
To start, we write a string directly to a file using TextIO.writeFile
.
For more granular writes, we open a file for writing using TextIO.openOut
.
In Standard ML, there’s no built-in defer mechanism, so we need to manually close the file after we’re done writing.
We can write byte slices using BinIO.output
and a Word8Vector
.
For string writes, we use TextIO.output
.
To ensure all writes are flushed to stable storage, we use TextIO.flushOut
.
Standard ML doesn’t have a direct equivalent to Go’s bufio
, but we can use BinIO
for buffered I/O operations.
After writing to a buffered stream, we use BinIO.flushOut
to ensure all buffered operations have been applied to the underlying writer.
To run the file-writing code, save it as writing-files.sml
and use the Standard ML of New Jersey (SML/NJ) interpreter:
Then check the contents of the written files:
Next, we’ll look at applying some of the file I/O ideas we’ve just seen to the standard input and output streams.