Skip to content

Commit

Permalink
#83 - add floor, round and ceil functions
Browse files Browse the repository at this point in the history
  • Loading branch information
danilopedraza committed Jan 10, 2025
1 parent 07959cb commit 9c58bbd
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 1 deletion.
14 changes: 14 additions & 0 deletions core/src/object/float.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,20 @@ impl Float {
}
}

pub fn ceil(&self) -> Result<Integer, ObjectError> {
match self.val.to_integer_round(rug::float::Round::Up) {
Some(int) => Ok(int.0.into()),
None => Err(ObjectError::CastInfinityToInt),
}
}

pub fn round(&self) -> Result<Integer, ObjectError> {
match self.val.to_integer_round(rug::float::Round::Nearest) {
Some(int) => Ok(int.0.into()),
None => Err(ObjectError::CastInfinityToInt),
}
}

wrapper_fn!(sin);
wrapper_fn!(cos);
wrapper_fn!(tan);
Expand Down
10 changes: 9 additions & 1 deletion core/src/object/fraction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,15 @@ impl Fraction {
}

pub fn floor(&self) -> Integer {
(self.val.numer() / self.val.denom()).complete().into()
self.val.clone().floor().numer().to_owned().into()
}

pub fn ceil(&self) -> Integer {
self.val.clone().ceil().numer().to_owned().into()
}

pub fn round(&self) -> Integer {
self.val.clone().round().numer().to_owned().into()
}
}

Expand Down
30 changes: 30 additions & 0 deletions core/src/std/math.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,29 @@ macro_rules! float_fn {
};
}

macro_rules! round_fn {
($name:ident) => {
fn $name(args: &[Object]) -> Object {
match &args[0] {
Object::Integer(int) => Object::Integer(int.to_owned()),
Object::Float(f) => match f.$name() {
Ok(int) => Object::Integer(int),
Err(err) => err.into(),
},
Object::Fraction(f) => Object::Integer(f.$name()),
obj => Object::Error(ObjectError::UnexpectedType(
vec![
String::from("Float"),
String::from("Integer"),
String::from("Fraction"),
],
obj.kind(),
)),
}
}
};
}

float_fn!(sin);
float_fn!(cos);
float_fn!(tan);
Expand All @@ -63,6 +86,10 @@ float_fn!(ln);
float_fn!(sqrt);
float_fn!(cbrt);

round_fn!(round);
round_fn!(floor);
round_fn!(ceil);

pub fn komodo_math(ctx: ExecContext) -> Environment {
env_with(
vec![
Expand All @@ -79,6 +106,9 @@ pub fn komodo_math(ctx: ExecContext) -> Environment {
("sqrt", Object::from_fn(sqrt, 1)),
("abs", Object::from_fn(abs, 1)),
("hypot", Object::from_fn(hypot, 2)),
("round", Object::from_fn(round, 1)),
("floor", Object::from_fn(floor, 1)),
("ceil", Object::from_fn(ceil, 1)),
],
ctx,
)
Expand Down

0 comments on commit 9c58bbd

Please sign in to comment.