Comment detail

printfの自作 (Nested Flatten)

OCaml で、サポートする書式指定は #4409 の jijixi さんのと大体同じですが、ちゃんと型チェックする版。

基本は参考ページの手法を使って、でもそれだけだと printf っぽく見えないので Camlp4 を被せました。

KURO-BOX% ocaml
        Objective Caml version 3.09.2

# #load "camlp4o.cma";;
        Camlp4 Parsing version 3.09.2

# #load "pa_printf.cmo";;
# myprintf "hoge %% %d %s %c %f" 10 "fuga" 'C' 2.1;;
- : string = "hoge % 10 fuga C 2.1"
# myprintf "hoge %% %d %s %c %f" 3.14 "fuga" 'C' 2.1;;
This expression has type float but is here used with type int
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
(* ocamlc -c -I +camlp4 -pp 'camlp4o pa_extend.cmo q_MLast.cmo' pa_printf.ml *)

let make_printf _loc format =
  let parse_format format =
    let rec lit e s = parser
    | [< ''%'; strm >] -> esc <:expr< compose $e$ (lit $str:s$) >>  "" strm
    | [< 'c; strm >] -> lit e (s  ^ String.make 1 c) strm
    | [< >] -> <:expr< compose $e$ (lit $str:s$) >>
    and esc e s = parser
    | [< ''d'; strm >] -> lit <:expr< compose $e$ int >> "" strm
    | [< ''f'; strm >] -> lit <:expr< compose $e$ float >> "" strm
    | [< ''c'; strm >] -> lit <:expr< compose $e$ char >> "" strm
    | [< ''s'; strm >] -> lit <:expr< compose $e$ str >> "" strm
    | [< ''%'; strm >] -> lit <:expr< compose $e$ (lit "%") >> "" strm
    in
    lit <:expr< fun x -> x >> "" (Stream.of_string format)
  in
  let parsed_format = parse_format format in
  <:expr<
    let compose f g x = f (g x) in
    let lit x k s = k (s ^ x) in
    let int k s x = k (s ^ string_of_int x) in
    let str k s x = k (s ^ x) in
    let float k s x = k (s ^ string_of_float x) in
    let char k s x = k (s ^ String.make 1 x) in
    let format p = p (fun s -> s) "" in
    format $parsed_format$
  >>
;;

EXTEND
  Pcaml.expr: LEVEL "expr1" [
    [ "myprintf"; format = STRING -> make_printf _loc format ]
  ];
END

Index

Feed

Other

Link

Pathtraq

loading...