Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I parse a string to an integer with Reasonml/Bucklescript?

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) |}];
like image 621
gabrielperales Avatar asked Dec 31 '17 19:12

gabrielperales


1 Answers

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

like image 144
sgrove Avatar answered Oct 14 '22 08:10

sgrove