home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / OL.LZH / PROCS.LZH / ISORT.ICN < prev    next >
Text File  |  1991-07-13  |  2KB  |  50 lines

  1. ############################################################################
  2. #
  3. #    Name:    isort.icn
  4. #
  5. #    Title:    Customizable sort procedure
  6. #
  7. #    Author:    Robert J. Alexander
  8. #
  9. #    Date:    December 5, 1989
  10. #
  11. ############################################################################
  12. #
  13. #  Customizable sort procedure for inclusion in Icon programs.
  14. #
  15. #       isort(x,keyproc,y)
  16. #
  17. #  Argument x can be any Icon data type that is divisible into elements
  18. #  by the unary element generation (!) operator.  The result is a list
  19. #  of the objects in sorted order.
  20. #
  21. #  The default is to sort elements in their natural, Icon-defined order.
  22. #  However, an optional parameter (keyproc) allows a sort key to be
  23. #  derived from each element, rather than the default of using the
  24. #  element itself as the key.  Keyproc can be a procedure provided by
  25. #  the caller, in which case the first argument to the key procedure is
  26. #  the item for which the key is to be computed, and the second argument
  27. #  is isort's argument y, passed unchanged.  The keyproc must produce
  28. #  the extracted key.  Alternatively, the keyproc argument can be an
  29. #  integer, in which case it specifies a subscript to be applied to each
  30. #  item to produce a key.  Keyproc will be called once for each element
  31. #  of structure x.
  32. #
  33. ############################################################################
  34.  
  35. procedure isort(x,keyproc,y)
  36.    local items,item,key,result
  37.    if y := integer(keyproc) then
  38.      keyproc := proc("[]",2)
  39.    else /keyproc := 1
  40.    items := table()
  41.    every item := !x do {
  42.       key := keyproc(item,y)
  43.       (/items[key] := [item]) | put(items[key],item)
  44.       }
  45.    items := sort(items,3)
  46.    result := []
  47.    while get(items) do every put(result,!get(items))
  48.    return result
  49. end
  50.