]> gitweb.factorcode.org Git - factor.git/blob - basis/combinators/random/random.factor
Merge remote-tracking branch 'Blei/gtk-image-loader'
[factor.git] / basis / combinators / random / random.factor
1 ! Copyright (C) 2010 Jon Harper.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: arrays assocs combinators combinators.short-circuit
4 kernel macros math math.order quotations random sequences
5 summary ;
6 IN: combinators.random
7
8 : ifp ( p true false -- ) [ 0 1 uniform-random-float > ] 2dip if ; inline
9 : whenp ( p true -- ) [ ] ifp ; inline
10 : unlessp ( p false -- ) [ [ ] ] dip ifp ; inline
11
12 <PRIVATE
13
14 : with-drop ( quot -- quot' ) [ drop ] prepend ; inline
15
16 : prepare-pair ( pair -- pair' )
17     first2 [ [ [ - ] [ < ] 2bi ] curry ] [ with-drop ] bi* 2array ;
18
19 ERROR: bad-probabilities assoc ;
20
21 M: bad-probabilities summary
22     drop "The probabilities do not satisfy the rules stated in the docs." ;
23     
24 : good-probabilities? ( assoc -- ? )
25     dup last pair? [
26         keys { [ sum 1 number= ] [ [ 0 1 between? ] all? ] } 1&&
27     ] [
28         but-last keys { [ sum 0 1 between? ] [ [ 0 1 between? ] all? ] } 1&&
29     ] if ;
30
31 ! Useful for unit-tests (no random part)
32 : (casep>quot) ( assoc -- quot )
33     dup good-probabilities? [
34         [ dup pair? [ prepare-pair ] [ with-drop ] if ] map
35         cond>quot
36     ] [ bad-probabilities ] if ;
37     
38 MACRO: (casep) ( assoc -- ) (casep>quot) ;
39
40 : casep>quot ( assoc -- quot )
41     (casep>quot) [ 0 1 uniform-random-float ] prepend ;
42     
43 : (conditional-probabilities) ( seq i -- p )
44     [ dup 0 > [ head [ 1 swap - ] [ * ] map-reduce ] [ 2drop 1 ] if ] [ swap nth ] 2bi * ;
45     
46 : conditional-probabilities ( seq -- seq' )
47     dup length iota [ (conditional-probabilities) ] with map ;
48     
49 : (direct>conditional) ( assoc -- assoc' )
50         [ keys conditional-probabilities ] [ values ] bi zip ;
51         
52 : direct>conditional ( assoc -- assoc' )
53     dup last pair? [ (direct>conditional) ] [
54         unclip-last [ (direct>conditional) ] [ suffix ] bi*
55     ] if ;
56
57 : call-random>casep ( seq -- assoc )
58     [ length recip ] keep [ 2array ] with map ;
59     
60 PRIVATE>
61
62 MACRO: casep ( assoc -- ) casep>quot ;
63
64 MACRO: casep* ( assoc -- ) direct>conditional casep>quot ;
65
66 MACRO: call-random ( seq -- ) call-random>casep casep>quot ;
67
68 MACRO: execute-random ( seq -- )
69     [ 1quotation ] map call-random>casep casep>quot ;