factor/library/collections/lists.factor

92 lines
2.2 KiB
Factor
Raw Normal View History

! Copyright (C) 2003, 2005 Slava Pestov.
! See http://factor.sf.net/license.txt for BSD license.
2005-04-03 16:55:56 -04:00
IN: lists USING: errors generic kernel math sequences ;
2005-04-02 02:39:33 -05:00
M: f car ;
M: f cdr ;
UNION: general-list POSTPONE: f cons ;
GENERIC: >list ( seq -- list )
M: general-list >list ( list -- list ) ;
2005-04-03 16:55:56 -04:00
PREDICATE: general-list list ( list -- ? )
#! Proper list test. A proper list is either f, or a cons
#! cell whose cdr is a proper list.
[ cdr list? ] [ t ] if* ;
: uncons ( [[ car cdr ]] -- car cdr ) dup car swap cdr ; inline
: unswons ( [[ car cdr ]] -- cdr car ) dup cdr swap car ; inline
2005-09-08 22:23:54 -04:00
: swons ( cdr car -- [[ car cdr ]] ) swap cons ; inline
: unit ( a -- [ a ] ) f cons ; inline
: 2car ( cons cons -- car car ) [ car ] 2apply ; inline
: 2cdr ( cons cons -- car car ) [ cdr ] 2apply ; inline
! Sequence protocol
M: f length drop 0 ;
M: cons length cdr length 1+ ;
2004-07-16 02:26:21 -04:00
: (list-each) ( list quot -- )
over [
[ >r car r> call ] 2keep >r cdr r> (list-each)
] [
2drop
] if ; inline
M: general-list each ( list quot -- | quot: elt -- )
(list-each) ;
: (list-map) ( list quot -- list )
over [
over cdr over >r >r >r car r> call
r> r> rot >r (list-map) r> swons
] [
drop
] if ; inline
M: general-list map ( list quot -- list ) (list-map) ;
2005-09-07 17:21:11 -04:00
2005-07-16 22:16:18 -04:00
: (list-find) ( list quot i -- i elt )
pick [
>r 2dup >r >r >r car r> call [
r> car r> drop r> swap
] [
2005-09-16 22:47:28 -04:00
r> cdr r> r> 1+ (list-find)
2005-09-24 15:21:17 -04:00
] if
2005-07-16 22:16:18 -04:00
] [
3drop -1 f
2005-09-24 15:21:17 -04:00
] if ; inline
2005-07-16 22:16:18 -04:00
M: general-list find ( list quot -- i elt )
0 (list-find) ;
2004-07-16 02:26:21 -04:00
2005-07-17 00:21:10 -04:00
M: general-list reverse-slice ( list -- list )
[ ] [ swons ] reduce ;
2004-10-13 17:42:03 -04:00
2005-07-17 00:21:10 -04:00
M: general-list reverse reverse-slice ;
M: general-list nth ( n list -- element )
over 0 <= [ nip car ] [ >r 1- r> cdr nth ] if ;
2005-09-16 22:47:28 -04:00
M: cons = ( obj cons -- ? )
{
{ [ 2dup eq? ] [ 2drop t ] }
{ [ over cons? not ] [ 2drop f ] }
{ [ t ] [ 2dup 2car = >r 2cdr = r> and ] }
} cond ;
2005-09-16 22:47:28 -04:00
2005-11-27 17:45:48 -05:00
: curry ( obj quot -- quot ) >r literalize r> cons ;
: (>list) ( n i seq -- list )
pick pick <= [
3drop [ ]
] [
2dup nth >r >r 1+ r> (>list) r> swons
] if ;
M: object >list ( seq -- list ) dup length 0 rot (>list) ;
M: general-list like drop >list ;