! Copyright (C) 2021 Doug Coleman.
! See http://factorcode.org/license.txt for BSD license.
USING: accessors arrays constructors growable kernel math
-sequences vectors ;
+multiline sequences vectors ;
IN: cursors2
TUPLE: cursor ;
TUPLE: sequence-output-cursor < cursor seq n ;
CONSTRUCTOR: <sequence-output-cursor> sequence-output-cursor ( seq n -- obj ) ;
-TUPLE: mapping-cursor < cursor input output ;
-CONSTRUCTOR: <mapping-cursor> mapping-cursor ( input output -- obj ) ;
+TUPLE: mapping-cursor < cursor output input ;
+CONSTRUCTOR: <mapping-cursor> mapping-cursor ( output input -- obj ) ;
TUPLE: alist-cusor < cursor alist n ;
: input>mapping-cursor ( input-cursor -- mapping-cursor )
- >input-cursor dup input>output-cursor <mapping-cursor> ;
+ >input-cursor [ input>output-cursor ] keep <mapping-cursor> ;
: (find2) ( cursor quot: ( cursor obj -- ? ) -- cursor/f elt/f ? )
[ >input-cursor ] dip (find2) ; inline
+
+: each-cursor-advance ( cursor elt quot: ( cursor elt -- ) -- )
+ [ call ] 3keep nip
+ [ cursor-inc-input ] dip ; inline
+
+: mapping-cursor-advance ( cursor elt quot: ( cursor elt -- out ) -- mapping-cursor' quot )
+ [ call ] 3keep nip
+ [
+ [ output>> cursor-put ] [ input>> cursor-inc-input ] bi <mapping-cursor>
+ ] dip ; inline
+
+: filter-cursor-advance ( cursor elt quot: ( cursor elt -- ? ) -- mapping-cursor' quot )
+ [ call ] 3keep
+ [
+ swapd
+ '[ _ [ _ swap output>> cursor-put ] [ output>> ] if ]
+ [ input>> cursor-inc-input ] bi <mapping-cursor>
+ ] dip ; inline
+
: (each2) ( cursor quot: ( cursor obj -- ) -- )
over cursor-at [
- [ swap call ] 3keep drop
- [ cursor-inc-input ] dip (each2)
+ swap each-cursor-advance (each2)
] [
3drop
] if ; inline recursive
: (map2) ( cursor quot: ( cursor obj -- obj' ) -- out )
over input>> cursor-at [
- [ swap call ] 3keep drop
- [ [ cursor-put ] change-output [ cursor-inc-input ] change-input ] dip (map2)
+ swap mapping-cursor-advance (map2)
] [
2drop output>>
] if ; inline recursive
: map2 ( obj quot -- obj' )
[ input>mapping-cursor ] dip (map2) ; inline
+
+
+: (filter2) ( cursor quot: ( cursor obj -- obj' ) -- out )
+ over input>> cursor-at [
+ swap filter-cursor-advance (filter2)
+ ] [
+ 2drop output>>
+ ] if ; inline recursive
+
+: filter2 ( obj quot -- obj' )
+ [ input>mapping-cursor ] dip (filter2) ; inline