1 ! Copyright (C) 2008 William Schlieper
\r
2 ! See http://factorcode.org/license.txt for BSD license.
\r
4 USING: assocs combinators continuations fry kernel macros math
\r
5 namespaces quotations sequences summary ;
\r
11 ERROR: amb-failure ;
\r
13 M: amb-failure summary drop "Backtracking failure" ;
\r
16 failure get [ continue ] [ amb-failure ] if* ;
\r
18 : must-be-true ( ? -- )
\r
21 MACRO: checkpoint ( quot -- quot' )
\r
24 '[ failure set _ continue ] callcc0
\r
29 : number-from ( from -- from+n )
\r
30 [ 1 + number-from ] checkpoint ;
\r
34 : preserve ( quot var -- ) [ get [ call ] dip ] keep set ; inline
\r
36 : amb-preserve ( quot -- ) failure preserve ; inline
\r
38 : unsafe-number-from-to ( to from -- to from+n )
\r
39 2dup = [ [ 1 + unsafe-number-from-to ] checkpoint ] unless ;
\r
41 : number-from-to ( to from -- to from+n )
\r
42 2dup < [ fail ] when unsafe-number-from-to ;
\r
44 : amb-integer ( seq -- int )
\r
45 length 1 - 0 number-from-to nip ;
\r
47 MACRO: unsafe-amb ( seq -- quot )
\r
51 unclip swap '[ _ [ drop _ unsafe-amb ] checkpoint ]
\r
56 : amb-lazy ( seq -- elt )
\r
57 [ amb-integer ] [ nth ] bi ;
\r
59 : amb ( seq -- elt )
\r
60 [ fail f ] [ unsafe-amb ] if-empty ; inline
\r
62 MACRO: amb-execute ( seq -- quot )
\r
63 [ length 1 - ] [ <enum> [ 1quotation ] assoc-map ] bi
\r
64 '[ _ 0 unsafe-number-from-to nip _ case ] ;
\r
66 : if-amb ( true false -- ? )
\r
69 [ '[ @ must-be-true t ] ]
\r
72 ] amb-preserve ; inline
\r
77 : amb-all ( quot -- )
\r
78 [ { t f } amb [ call fail ] [ drop ] if ] amb-preserve ; inline
\r
80 : bag-of ( quot -- seq )
\r
81 V{ } clone [ '[ @ _ push ] amb-all ] keep ; inline
\r