我希望从文件中读取N对,并将它们作为元组存储在list.For示例中,如果我有这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
当我运行它时,我得到了一个异常错误:/什么问题??
发布于 2020-04-30 13:56:05
我想出了这个解决方案。我从给定的文件中读取一行。在处理文本时,它去掉了除数字以外的所有内容,创建了一个单一的字符列表。然后,它将字符的平面列表拆分成对的列表,并在此过程中将字符转换为整数。我相信这是可以改进的。
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");
https://stackoverflow.com/questions/61509288
复制相似问题