I'm learning Reasonml, and I can't find any function in the standard library to do so, neither of the Bucklescript Js modules. Is there any better option than using raw javascript?
Right now I'm achieving it with this function:
let parseint: string => int = [%raw {| x => parseInt(x, 10) |}];
int_of_string
(and also float_of_string
/ bool_of_string
) should do what you need.
It's in the standard lib, you should be able to search for it https://caml.inria.fr/pub/docs/manual-ocaml/libref/Pervasives.html (that site will work better for you if you have the reason-tools browser extension installed so it auto-converts from OCaml to Reason syntax for you)
Note that all of those functions will throw an exception if the string isn't valid for that type (read the link to see how each works and what each expects for the string).
As @glennsl points out, when Bucklescript catches up with a more recent version of the OCaml compiler than 4.02.3
, you may want to use the safer _opt
variants, e.g. int_of_string_opt
that returns a Some(number)
or None
instead, depending on how much you trust the input, how much you want to avoid exceptions, and how you want to deal with bad input (is it exceptional and should kill the program/stack, or is it normal and should be handled locally?).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With