Skip to content

Commit

Permalink
Adding Random to standard libraries (#475)
Browse files Browse the repository at this point in the history
* Adding Random to standard libraries

Adds a new passive class "Random" to the standard libraries.
Each instance of Random encapsulates a seed of its own.
Technically, this may be wasteful -- possibly one seed per
thread might do, but this will facilitate debugging programs
with random numbers.

* Added a global random function with a thread-local seed

* Changed the int hack to an embed type

* Changed int to void type for less confusion

* Change the name of the test to avoid name clashes

* Update Random.enc
  • Loading branch information
TobiasWrigstad authored and Kiko committed Jun 13, 2016
1 parent 4d35688 commit 13b916f
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 0 deletions.
35 changes: 35 additions & 0 deletions bundles/standard/Random.enc
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
embed
body
__thread unsigned seed;
end

-- Random number generator with thread-local seed
def random(max:int) : int
embed int
if (seed == 0)
{
seed = (unsigned) time(NULL);
}
rand_r(&seed) % #{max};
end

-- Simple random number generator encapsulating a seed of its own
passive class Random
seed:embed unsigned int end
-- Trace funcition required because of the embed type of seed
def Random_trace() : void
()
-- Initialisation always with a seed in [0..2^32)
def init(seed:int) : void {
assertFalse(seed < 0) ;
assertFalse(seed > 4294967295) ; -- for want of an Encore 2^32 operator
embed void
_this->_enc__field_seed = (unsigned) #{seed};
end;
}
-- Returns random % max where max [0..2^32)
def random(max:int) : int
embed int
rand_r((unsigned *) &(_this->_enc__field_seed)) % #{max};
end

10 changes: 10 additions & 0 deletions src/tests/encore/stdlib/random_test.enc
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import Random

class Main
def main() : void
let
r = new Random(100)
v1 = r.random(1)
v2 = random(1)
in
print("{}\n{}\n", v1, v2)
2 changes: 2 additions & 0 deletions src/tests/encore/stdlib/random_test.out
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
0
0

0 comments on commit 13b916f

Please sign in to comment.