All of these start from a simple idea: How to write python-style formatted string in ocaml.
pythoners could init a string as:
str = "this var: %s" % this_var
str2 = "this: %s; that: %s" % (this_var, that_var)
but ocaml's formatted string code as :
let str = Printf.sprintf "this var: %s" this_var
let str2 = Printf.sprintf "this: %s; that: %s" this_var that_var
I believed I can do sth to make the ocaml string formating code python-like At first, I defined a function as below:
let (%) s x = Printf.sprintf s x
then, I can write directly as:
let str = "this: %s" % "sth"
but the simple function cannot handle more complex situations as two or more variables. so I wanted to write a little complex function to make it perfectly simulate the python way. I wrote it as below :
let (%) s li =
let split_list = Str.full_split (regexp "%[a-z]") s in
let rec fmt result_str s_list x_list = match s_list with
| [] -> result_str
| shd::stl -> match shd with
| Text t -> fmt (result_str^t) stl x_list
| Delim d -> match x_list with
| [] -> fmt result_str stl []
| xhd::xtl -> fmt (result_str^(Printf.sprintf d xhd)) stl xtl
in
fmt "" split_list li
But the function just CANNOT work, because the type error and also ocaml's list cannot contains multiple types.
if you write sth like: "name: %s; age: %d" % ["John"; 20]
the ocaml compiler world laugh at the code and tell you some type ERROR.
Obviously, I must use Tuple to replace List. but I just do NOT konw how to tail-recursive a variable-length tuple.
any suggestion is welcomed. I have two question indeed.
- how to write a pythonic ocaml code to format string.
If Ocaml cannot dynamically generate some string as format6 str and pass it to sprintf? for code:
let s = "%s" in Printf.sprintf s "hello"
would generate ERROR info as:
Error: This expression has type string but an expression was expected of type ('a -> 'b, unit, string) format = ('a -> 'b, unit, string, string, string, string) format6