Skip to content

Commit

Permalink
Add functionality to BigInts which ensures a Double is returned when …
Browse files Browse the repository at this point in the history
…a sqrt of a BigInt is attempted and the answer is not a BigInt.
  • Loading branch information
ummarikar committed Oct 31, 2019
1 parent ec7df35 commit 5debb2a
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 5 deletions.
18 changes: 18 additions & 0 deletions lang_tests/int29.som
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
"
VM:
status: success
stdout:
Integer
Integer
Double
Double
"

int29 = (
run = (
(4 sqrt class) println.
((1 << 200) sqrt class) println.
(3 sqrt class) println.
((1 << 103) sqrt class) println.
)
)
22 changes: 17 additions & 5 deletions src/lib/vm/objects/integers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@
use std::convert::TryFrom;

use abgc_derive::GcLayout;
use num_bigint::BigInt;
use num_traits::{FromPrimitive, ToPrimitive, Zero};
use num_bigint::{BigInt, ToBigInt};
use num_traits::{FromPrimitive, ToPrimitive};

use crate::vm::{
core::{VMError, VM},
Expand Down Expand Up @@ -156,10 +156,22 @@ impl Obj for ArbInt {
}

fn sqrt(&self, vm: &VM) -> Result<Val, Box<VMError>> {
if self.val < Zero::zero() {
Err(Box::new(VMError::DomainError))
if let Some(result) = self.val.to_f64() {
if result < 0.0 {
Err(Box::new(VMError::DomainError))
} else {
let root = result.sqrt();
if root.round() == root {
match root.to_bigint() {
Some(i) => ArbInt::new(vm, i),
None => Err(Box::new(VMError::DomainError)),
}
} else {
Ok(Double::new(vm, root))
}
}
} else {
ArbInt::new(vm, self.val.sqrt())
Err(Box::new(VMError::CantRepresentAsDouble))
}
}

Expand Down

0 comments on commit 5debb2a

Please sign in to comment.