4

I'm trying to read text from a file in SML but I can't get it to work. Here's what I'm trying

fun read file =
let val inStream = TextIO.openIn file

in
        TextIO.StreamIO.input1 inStream
end

The actual function call input1 is not important, all I want is to be able to read from a file.

Nosrettap
  • 10,940
  • 23
  • 85
  • 140

1 Answers1

6

You error is in TextIO.StreamIO.input1, you most likely mean TextIO.input1.

If you really need/wan't to work with the file using StreamIO, you have to convert the instream type returned by openIN, to an StreamIO.instream with the TextIO.getInstream function.

You can read more about all this in the SML Basis library TEXT_IO signature.

Remember that it is good practice to close the files when you are done reading from them.

Update

As suggested in the comments, you can either read in the entire file (if you know it is small) or you can read it line by line.
The easiest thing to do, if you wan't to get the contents word by word, is to split the content by whitespace. This way you will end up with a list of strings that represent each individual "words" from the file.

Jesper.Reenberg
  • 5,944
  • 23
  • 31
  • The reason I didn't think `TextIO.input1` was correct is that it's not listed in the TEXT_IO signature. All I want is to be able to read word by word a text file. – Nosrettap Jan 25 '13 at 03:28
  • @Nosrettap: `input1` is part of the `IMPERATIVE_IO` signature, which is included in `TEXT_IO`. However, unless your file is really large, I'd rather use `inputAll` and do the processing on the string you get. – Andreas Rossberg Jan 25 '13 at 09:04
  • @Nosrettap, I don't blame you for getting confused about this. The basis library haven't made it easy to decipher. Take this comment for once "The signature given below for TEXT_IO is not valid SML [...]". Maybe you will get more insight if you look at the MosML documentation on [TextIO](http://www.itu.dk/~sestoft/mosmllib/TextIO.html). Note however that it is not all of MosML's modules that conform to the basis library definition (sadly). Just so you don't start using it as you main reference for SML/NJ. – Jesper.Reenberg Jan 25 '13 at 14:23
  • Do you know how to split words by white space? Is there a specific api call or do I have to write my own function? Thanks – Nosrettap Jan 25 '13 at 14:53
  • @Nosrettap: `String.tokens Char.isSpace "bla bla"` should do the trick. – Andreas Rossberg Jan 25 '13 at 17:44