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

1

7

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) |}];
Barrelhouse answered 31/12, 2017 at 19:24 Comment(0)
E
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?).

Erotic answered 31/12, 2017 at 19:42 Comment(2)
Note that the _opt variants aren't available with BuckleScipt, since it still uses the 4.02.3 compiler.Tanner
This is what I was looking for. It is weird because BuckleScript has a function to parse floats from a string (Js.Float.fromString), but it doesn't have it to do it with integers.Barrelhouse

© 2022 - 2024 — McMap. All rights reserved.