Skip to main content

rl_lang/interpreter/stdlib/types/
float.rs

1use crate::interpreter::{
2    evaluator::Evaluator,
3    stdlib::common::{verr, vf, vok, vs},
4    values::Value,
5};
6
7pub fn std_is_float(_: &mut Evaluator, value: Value) -> bool {
8    matches!(value, Value::Float(_))
9}
10
11pub fn std_to_float(_: &mut Evaluator, value: Value) -> Value {
12    let result = match value {
13        Value::Float(f) => f,
14        Value::Integer(i) => i as f64,
15        Value::Byte(i) => i as f64,
16        Value::Bool(b) => {
17            if b {
18                1.0
19            } else {
20                0.0
21            }
22        }
23        Value::String(s) => match s.trim().parse::<f64>() {
24            Ok(f) => f,
25            Err(_) => return verr!(vs!(format!("cannot parse \"{}\" as float", s))),
26        },
27
28        other => {
29            return verr!(vs!(format!(
30                "cannot parse \"{}\" as float",
31                other.type_name()
32            )));
33        }
34    };
35
36    vok!(vf!(result))
37}