SML: Why no new line can't be written to file with “\n”

十年热恋 提交于 2020-01-06 02:19:10

问题


Below is a simple program to write an int list to a file:

fun write(num_list, file) = 
let 
    val output = TextIO.openOut file
    fun num(nil) = TextIO.closeOut output
      | num(n::ns) = (TextIO.output(output, Int.toString(n)); TextIO.output(output, "\n"); num(ns))
in
    num(num_list)
end;

Why no new line was written to file after each number printed?


回答1:


It appears that your code works and that a newline character is written after each number.

I have provided an alternative definition for your write function, but both appear to work.

fun writeInts (ints, filename) = 
    let val fd = TextIO.openOut filename
        val _ = List.app (fn i => TextIO.output (fd, Int.toString i ^ "\n")) ints
        val _ = TextIO.closeOut fd
    in () end

fun read filename =
    let val fd = TextIO.openIn filename
        val content = TextIO.inputAll fd
        val _ = TextIO.closeIn fd
    in content end

val test = (writeInts ([1,2,3,4], "hello.txt"); read "hello.txt" = "1\n2\n3\n4\n")


来源:https://stackoverflow.com/questions/33618000/sml-why-no-new-line-cant-be-written-to-file-with-n

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!