How to convert a string to integer list in ocaml?

我与影子孤独终老i 提交于 2019-12-02 04:32:49

Sys.argv.(n) will always be a string. You need to parse the string into a list of integers. You could try something like this:

$ ocaml
        OCaml version 4.01.0

# #load "str.cma";;
# List.map int_of_string (Str.split (Str.regexp "[^0-9]+") "[1;5;6;7]");;
- : int list = [1; 5; 6; 7]

Of course this doesn't check the input for correct form. It just pulls out sequences of digits by brute force. To do better you need to do some real lexical analysis and simple parsing.

(Maybe this is obvious, but you could also test your function in the toplevel (the OCaml read-eval-print loop). The toplevel will handle the work of making a list from what you type in.)

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!