How to convert a string to integer list in ocaml?

前端 未结 2 1021
醉酒成梦
醉酒成梦 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 19:51

    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.)

提交回复
热议问题