I need to read file in ML (SLMNJ) and save it in some structures. I need to read some data that points to graph declaration:
[( 1 , 2 , 13 ),( 2 , 3 , 3 ),( 2 , 4 , 8 ),( 2 , 5 , 4 ),( 3 , 1 , 5 ),( 3 , 4 , 1 ),( 4 , 6 , 5 ),( 5 , 5 , 5 ),( 6 , 4 , 6 )]
(first number: name of the node , secend number: name of connected node , third number weight for this mane (each () show one mane ) )
for expamle this is test input how to read file and which structure to save it
for reading from file follow this to list of string per line :
val infile = "c:/input.txt" ;
fun readlist (infile : string) = let
val ins = TextIO.openIn infile
fun loop ins =
case TextIO.inputLine ins of
SOME line => line :: loop ins
| NONE => []
in
loop ins before TextIO.closeIn ins
end ;
val pureGraph = readlist(infile);
and with this function you can parse it to tuple (x,y,z ) :
fun creatGraph([],reList) = reList
|creatGraph(x::y::z::input,reList) = creatGraph(input,reList@[(x,y,z)]);
This problem is perfectly suited to parsing combinators, which you can steal from my friend Greg Morrisett at Harvard.
If you want to understand the underlying ideas, read Graham Hutton's paper Higher-Order Functions for Parsing. If you want to know how to implement I/O in Standard ML, consult the TextIO
module in the Standard Basis Library. If you want someone to write the code for you, you may have reached the wrong web site.
来源:https://stackoverflow.com/questions/2168029/open-file-in-mlsmlnj