ysig
ysig

Reputation: 507

Reading an integer file to an integer list in sml

Hi i won't to make a function in standard ML that takes as input integers separated by spaces in many lines and returns a list of them one by one. For example, for the input file

3 4 5 6 7 8 4
4 5 6 2 3 
6 4 3 2
2 3 5 6 7

to return a list [3,4,5,6,7,8,4,4,5,6,2,3,6,4,3,2,2,3,5,6,7].

I had tried to figure it out myself but i couldn't because i don't have good knowledge of ML's IO functions. I would appreciate your help. Thank you

Upvotes: 1

Views: 1997

Answers (3)

KLkldsdk
KLkldsdk

Reputation: 11

Try this :)

  fun readint(infile : string) = let

        val ins = TextIO.openIn infile


    fun loop ins =

        case TextIO.scanStream( Int.scan StringCvt.DEC) ins of

    SOME int => int :: loop ins

    | NONE => []

          in
 loop ins before TextIO.closeIn ins

  end;

Upvotes: 1

george
george

Reputation: 1829

I agree with Sebastian. here is an example reading integer

fun int_from_stream stream =
  Option.valOf (TextIO.scanStream (Int.scan StringCvt.DEC) stream)

val fstream = TextIO.openIn file
val N = int_from_stream fstream

Upvotes: 2

You can use a combination of TextIO.scanStream and Int.scan. This will produce an int option, which contains the next integer in the file if one is available.

You can then simply build up a list of all the integers in the file, by calling this function repeatedly until you get a NONE, signifying that there are no more integers.

Upvotes: 2

Related Questions