Search code examples
smlsmlnjml

Read file character by character in SMLNJ


I need to read a text file character by character in SMLNJ and store it in a list. The file consists of one line with numbers, without spaces or any form of separation. My question is how do I get a single character from the file and add it to the list of characters?

Example:

12345678

Result:

val input = [1, 2, 3, 4, 5, 6, 7, 8]

Solution

  • Using the following code you can get a list of characters by reading the contents of the file as a string (TextIO.vector to be accurate). The explode function is used for the conversion to a list of characters.

    fun parse file =
    let
        fun next_String input = (TextIO.inputAll input) 
        val stream = TextIO.openIn file
        val a = next_String stream
    in
        explode(a)
    end