home *** CD-ROM | disk | FTP | other *** search
- ############################################################################
- #
- # File: isort.icn
- #
- # Subject: Procedure for customizable sorting
- #
- # Author: Robert J. Alexander
- #
- # Date: December 5, 1989
- #
- ###########################################################################
- #
- # Customizable sort procedure for inclusion in Icon programs.
- #
- # isort(x,keyproc,y)
- #
- # Argument x can be any Icon data type that is divisible into elements
- # by the unary element generation (!) operator. The result is a list
- # of the objects in sorted order.
- #
- # The default is to sort elements in their natural, Icon-defined order.
- # However, an optional parameter (keyproc) allows a sort key to be
- # derived from each element, rather than the default of using the
- # element itself as the key. Keyproc can be a procedure provided by
- # the caller, in which case the first argument to the key procedure is
- # the item for which the key is to be computed, and the second argument
- # is isort's argument y, passed unchanged. The keyproc must produce
- # the extracted key. Alternatively, the keyproc argument can be an
- # integer, in which case it specifies a subscript to be applied to each
- # item to produce a key. Keyproc will be called once for each element
- # of structure x.
- #
- ############################################################################
-
- procedure isort(x,keyproc,y)
- local items,item,key,result
- if y := integer(keyproc) then
- keyproc := proc("[]",2)
- else /keyproc := 1
- items := table()
- every item := !x do {
- key := keyproc(item,y)
- (/items[key] := [item]) | put(items[key],item)
- }
- items := sort(items,3)
- result := []
- while get(items) do every put(result,!get(items))
- return result
- end
-