From 9efa64831f78ff1b94c91e8a7cdd082b31450aae Mon Sep 17 00:00:00 2001 From: John Benediktsson Date: Thu, 7 Apr 2011 08:57:26 -0700 Subject: [PATCH] sorting: change sort-keys and sort-values to generics. --- core/sorting/sorting-docs.factor | 8 ++++---- core/sorting/sorting.factor | 14 +++++++++++--- 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/core/sorting/sorting-docs.factor b/core/sorting/sorting-docs.factor index 5b013f95fb..4877cdf410 100644 --- a/core/sorting/sorting-docs.factor +++ b/core/sorting/sorting-docs.factor @@ -36,12 +36,12 @@ HELP: inv-sort-with { $description "Sorts the elements of " { $snippet "seq" } " by applying " { $link compare } " with " { $snippet "quot" } " to each pair of elements in the sequence and inverting the results." } ; HELP: sort-keys -{ $values { "seq" "an alist" } { "sortedseq" "a new sorted sequence" } } -{ $description "Sorts the elements of " { $snippet "seq" } " comparing first elements of pairs using the " { $link <=> } " word." } ; +{ $values { "obj" "an object" } { "sortedseq" "a new sorted sequence" } } +{ $description "Sorts the elements of " { $snippet "obj" } " (converting to an alist first if not a sequence), comparing first elements of pairs using the " { $link <=> } " word." } ; HELP: sort-values -{ $values { "seq" "an alist" } { "sortedseq" "a new sorted sequence" } } -{ $description "Sorts the elements of " { $snippet "seq" } " comparing second elements of pairs using the " { $link <=> } " word." } ; +{ $values { "obj" "an object" } { "sortedseq" "a new sorted sequence" } } +{ $description "Sorts the elements of " { $snippet "obj" } " (converting to an alist first if not a sequence), comparing second elements of pairs using the " { $link <=> } " word." } ; HELP: natural-sort { $values { "seq" "a sequence of real numbers" } { "sortedseq" "a new sorted sequence" } } diff --git a/core/sorting/sorting.factor b/core/sorting/sorting.factor index b8258b239b..b26a34b41e 100644 --- a/core/sorting/sorting.factor +++ b/core/sorting/sorting.factor @@ -1,6 +1,6 @@ ! Copyright (C) 2005, 2009 Slava Pestov. ! See http://factorcode.org/license.txt for BSD license. -USING: accessors arrays kernel math vectors math.order +USING: accessors arrays assocs kernel math vectors math.order sequences sequences.private ; IN: sorting @@ -160,8 +160,16 @@ PRIVATE> : inv-sort-with ( seq quot -- sortedseq ) [ compare invert-comparison ] curry sort ; inline -: sort-keys ( seq -- sortedseq ) [ first ] sort-with ; +GENERIC: sort-keys ( obj -- sortedseq ) -: sort-values ( seq -- sortedseq ) [ second ] sort-with ; +M: object sort-keys >alist sort-keys ; + +M: sequence sort-keys [ first ] sort-with ; + +GENERIC: sort-values ( obj -- sortedseq ) + +M: object sort-values >alist sort-values ; + +M: sequence sort-values [ second ] sort-with ; : sort-pair ( a b -- c d ) 2dup after? [ swap ] when ;