factor/basis/sorting/slots/slots.factor

29 lines
960 B
Factor
Raw Normal View History

! Copyright (C) 2009 Slava Pestov, Doug Coleman.
! See http://factorcode.org/license.txt for BSD license.
2009-04-18 17:44:24 -04:00
USING: arrays fry kernel math.order sequences sorting ;
IN: sorting.slots
2009-04-18 17:44:24 -04:00
: execute-comparator ( obj1 obj2 word -- <=>/f )
execute( obj1 obj2 -- <=> ) dup +eq+ eq? [ drop f ] when ;
2009-04-18 17:44:24 -04:00
: execute-accessor ( obj1 obj2 word -- obj1' obj2' )
'[ _ execute( tuple -- value ) ] bi@ ;
2009-04-18 17:44:24 -04:00
: compare-slots ( obj1 obj2 sort-specs -- <=> )
2015-09-08 19:15:10 -04:00
! sort-spec: { accessors comparator }
2009-04-18 17:44:24 -04:00
[
dup array? [
unclip-last-slice
[ [ execute-accessor ] each ] dip
] when execute-comparator
] 2with map-find drop +eq+ or ;
2011-09-22 20:19:51 -04:00
: sort-by-with ( seq sort-specs quot: ( obj -- key ) -- seq' )
2009-04-18 17:44:24 -04:00
swap '[ _ bi@ _ compare-slots ] sort ; inline
2009-04-18 17:44:24 -04:00
: sort-by ( seq sort-specs -- seq' ) [ ] sort-by-with ;
2009-04-18 17:44:24 -04:00
: sort-keys-by ( seq sort-seq -- seq' ) [ first ] sort-by-with ;
2009-04-18 17:44:24 -04:00
: sort-values-by ( seq sort-seq -- seq' ) [ second ] sort-by-with ;