Question

I am trying to learn input output in sml.In an effort to copy strings of lsthat are the same as s1 into the file l2 I did the following.I am getting some errors I can not really understand.Can someone help me out.

fun test(l2:string,ls:string list,s1:string) = if (String.isSubstring(s1 hd(ls))) then

                       (TextIO.openOut l2; TextIO.inputLine hd(ls))::test(l2,tl(ls),s1) else 

                       test(l2,tl(ls),s1);
Was it helpful?

Solution

Here are some general hints:

  1. Name your variables something meaningful, like filename, lines and line.
  2. The function TextIO.inputLine takes as argument a value of type instream.
  3. When you write TextIO.inputLine hd(ls), what this is actually interpreted as is (TextIO.inputLine hd) ls, which means "treat hd as if it were an instream and try and read a line from it, take that line and treat it as if it were a function, and apply it on ls", which is of course complete nonsense.

    The proper parenthesising in this case would be TextIO.inputLine (hd ls), which still does not make sense, since we decided that ls is a string list, and so hd ls will be a string and not an instream.

Here is something that resembles what you want to do, but opposite:

(* Open a file, read each line from file and return those that contain mySubstr *)
fun test (filename, mySubstr) =
    let val instr = TextIO.openIn filename
        fun loop () = case TextIO.inputLine instr of
                          SOME line => if String.isSubstring mySubstr line
                                       then line :: loop () else loop ()
                        | NONE => []
        val lines = loop ()
        val _ = TextIO.closeIn instr
    in lines end

You need to use TextIO.openOut and TextIO.output instead. TextIO.inputLine is one that reads from files.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top