2010-11-29 37 views
4

我正在嘗試讀取文件並將從文件中讀取的元素作爲輸入返回給另一個函數。從文件返回值 - ocaml

當我從文件中讀取數據時,如何返回值? 我嘗試了我所知道的一切,但仍然無法挽回。

我的代碼如下:

let file = "code.txt";; 

let oc = open_out file in (* create or truncate file, return channel *) 

    fprintf oc "%s\n" (play); (* write code to file returned from calling (play) function *) 

    close_out oc ;; 


(*read from file*) 


let read l= 

    let f x = 

     let ic = open_in file in 

     let line = input_line ic in (* read line from in_channel and discard \n *) 

      print_endline line;   (* write the result to stdout *) 

       ((x^line) :: l); 

      flush stdout;     

      close_in ic ; 
    in 
    f l 
    ;; 

prompt: read;; function call outputs: 

- : unit =() 

我的文件包含一個字符串,它是需要的,作爲另一個功能輸入一個代碼。

請幫忙。我不知道我哪裏出錯了。

謝謝。

回答

4

如果使用;將多個表達式排在一起,則整個表達式的值就是該序列中最後一個表達式的值。

因此,如果您有類似((x^line) :: l); close_in ic的值,則表達式的值爲close_in ic,即()

很明顯,這不是你想要的。爲了使((x^line) :: l)整個表達式的結果,你應該把它放在close_in ic之後。

+0

非常感謝你!我完全失去了!謝謝 :) – JJunior 2010-11-29 20:15:11