File tree Expand file tree Collapse file tree 3 files changed +41
-0
lines changed Expand file tree Collapse file tree 3 files changed +41
-0
lines changed Original file line number Diff line number Diff line change @@ -74,6 +74,7 @@ impl Environment {
74
74
let subtract_fn = rust_core:: SubtractFn { } ;
75
75
let multiply_fn = rust_core:: MultiplyFn { } ;
76
76
let divide_fn = rust_core:: DivideFn { } ;
77
+ let rand_fn = rust_core:: RandFn { } ;
77
78
let str_fn = rust_core:: StrFn { } ;
78
79
let do_fn = rust_core:: DoFn { } ;
79
80
let nth_fn = rust_core:: NthFn { } ;
@@ -105,6 +106,7 @@ impl Environment {
105
106
environment. insert ( Symbol :: intern ( "-" ) , subtract_fn. to_rc_value ( ) ) ;
106
107
environment. insert ( Symbol :: intern ( "*" ) , multiply_fn. to_rc_value ( ) ) ;
107
108
environment. insert ( Symbol :: intern ( "_slash_" ) , divide_fn. to_rc_value ( ) ) ;
109
+ environment. insert ( Symbol :: intern ( "rand" ) , rand_fn. to_rc_value ( ) ) ;
108
110
environment. insert ( Symbol :: intern ( "let" ) , let_macro. to_rc_value ( ) ) ;
109
111
environment. insert ( Symbol :: intern ( "str" ) , str_fn. to_rc_value ( ) ) ;
110
112
environment. insert ( Symbol :: intern ( "quote" ) , quote_macro. to_rc_value ( ) ) ;
Original file line number Diff line number Diff line change @@ -22,6 +22,10 @@ pub use self::_divide_::*;
22
22
pub ( crate ) mod _multiply_;
23
23
pub use self :: _multiply_:: * ;
24
24
25
+ pub ( crate ) mod rand;
26
+ pub use self :: rand:: * ;
27
+
28
+
25
29
// string
26
30
pub ( crate ) mod str;
27
31
pub use self :: str:: * ;
Original file line number Diff line number Diff line change
1
+ use crate :: ifn:: IFn ;
2
+ use crate :: value:: { Value , ToValue } ;
3
+ use std:: rc:: Rc ;
4
+ use rand:: { random, thread_rng, Rng } ;
5
+ use crate :: error_message;
6
+ use std:: any:: Any ;
7
+
8
+ /// (rand) or (rand n)
9
+ ///
10
+ #[ derive( Debug , Clone ) ]
11
+ pub struct RandFn { }
12
+ impl ToValue for RandFn {
13
+ fn to_value ( & self ) -> Value {
14
+ Value :: IFn ( Rc :: new ( self . clone ( ) ) )
15
+ }
16
+ }
17
+ impl IFn for RandFn {
18
+ fn invoke ( & self , args : Vec < Rc < Value > > ) -> Value {
19
+ match args. len ( ) {
20
+ 0 => Value :: F64 ( thread_rng ( ) . gen ( ) ) ,
21
+ 1 => {
22
+ let arg = args. get ( 0 ) . unwrap ( ) . to_value ( ) ;
23
+ match arg {
24
+ Value :: I32 ( i_) => Value :: F64 ( thread_rng ( ) . gen_range ( 0.0 , i_ as f64 ) ) ,
25
+ Value :: F64 ( f_) => Value :: F64 ( thread_rng ( ) . gen_range ( 0.0 , f_) ) ,
26
+ _ => Value :: Condition ( format ! ( // TODO: what error message should be returned regarding using typetags?
27
+ "Type mismatch; Expecting: (i32 | i64 | f32 | f64), Found: {}" ,
28
+ arg. type_tag( )
29
+ ) )
30
+ }
31
+ } ,
32
+ _ => error_message:: wrong_varg_count ( & [ 0 , 1 ] , args. len ( ) )
33
+ }
34
+ }
35
+ }
You can’t perform that action at this time.
0 commit comments