Reputation: 4197
I want to convert string representation of real number to real type.
I know that I can do Real.fromString("5.5")
but it doesn't return real type but real option type which I can't multiply or add with any other real.
Upvotes: 1
Views: 3856
Reputation: 122519
To add to Michael J. Barber's answer, the option type is an algebraic datatype which is either SOME something, or NONE.
Usually, in ML we usually deconstruct algebraic datatypes with pattern matching:
case Real.fromString "5.5" of SOME x => x + 1.0
| NONE => 42.0;
You could use getOpt
like Michael J. Barber suggested (you don't actually need the Option.
since getOpt
is in the top-level environment), which is a simplified version of the above.
Or, if you are sure that it is going to be a SOME, you could use valOf
(which will error if it is NONE):
- val x = Real.fromString "5.5";
val x = SOME 5.5 : real option
- valOf x;
val it = 5.5 : real
or you could pattern-match it away in a val
(since val
is also a pattern match, albeit with only one branch):
- val SOME x = Real.fromString "5.5";
> val x = 5.5 : real
Upvotes: 3
Reputation: 25052
Extract the value from the option by pattern matching or using one of the functions in the Option structure. For example:
- val x = Real.fromString("5.5");
> val x = SOME 5.5 : real option
- Option.getOpt(x, 0.0);
> val it = 5.5 : real
Upvotes: 4