我有這個功能在檔案中添加日志:
let log_datas f file (datas: 'a list) =
let oc = open_out file.file_name in
List.iter (fun x -> Printf.fprintf oc "%s" @@ f x) datas;
close_out oc
let () = let f = string_of_int in log_datas f {file_name="log"} [1;2]
哪個有效。
我試圖讓它默認接受字串串列作為引數:
let log_datas ?(f:'a -> string = fun x -> x^"\n") file (datas: 'a list) =
let oc = open_out file.file_name in
List.iter (fun x -> Printf.fprintf oc "%s" @@ f x) datas;
close_out oc
但是當我嘗試
let () = let f = string_of_int in log_datas ~f {file_name="log"} [1;2]
我收到型別錯誤
23 | let () = let f = string_of_int in log_datas ~f {file_name="log"} [1;2]
^
Error: This expression has type int -> string
but an expression was expected of type string -> string
Type int is not compatible with type string
一個明顯的解決方案是創建 2 個函式,一個沒有f引數,一個有f引數。但我想知道,還有其他可能的解決方法嗎?
uj5u.com熱心網友回復:
不,這是不可能的,您必須指定兩個引數以使其保持多型。基本上,你的例子可以被提煉成,
let log ?(to_string=string_of_int) data =
print_endline (to_string data)
如果 OCaml 將保持多型,則將允許以下內容,
log "hello"
并且string_of_int "hello"型別不正確。
所以你必須保持兩個引數都是必需的,例如,
let log to_string data =
print_endline (to_string data)
我還建議查看Format模塊并定義您自己的多型函式,該函式使用格式規范來定義如何撰寫不同型別的資料,例如,
let log fmt =
Format.kasprintf print_endline fmt
print_endline用我們自己的伐木設施代替。該log函式可以用作printf,例如,
log "%s %d" "hello" 42
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/365097.html
上一篇:帶有數字變數的顏色時間序列
