Question

I'm writing a function that returns a string, and the problem is that I want to store this string in a new file that should be created if it can't be found on the computer. Every string created by the function should end up in the same text file, one after another. How can this be implemented in SML? I've been stuck on this for a while now and could really need some help.

The part of my code where I want to use this looks like (show(solveAux(nls, sl, match(nl, sl, []))) is the string in question):

fun solve (nl::nls, sl) = let

fun solveAux ([], sl, cnll) = cnll
  | solveAux (nl::nls, sl, cnll) = List.concat(map(fn cnl => solveAux(nls, sl, match(nl, sl, cnl))) cnll)

in
    show(solveAux(nls, sl, match(nl, sl, [])))
end;

And I thought this should do the trick:

fun solve (nl::nls, sl) = 

let

  val writestream = TextIO.openAppend "test.txt";

  fun solveAux ([], sl, cnll) = cnll
    | solveAux (nl::nls, sl, cnll) = List.concat(map(fn cnl => solveAux(nls, sl, match(nl, sl, cnl))) cnll)

in

  TextIO.output (writestream, show(solveAux(nls, sl, match(nl, sl, []))))
  TextIO.closeOut writestream;

end

But apparently not...

Was it helpful?

Solution

You can use the TextIO structure for writing to files.

The openAppend lets you open a file in append mode, allowing you to append lines to the file if the file already exists, or create a file if none exists. This function provides you with an output stream you can use with the other IO functions.

The output function lets you write to a output stream. For instance:

TextIO.output(yourStream, "This is a message to write to your stream.");

Note, you need to remember to flush or close the stream, before you can be sure the data is actually written to the file on disk. Until you do one of those, the compiler may choose to delay writing the data to disk, to speed up execution.

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