String OCaml-字符串(程序)

String OCaml-字符串(程序),string,ocaml,scanf,String,Ocaml,Scanf,我想创建一个程序,从标准输入读取由空格分隔的两个整数。所以我想我可以将它们存储为字符串。 然后,我想使用String.get之类的东西来获取第一个和第三个字符(用空格分隔的整数),然后将它们打印为整数 以下是我迄今为止的代码(可能有语法错误): 我发现编译器错误 File "string.ml", line 9, characters 23-26: Error: This expression has type (string -> 'a) -> 'a but an expre

我想创建一个程序,从标准输入读取由空格分隔的两个整数。所以我想我可以将它们存储为字符串。 然后,我想使用String.get之类的东西来获取第一个和第三个字符(用空格分隔的整数),然后将它们打印为整数

以下是我迄今为止的代码(可能有语法错误):

我发现编译器错误

File "string.ml", line 9, characters 23-26:
Error: This expression has type (string -> 'a) -> 'a
   but an expression was expected of type String
所以我想知道我怎样才能做到这一点?有没有更好的方法来做这个项目

扫描“%s”的类型与您的想法不同。OCaml中的
scanf
系列采用的参数是用于处理给定类型输入的函数。因此
scanf“%s”
将函数作为参数。由于没有传递该函数,因此最终将得到复杂的类型
string->'\u a->'\u a

如果希望函数返回的字符串保持不变,可以使用identity函数:

# let id x = x ;;
val id : 'a -> 'a = <fun>

# let mystring = scanf "%s" id ;;
testing
val mystring : string = "testing"
let int_of_char c = Char.code c - Char.code '0'
如果要将单个数字转换为整数,可以使用此函数:

# let id x = x ;;
val id : 'a -> 'a = <fun>

# let mystring = scanf "%s" id ;;
testing
val mystring : string = "testing"
let int_of_char c = Char.code c - Char.code '0'
然而,这不是一个非常健壮的函数

最好首先使用
scanf
进行转换,这实际上是它的主要目的

# let myint = scanf " %d" id ;;
347
val myint : int = 347