I am trying to extract integer value from a string using Int.fromString
function
but as we know, its specification is : String -> int option
. So the result of applying Int.fromString
is of type int option
. But I need the result of type int
. Also I am sure that the extracted part is integer. How can this be done?
Another way to convert string to integer is by using static Convert class. The Convert class includes different methods which convert base data type to another base data type. The Convert class includes the following methods to convert from different data types to int type. Convert.ToInt16 ()
It is important that you do so in a way that does not throw potential exceptions. You can use a couple built in methods, as shown below, to convert a string to int. Both of these would throw an exception if the string value is not a valid integer.
The function Int.fromString : string -> int option is safe, but if you don't like it, you could do: although it should be just as natural to handle NONE in the calling function, or in a specialized bind operator ( >>= ).
The Convert class includes the following methods to convert from different data types to int type. The Convert.ToInt16 () method returns the 16-bit integer e.g. short, the Convert.ToInt32 () returns 32-bit integers e.g. int and the Convert.ToInt64 () returns the 64-bit integer e.g. long.
You are free to use SOME
in the left part of expression:
val SOME x = Int.fromString "3";
val x = 3 : int
You can use the valOf
function to get the SOME value of an option:
val i : int = valOf (Int.fromString "1")
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