Skip to content

Commit 67b4984

Browse files
authored
Merge pull request #8 from sebinsaji007/lib-feature
added random library
2 parents 33b9edc + fc29d5a commit 67b4984

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

src/std_library/mod.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ pub mod array;
66
pub mod fs;
77
pub mod string;
88
pub mod math;
9+
pub mod random;
910
/// Function to load a standard library
1011
/// # Arguments
1112
/// * `lib` - The name of the library to load.
@@ -23,6 +24,7 @@ pub fn get_std_lib(lib: String) -> Option<Res> {
2324
"nya:whiskers" => Some(string::add_globals()),
2425
"nya:scratchpad" => Some(fs::add_globals()),
2526
"nya:catculator" => Some(math::add_globals()),
27+
"nya:rundamn" => Some(random::add_globals()),
2628
//"nya:meowternet" => Some(http::add_globals()),
2729
_ => None,
2830
}

src/std_library/random.rs

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
extern crate rand;
2+
use rand::seq::SliceRandom;
3+
use rand::Rng;
4+
5+
6+
pub fn add_globals() -> Res {
7+
let mut globals = HashMap::new();
8+
globals.insert(String::from("new"), Object::Inbuilt(new));
9+
globals.insert(String::from("random"), Object::Inbuilt(random));
10+
globals.insert(String::from("uniform"), Object::Inbuilt(uniform));
11+
globals.insert(String::from("randint"), Object::Inbuilt(randint));
12+
globals.insert(String::from("choice"), Object::Inbuilt(choice));
13+
globals.insert(String::from("shuffle"), Object::Inbuilt(shuffle));
14+
15+
16+
Res {
17+
globals,
18+
raw: None,
19+
}
20+
}
21+
pub struct SimpleRandom {
22+
rng: rand::rngs::ThreadRng,
23+
}
24+
25+
impl SimpleRandom {
26+
pub fn new() -> Self {
27+
SimpleRandom { rng: rand::thread_rng() }
28+
}
29+
30+
pub fn random(&mut self) -> f64 {
31+
self.rng.gen::<f64>()
32+
}
33+
34+
pub fn uniform(&mut self, a: f64, b: f64) -> f64 {
35+
self.rng.gen_range(a..b)
36+
}
37+
38+
pub fn randint(&mut self, a: i64, b: i64) -> i64 {
39+
self.rng.gen_range(a..=b)
40+
}
41+
42+
pub fn choice<T: Clone>(&mut self, seq: &[T]) -> T {
43+
seq.choose(&mut self.rng).unwrap().clone()
44+
}
45+
46+
pub fn shuffle<T>(&mut self, x: &mut Vec<T>) {
47+
x.shuffle(&mut self.rng);
48+
}
49+
}
50+
51+

0 commit comments

Comments
 (0)