如何将字符串转换为ocaml中的整数列表? [英] How to convert a string to integer list in ocaml?

查看:305
本文介绍了如何将字符串转换为ocaml中的整数列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在ocaml中传递两个列表作为命令行参数。
我使用下面的代码在程序中访问它。

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

我需要将list1和list2作为整数列表。
我得到错误

lockquote

这个表达式有类型字符串,但是表达式类型为
int list


同时处理。
如何将该参数转换为整数列表。
参数以这种格式传递[1; 2; 3; 4] [1; 5; 6; 7]

解决方案

Sys.argv。(n)将始终是一个字符串。您需要将字符串解析为整数列表。您可以尝试如下所示:

  $ ocaml 
OCaml版本4.01.0

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

当然,这并不检查输入是否正确。它只是通过蛮力拉出数字序列。为了做得更好,你需要做一些真正的词法分析和简单的解析。

(也许这是显而易见的,但你也可以在顶层测试你的函数(OCaml读-eval-print loop)。顶层将根据你输入的内容来处理列表的工作。)


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

I need to have the list1 and list2 as list of integers. I am getting the error

This expression has type string but an expression was expected of type int list

while processing. How can I convert that arguments to a list of integers. The arguments are passed in this format [1;2;3;4] [1;5;6;7]

解决方案

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

这篇关于如何将字符串转换为ocaml中的整数列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆