]> gitweb.factorcode.org Git - factor.git/commitdiff
combinators.smart: adding smart-loop.
authorJohn Benediktsson <mrjbq7@gmail.com>
Sun, 4 Apr 2021 04:00:41 +0000 (21:00 -0700)
committerJohn Benediktsson <mrjbq7@gmail.com>
Sun, 4 Apr 2021 04:00:41 +0000 (21:00 -0700)
basis/combinators/smart/smart-docs.factor
basis/combinators/smart/smart-tests.factor
basis/combinators/smart/smart.factor

index cee3add9adb9681028e8a546ce4a0e3e52f37fe2..43d4bf1d3bbd548348308f15a75c81239c608460 100644 (file)
@@ -247,6 +247,10 @@ HELP: smart-2map-reduce
 { $values { "2map-reduce-quots" sequence } }
 { $description "A version of " { $link 2map-reduce } " that takes a sequence of " { $snippet "{ 2map-quot 2reduce-quot }" } " pairs, returning the " { $link 2map-reduce } " result for each pair." } ;
 
+HELP: smart-loop
+{ $values { "quot" { $quotation ( ..a -- ..b ? ) } } }
+{ $description "A version of " { $link loop } " that runs until the " { $snippet "quot" } " returns " { $link f } " and leaves the result of the quotation on the stack." } ;
+
 ARTICLE: "combinators.smart" "Smart combinators"
 "A " { $emphasis "smart combinator" } " is a macro which reflects on the stack effect of an input quotation. The " { $vocab-link "combinators.smart" } " vocabulary implements a few simple smart combinators which look at the static stack effects of input quotations and generate code which produces or consumes the relevant number of stack values." $nl
 "Take all input values from a sequence:"
index d3f8bfee25cb4258ccbc5c36e1195d9b677d74e1..59e778dd6edac03e48f41b5da5ef26ded9c1daf8 100644 (file)
@@ -1,7 +1,7 @@
 ! Copyright (C) 2009 Doug Coleman.
 ! See http://factorcode.org/license.txt for BSD license.
 USING: accessors arrays assocs combinators.smart kernel locals
-math sequences stack-checker tools.test ;
+math random sequences stack-checker tools.test ;
 IN: combinators.smart.tests
 
 : test-bi ( -- 9 11 )
@@ -127,3 +127,6 @@ IN: combinators.smart.tests
 { { 1 2 3 4 } 5 6 } [ [ 1 2 3 4 5 6 ] 2 output>array-n ] unit-test
 { { } 5 6 } [ [ 5 6 ] 2 output>array-n ] unit-test
 { { 1 2 } 3 4 5 6 } [ [ 1 2 3 4 5 6 ] 4 output>array-n ] unit-test
+
+{ t } [ [ 10 random dup even? ] smart-loop odd? ] unit-test
+{ t } [ 10 [ random dup even? ] smart-loop odd? ] unit-test
index 60dfd714ecbca20ff6769cd367c40ac314500396..cce860858f1892872db4cb3af8abae8db5aea150 100644 (file)
@@ -161,3 +161,9 @@ MACRO: smart-2map-reduce ( 2map-reduce-quots -- quot )
         [ @ _ [ cleave-curry ] [ cleave-curry ] bi _ spread* ]
         1 2each-from
     ] ;
+
+:: smart-loop ( ..a quot: ( ..a -- ..b ? ) -- ..b )
+    quot inputs/outputs :> ( #inputs #outputs )
+    [ quot preserving dup ]
+    [ #outputs ndrop ] while
+    [ #inputs ndrop ] #outputs ndip drop ; inline