0

I want to read N pairs from a file and store them as a tuples in a list.For example if i have these 3 pairs : 1-2 , 7-3, 2-9 i want my list to look like this -> [(1,2),(7,3),(2-9)]

I tried something like this:

   fun ex filename = 
 let
   fun readInt input = Option.valOf (TextIO.scanStream (Int.scan StringCvt.DEC) input)
   val instream = TextIO.openIn filename
   val T = readInt instream (*number of pairs*)
   val _ = TextIO.inputLine instream


fun read_ints2 (x,acc) =
if x = 0 then acc
else read_ints2(x-1,(readInt instream,readInt instream)::acc)
in
 ...
end

When i run it i get an exeption error :/ What's wrong??

panakran
  • 13
  • 3

1 Answers1

0

I came up with this solution. I reads a single line from the given file. In processing the text it strips away anything not a digit creating a single flat list of chars. Then it splits the flat list of chars into a list of pairs and in the process converts the chars to ints. I'm sure it could be improved.

fun readIntPairs file =
    let val is = TextIO.openIn file
    in
        case (TextIO.inputLine is)
        of NONE => ""
         | SOME line => line
    end

fun parseIntPairs data =
    let val cs = (List.filter Char.isDigit) (explode data)
        fun toInt c =
            case Int.fromString (str c)
             of NONE => 0
              | SOME i => i
        fun part [] = []
          | part [x] = []
          | part (x::y::zs) = (toInt x,toInt y)::part(zs)
    in
        part cs
    end

 parseIntPairs (readIntPairs "pairs.txt");
Psyllo
  • 674
  • 5
  • 8