Ocaml 将字符串转换为元组列表

作者:Podluzhnyi

我有带有文本的文件“example.dat” "[(1,2); (3,4); (5,6)]"我需要从中获取元组列表。我知道,如何从整数列表中获取它。

# let f line = List.map int_of_string line;;
# open Printf
      let file = "example.dat"  
      let () =
      let ic = open_in file in
        try 
          let line = input_line ic in        
  f line;
  flush stdout;
        close_in ic
        with e ->
        close_in_noerr ic;
        raise e;;

我必须如何更改我的功能?

作者:Podluzhnyi
    let open Genlex in
    let open Stream in
    let lexer = make_lexer ["["; "("; ","; ")"; ";"; "]";] in
    let stream = lexer (of_string array_string) in
    let fail () = failwith "Malformed string" in
    let parse_tuple acc = match next stream with
        | Int first -> ( match next stream with
            | Kwd "," -> ( match next stream with
                | Int second -> ( match next stream with
                    | Kwd ")" -> (first, second) :: acc
                    | _ -> fail () )
                | _ -> fail () )
            | _ -> fail () )
        | _ -> fail ()
    in
    let rec parse_array acc =
        match next stream with
        | Kwd "(" -> parse_array (parse_tuple acc)
        | Kwd ";" -> parse_array acc
        | Kwd "]" -> acc
        | _ -> fail ()
    in
    try
        match next stream with
            | Kwd "[" -> List.rev (parse_array [])
            | _ -> fail ()
    with Stream.Failure -> fail ();;

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章