From b33a8d20e524ecf57568a3af8e814a7fb3f7dd62 Mon Sep 17 00:00:00 2001 From: Leah Neukirchen Date: Sat, 26 Nov 2022 17:47:30 +0100 Subject: add rand --- mew.scm | 11 ++++++++++- mew.svnwiki | 17 +++++++++++++++++ tests/test.mew | 6 ++++++ 3 files changed, 33 insertions(+), 1 deletion(-) 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 {{}} in the string {{}}, at most {{>} times When the pattern {{}} uses match data, the result is unspecified. +== Random numbers + +Mew initializes the {{(chicken random)}} generator from a high entropy source. + +(rand) + +Returns a random real between 0 and 1. + +(rand N) + +Returns a random integer such that 0 <= {{(rand N)}} < {{N}}. + +(rand N M) + +Returns a random integer such that N <= {{(rand M)}} < {{M}}. + + == Special syntax (-> a -> b c -> d e f) 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))) -- cgit 1.4.1