factor/library/collections/lists.factor

84 lines
1.9 KiB
Factor
Raw Permalink 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
! Sequence protocol
M: f length drop 0 ;
2005-09-16 22:47:28 -04:00
M: cons length cdr length 1+ ;
2005-04-03 16:55:56 -04:00
M: f empty? drop t ;
M: cons empty? drop f ;
2005-09-08 22:23:54 -04:00
M: f peek ( f -- f ) ;
2005-07-16 22:16:18 -04:00
M: cons peek ( list -- last )
#! Last element of a list.
last car ;
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 ;
2005-05-18 16:26:22 -04:00
M: general-list head ( n list -- list )
2004-12-23 01:14:07 -05:00
#! Return the first n elements of the list.
2005-05-18 16:26:22 -04:00
over 0 > [
2005-09-16 22:47:28 -04:00
unswons >r >r 1- r> head r> swons
2005-05-18 16:26:22 -04:00
] [
2drop f
2005-09-24 15:21:17 -04:00
] if ;
2005-05-18 16:26:22 -04:00
M: general-list tail ( n list -- tail )
#! Return the rest of the list, from the nth index onward.
2005-05-18 16:26:22 -04:00
swap [ cdr ] times ;
M: general-list nth ( n list -- element )
2006-01-28 15:49:31 -05:00
over zero? [ 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
M: f = ( obj f -- ? ) eq? ;
2005-09-28 20:09:10 -04:00
2005-11-27 17:45:48 -05:00
: curry ( obj quot -- quot ) >r literalize r> cons ;
: assoc ( key alist -- value ) [ car = ] find-with nip cdr ;