2005-01-14 12:01:48 -05:00
|
|
|
! Copyright (C) 2003, 2005 Slava Pestov.
|
2005-01-29 14:18:28 -05:00
|
|
|
! 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
|
2005-05-14 17:18:45 -04:00
|
|
|
M: f length drop 0 ;
|
|
|
|
|
M: cons length cdr length 1 + ;
|
2005-04-03 16:55:56 -04:00
|
|
|
|
2005-04-25 19:54:21 -04:00
|
|
|
M: f empty? drop t ;
|
|
|
|
|
M: cons empty? drop 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
|
|
|
|
2005-07-16 22:16:18 -04:00
|
|
|
M: f each ( list quot -- ) 2drop ;
|
2004-07-16 02:26:21 -04:00
|
|
|
|
2005-07-25 17:13:35 -04:00
|
|
|
M: cons each ( list quot -- | quot: elt -- )
|
|
|
|
|
[ >r car r> call ] 2keep >r cdr r> each ;
|
2005-01-31 14:02:09 -05:00
|
|
|
|
2005-09-07 17:21:11 -04:00
|
|
|
M: f map ( f quot -- f ) drop ;
|
|
|
|
|
|
|
|
|
|
M: cons map ( cons quot -- cons )
|
|
|
|
|
over cdr over >r >r >r car r> call r> r> rot >r map r> swons ;
|
|
|
|
|
|
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
|
|
|
|
|
] [
|
|
|
|
|
r> cdr r> r> 1 + (list-find)
|
|
|
|
|
] ifte
|
|
|
|
|
] [
|
|
|
|
|
3drop -1 f
|
|
|
|
|
] ifte ; inline
|
|
|
|
|
|
|
|
|
|
M: general-list find ( list quot -- i elt )
|
|
|
|
|
0 (list-find) ;
|
2004-07-16 02:26:21 -04:00
|
|
|
|
|
|
|
|
: unique ( elem list -- list )
|
2004-11-15 21:37:49 -05:00
|
|
|
#! Prepend an element to a list if it does not occur in the
|
|
|
|
|
#! list.
|
2005-07-16 22:16:18 -04:00
|
|
|
2dup member? [ nip ] [ cons ] ifte ;
|
2004-07-16 02:26:21 -04:00
|
|
|
|
2005-07-17 00:21:10 -04:00
|
|
|
M: general-list reverse-slice ( list -- list )
|
2005-06-25 20:39:53 -04:00
|
|
|
[ ] [ 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-01-01 17:20:48 -05:00
|
|
|
|
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 > [
|
|
|
|
|
unswons >r >r 1 - r> head r> swons
|
|
|
|
|
] [
|
|
|
|
|
2drop f
|
|
|
|
|
] ifte ;
|
2004-12-23 02:14:40 -05:00
|
|
|
|
2005-05-18 16:26:22 -04:00
|
|
|
M: general-list tail ( n list -- tail )
|
2004-12-23 02:14:40 -05:00
|
|
|
#! Return the rest of the list, from the nth index onward.
|
2005-05-18 16:26:22 -04:00
|
|
|
swap [ cdr ] times ;
|
2004-12-23 02:14:40 -05:00
|
|
|
|
2005-05-28 20:52:23 -04:00
|
|
|
M: general-list nth ( n list -- element )
|
2005-06-07 03:44:34 -04:00
|
|
|
over 0 number= [ nip car ] [ >r 1 - r> cdr nth ] ifte ;
|