VM instruction for parsing a Float from a String
Summary
A VM instruction (StringToFloat
) should be added that can be used to convert a String
into a Float
. This instruction can use use String::parse::<f64>()
for Rust. Invalid floats should produce a NaN, since the input is not a number. We can't throw, because ToFloat.to_float
does not (and should not) specify an error type.
Once the instruction is added, it should be use to implement String.to_float
.
Motivation
Converting strings to floats is pretty common, especially when reading numbers from external sources, such as files. Right now Inko provides no means of doing this, and I'd rather not implement this from scratch (at least not for now).
Implementation
We can simply use Rust's String::parse::<f64>()
method for this. The rough implementation would then translate to:
if let Ok(float) = input_string.parse::<f64>() {
float
} else {
f64::NAN
}
String.to_float
can then be implemented like so:
impl ToFloat for String {
def to_float -> Float {
_INKOC.string_to_float(self)
}
}
Drawbacks
Returning a NaN
is a bit different from other languages, but I think it's correct. For example, in Ruby "foo".to_f
returns 0.0. This makes no sense, because "foo"
is not 0.0, it's not even a number. Ruby has Float()
which will raise in case an invalid input value is provided:
Float("foo") # => ArgumentError
This however won't work since ToFloat.to_float
does not include an error signature.