Skip to content

Commit a46ef36

Browse files
Rajneesh Lakkundifacebook-github-bot
Rajneesh Lakkundi
authored andcommitted
Extend abs to Num types
Summary: Extend abs() to support floats by accepting and returning Num types. More details in the task. Reviewed By: JakobDegen Differential Revision: D59392677 fbshipit-source-id: 2b9588cccf1f99079d0c7eab0fefaef5b4d7b7a9
1 parent f9bbeac commit a46ef36

File tree

1 file changed

+11
-4
lines changed

1 file changed

+11
-4
lines changed

starlark/src/stdlib/funcs/other.rs

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ use crate::values::function::SpecialBuiltinFunction;
3434
use crate::values::int::PointerI32;
3535
use crate::values::list::AllocList;
3636
use crate::values::none::NoneType;
37+
use crate::values::num::value::Num;
3738
use crate::values::num::value::NumRef;
3839
use crate::values::range::Range;
3940
use crate::values::string::repr::string_repr;
@@ -43,7 +44,6 @@ use crate::values::tuple::AllocTuple;
4344
use crate::values::tuple::TupleRef;
4445
use crate::values::tuple::UnpackTuple;
4546
use crate::values::types::int_or_big::StarlarkInt;
46-
use crate::values::types::int_or_big::StarlarkIntRef;
4747
use crate::values::typing::never::StarlarkNever;
4848
use crate::values::typing::ty::AbstractType;
4949
use crate::values::typing::StarlarkIter;
@@ -100,11 +100,15 @@ pub(crate) fn register_other(builder: &mut GlobalsBuilder) {
100100
/// abs(0) == 0
101101
/// abs(-10) == 10
102102
/// abs(10) == 10
103+
/// abs(10.0) == 10.0
104+
/// abs(-12.34) == 12.34
103105
/// # "#);
104106
/// ```
105-
fn abs(#[starlark(require = pos)] x: StarlarkIntRef) -> anyhow::Result<StarlarkInt> {
106-
// TODO(nga): does not handle float.
107-
Ok(x.abs())
107+
fn abs(#[starlark(require = pos)] x: NumRef) -> anyhow::Result<Num> {
108+
match x {
109+
NumRef::Int(a) => Ok(Num::Int(a.abs())),
110+
NumRef::Float(a) => Ok(Num::Float(a.0.abs())),
111+
}
108112
}
109113

110114
/// [any](
@@ -890,6 +894,9 @@ mod tests {
890894
assert::eq("2147483648", "abs(-2147483648)");
891895
assert::eq("2147483648000", "abs(2147483648000)");
892896
assert::eq("2147483648000", "abs(-2147483648000)");
897+
assert::eq("1.23", "abs(-1.23)");
898+
assert::eq("2.3", "abs(2.3)");
899+
assert::is_true("isinstance(abs(1), int)");
893900
}
894901

895902
#[test]

0 commit comments

Comments
 (0)