我想从文件中读取N对,并将它们作为元组存储在列表中。例如,如果我具有以下3对:1-2,7-3,2-9我希望我的列表看起来像这样- > [(1,2),(7,3),(2-9)]
我尝试过这样的事情:
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
当我运行它时,我遇到了exeption错误:/怎么了?
我想出了这个解决方案。我从给定的文件中读取一行。在处理文本时,它会剥离不包含数字的所有内容,从而创建一个字符的平面列表。然后,它将平面字符列表拆分为成对列表,然后在此过程中将字符转换为整数。我相信它可以得到改善。
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");