]> gitweb.factorcode.org Git - factor.git/blobdiff - extra/sequences/extras/extras.factor
sequences.extras: Add {2,3}nested-each/map combinators
[factor.git] / extra / sequences / extras / extras.factor
index 1cc541f163e751507503760c400199994c707f18..24561f91460863cbd2daa829e5fb54385b1e0588 100644 (file)
@@ -282,6 +282,9 @@ PRIVATE>
 : map-from ( ... seq quot: ( ... elt -- ... newelt ) i -- ... newseq )
     pick map-from-as ; inline
 
+: map-if ( ... seq if-quot: ( ... elt -- ... ? ) map-quot: ( ... elt -- ... newelt ) -- ... newseq )
+    '[ dup @ _ when ] map ; inline
+
 <PRIVATE
 
 : push-map-if ( ..a elt filter-quot: ( ..a elt -- ..b ? ) map-quot: ( ..a elt -- ..b newelt ) accum -- ..b )
@@ -376,6 +379,12 @@ PRIVATE>
 : >string-list ( seq -- seq' )
     [ "\"" 1surround ] map "," join ;
 
+: with-string-lines ( str quot -- str' )
+    [ string-lines ] dip map "\n" join ; inline
+
+: prepend-lines-with-spaces ( str -- str' )
+    [ "    " prepend ] with-string-lines ;
+
 : one? ( ... seq quot: ( ... elt -- ... ? ) -- ... ? )
     [ find ] 2keep rot [
         [ 1 + ] 2dip find-from drop not
@@ -634,10 +643,10 @@ PRIVATE>
     ] if-empty ;
 
 : change-last ( seq quot -- )
-    [ drop length 1 - ] [ change-nth ] 2bi ; inline
+    [ index-of-last ] [ change-nth ] bi* ; inline
 
 : change-last-unsafe ( seq quot -- )
-    [ drop length 1 - ] [ change-nth-unsafe ] 2bi ; inline
+    [ index-of-last ] [ change-nth-unsafe ] bi* ; inline
 
 : replicate-into ( ... seq quot: ( ... -- ... newelt ) -- ... )
     over [ length ] 2dip '[ _ dip _ set-nth-unsafe ] each-integer ; inline
@@ -765,3 +774,29 @@ M: step-slice length
     zero? [ 1 + ] unless ; inline
 
 INSTANCE: step-slice virtual-sequence
+
+: 2nested-each ( seq1 seq2 quot -- )
+    swapd '[
+        swap _ with each
+    ] with each ; inline
+
+: 3nested-each ( seq1 seq2 seq3 quot -- )
+    [ spin ] dip '[
+        -rot [
+            swap _ with with each
+        ] with with each
+    ] with with each ; inline
+
+: 2nested-map ( seq1 seq2 quot -- seq )
+    2over [ length ] bi@ * reach
+    [
+        new-resizable
+        [ [ push ] curry compose 2nested-each ] keep
+    ] keep like ; inline
+
+: 3nested-map ( seq1 seq2 seq3 quot -- seq )
+    3 nover [ length ] tri@ * * 5 npick
+    [
+        new-resizable
+        [ [ push ] curry compose 3nested-each ] keep
+    ] keep like ; inline