0

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);
4

1 回答 1

1

以下是一些一般性提示:

  1. 将变量命名为有意义的名称,filename例如linesline
  2. 该函数TextIO.inputLine将 type 的值作为参数instream
  3. 当您编写TextIO.inputLine hd(ls)时, this 实际上被解释为 is (TextIO.inputLine hd) ls,这意味着“将hd其视为 aninstream并尝试从中读取一行,取该行并将其视为一个函数,并将其应用于ls”,这当然完全是胡说八道。

    在这种情况下,正确的括号是TextIO.inputLine (hd ls),这仍然没有意义,因为我们决定那ls是 a string list,所以hd ls 将是 astring而不是 a instream

这是类似于您想要做的事情,但相反:

(* 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

您需要使用TextIO.openOutandTextIO.output来代替。TextIO.inputLine是从文件中读取的一种。

于 2013-11-08T18:21:13.433 回答