summary refs log tree commit diff
diff options
context:
space:
mode:
-rw-r--r--mew.scm11
-rw-r--r--mew.svnwiki17
-rw-r--r--tests/test.mew6
3 files changed, 33 insertions, 1 deletions
diff --git a/mew.scm b/mew.scm
index db53e87..1c1674c 100644
--- a/mew.scm
+++ b/mew.scm
@@ -16,7 +16,7 @@
      negate
      odometer one-of op op*
      per prn proj puts
-     range rep
+     rand range rep
      scan scan-right sing? search seq set set-at str slurp
      tally-accumulator tbl time
      while
@@ -41,6 +41,7 @@
           (chicken condition)
           (chicken module)
           (chicken port)
+          (chicken random)
           (chicken repl)
           (chicken syntax)
           srfi-17
@@ -394,6 +395,12 @@
   (define (void? x)
     (eq? x (void)))
 
+  (define rand
+    (case-lambda
+      (()    (pseudo-random-real))
+      ((n)   (pseudo-random-integer n))
+      ((n m) (+ n (pseudo-random-integer (- m n))))))
+
   (define range
     (case-lambda
       (()               (make-range-generator 0 +inf.0 1))
@@ -1023,4 +1030,6 @@
                      (str (substring old-prompt 0 2)
                           "^_^;"
                           (substring old-prompt 2))))))
+
+  (set-pseudo-random-seed! (random-bytes))
 )
diff --git a/mew.svnwiki b/mew.svnwiki
index 09c6d86..5c955ed 100644
--- a/mew.svnwiki
+++ b/mew.svnwiki
@@ -507,6 +507,23 @@ irregex {{<irx>}} in the string {{<str>}}, at most {{<max>>} times
 When the pattern {{<irx>}} uses match data, the result is unspecified.
 
 
+== Random numbers
+
+Mew initializes the {{(chicken random)}} generator from a high entropy source.
+
+<procedure>(rand)<procedure>
+
+Returns a random real between 0 and 1.
+
+<procedure>(rand N)<procedure>
+
+Returns a random integer such that 0 <= {{(rand N)}} < {{N}}.
+
+<procedure>(rand N M)<procedure>
+
+Returns a random integer such that N <= {{(rand M)}} < {{M}}.
+
+
 == Special syntax
 
 <syntax>(-> a -> b c -> d e f)</syntax>
diff --git a/tests/test.mew b/tests/test.mew
index 904059d..d0b5685 100644
--- a/tests/test.mew
+++ b/tests/test.mew
@@ -24,6 +24,12 @@
   (test '(11 22 33) (sort (vals (tbl 1 11 2 22 3 33)) <))
   (test-error (vals #(1 2 3))))
 
+(test-group "rand"
+  (test #f (integer? (rand)))
+  (test #t (integer? (rand 6)))
+  (test #t (<= 2 (rand 2 6)))
+  (test #t (< (rand 2 6) 6)))
+
 (test-group "range"
   (test '(1 2 3) (into '() (range 1 4)))
   (test '() (into '() (range 4 1)))