How to convert a string to integer list in ocaml?

前端 未结 2 1027
醉酒成梦
醉酒成梦 2021-01-25 19:16

I need to pass two list as command line arguments in ocaml. I used the following code to access it in the program.

let list1=Sys.argv.(1);;
let list2=Sys.argv.(2         


        
2条回答
  •  春和景丽
    2021-01-25 20:02

    As Sys.argv is a string array, you need to write your own transcription function.

    I guess the simplest way to do this is to use the Genlex module provided by the standard library.

    let lexer = Genlex.make_lexer ["["; ";"; "]"; ]
    let list_of_string s =
      let open Genlex in
      let open Stream in
      let stream = lexer (of_string s) in
      let fail () = failwith "Malformed string" in
      let rec aux acc =
        match next stream with
        | Int i ->
          ( match next stream with
            | Kwd ";" -> aux (i::acc)
            | Kwd "]" -> i::acc
            | _ -> fail () )
        | Kwd "]" -> acc
        | _ -> fail ()
      in
      try
        match next stream with
        | Kwd "[" -> List.rev (aux [])
        | _ -> fail ()
      with Stream.Failure -> fail ()
    
    let list1 = list_of_string Sys.argv.(1)
    let list2 = list_of_string Sys.argv.(2)
    

    Depending on the OCaml flavor you want to use, some other library may look more interesting. If you like yacc, Menhir may solve your problem in a few lines of code.

提交回复
热议问题