factor/library/collections/assoc.factor

46 lines
1.5 KiB
Factor
Raw Normal View History

! Copyright (C) 2004, 2005 Slava Pestov.
! See http://factor.sf.net/license.txt for BSD license.
IN: lists USING: kernel sequences ;
2004-07-16 02:26:21 -04:00
: assoc? ( list -- ? )
#! Push if the list appears to be an alist. An association
#! list is a list of conses where the car of each cons is a
#! key, and the cdr is a value.
2004-07-16 02:26:21 -04:00
dup list? [ [ cons? ] all? ] [ drop f ] ifte ;
: assoc* ( key alist -- [[ key value ]] )
#! Look up a key/value pair.
2005-07-16 22:16:18 -04:00
[ car = ] find-with nip ;
2004-07-16 02:26:21 -04:00
2005-03-19 00:30:49 -05:00
: assoc ( key alist -- value ) assoc* cdr ;
2004-07-16 02:26:21 -04:00
: assq* ( key alist -- [[ key value ]] )
#! Looks up a key/value pair using identity comparison.
2005-07-16 22:16:18 -04:00
[ car eq? ] find-with nip ;
2005-03-19 00:30:49 -05:00
: assq ( key alist -- value ) assq* cdr ;
2004-10-16 21:55:13 -04:00
: remove-assoc ( key alist -- alist )
#! Remove all key/value pairs with this key.
[ car = not ] subset-with ;
2004-10-16 21:55:13 -04:00
2004-08-03 20:21:43 -04:00
: acons ( value key alist -- alist )
2004-10-16 21:55:13 -04:00
#! Adds the key/value pair to the alist. Existing pairs with
#! this key are not removed; the new pair simply shadows
#! existing pairs.
2004-08-03 20:21:43 -04:00
>r swons r> cons ;
2004-07-16 02:26:21 -04:00
: set-assoc ( value key alist -- alist )
2004-10-16 21:55:13 -04:00
#! Adds the key/value pair to the alist.
dupd remove-assoc acons ;
2004-08-21 02:55:37 -04:00
2004-08-21 03:30:52 -04:00
: assoc-apply ( value-alist quot-alist -- )
2004-08-21 02:55:37 -04:00
#! Looks up the key of each pair in the first list in the
#! second list to produce a quotation. The quotation is
#! applied to the value of the pair. If there is no
#! corresponding quotation, the value is popped off the
#! stack.
swap [
unswons rot assoc* dup [ cdr call ] [ 2drop ] ifte
] each-with ;