Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
rand works for doubles
  • Loading branch information
erkkikeranen committed May 5, 2020
commit 2c9acbf52a80d82d41ea4f604c4078c798dd2bc8
2 changes: 2 additions & 0 deletions src/environment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ impl Environment {
let subtract_fn = rust_core::SubtractFn {};
let multiply_fn = rust_core::MultiplyFn {};
let divide_fn = rust_core::DivideFn {};
let rand_fn = rust_core::RandFn {};
let str_fn = rust_core::StrFn {};
let do_fn = rust_core::DoFn {};
let nth_fn = rust_core::NthFn {};
Expand Down Expand Up @@ -105,6 +106,7 @@ impl Environment {
environment.insert(Symbol::intern("-"), subtract_fn.to_rc_value());
environment.insert(Symbol::intern("*"), multiply_fn.to_rc_value());
environment.insert(Symbol::intern("_slash_"), divide_fn.to_rc_value());
environment.insert(Symbol::intern("rand"), rand_fn.to_rc_value());
environment.insert(Symbol::intern("let"), let_macro.to_rc_value());
environment.insert(Symbol::intern("str"), str_fn.to_rc_value());
environment.insert(Symbol::intern("quote"), quote_macro.to_rc_value());
Expand Down
4 changes: 4 additions & 0 deletions src/rust_core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ pub use self::_divide_::*;
pub(crate) mod _multiply_;
pub use self::_multiply_::*;

pub(crate) mod rand;
pub use self::rand::*;


// string
pub(crate) mod str;
pub use self::str::*;
Expand Down
35 changes: 35 additions & 0 deletions src/rust_core/rand.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
use crate::ifn::IFn;
use crate::value::{Value, ToValue};
use std::rc::Rc;
use rand::{random, thread_rng, Rng};
use crate::error_message;
use std::any::Any;

/// (rand) or (rand n)
///
#[derive(Debug, Clone)]
pub struct RandFn {}
impl ToValue for RandFn {
fn to_value(&self) -> Value {
Value::IFn(Rc::new(self.clone()))
}
}
impl IFn for RandFn {
fn invoke(&self, args: Vec<Rc<Value>>) -> Value {
match args.len() {
0 => Value::F64(thread_rng().gen()),
1 => {
let arg = args.get(0).unwrap().to_value();
match arg {
Value::I32(i_) => Value::F64(thread_rng().gen_range(0.0, i_ as f64)),
Value::F64(f_) => Value::F64(thread_rng().gen_range(0.0, f_)),
_ => Value::Condition(format!( // TODO: what error message should be returned regarding using typetags?
"Type mismatch; Expecting: (i32 | i64 | f32 | f64), Found: {}",
arg.type_tag()
))
}
},
_ => error_message::wrong_varg_count(&[0, 1], args.len())
}
}
}