开发者

Secure String.to_int and others

开发者 https://www.devze.com 2023-03-21 05:03 出处:网络
I use String.to_int, and some time开发者_开发知识库 i get errors, for example when the string is not a representation of an int. I would like to catch these errors, or test parameter before to use the

I use String.to_int, and some time开发者_开发知识库 i get errors, for example when the string is not a representation of an int. I would like to catch these errors, or test parameter before to use the function. Some ideas ?

Thanks


Hmm, one could argue that it would have been better if String.to_int from the stdlib returned an optional integer (none indicating an error).

However, in Opa most parsing is done using parsers*. For instance to get the aforementioned function you could write:

string_to_int_opt(s : string) : option(int) =
  Parser.try_parse(Rule.integer, s)

or, if you want to be less verbose the equivalent:

string_to_int_opt = Parser.try_parse(Rule.integer, _)

or if it's part of the more complex parsing you would just use the Rule.integer parser there.

(*) I guess this section of the manual could use some extensions...

0

精彩评论

暂无评论...
验证码 换一张
取 消