[comp.lang.icon] Using the ``map'' function

Paul_Abrahams@MTS.cc.Wayne.edu (04/04/91)

 
In doing the index for my latest book, I need to sort the entries using a
nonstandard collating sequence.  I therefore need a ``keytrans'' function
that transforms a sorting key to a key that uses the correct collating
sequence.  Here's the obvious way to do it in Icon:
 
procedure keytrans(key)
   static collator
   initial {collator := ...} # printable chars in collating sequence order
   return map(key, collator, &ascii[33:128])
end
 
This is simple but slow since the map must be regenerated for each key.
Here's the other way:
 
procedure keytrans(key)
   static collator, lookup
   initial {
      collator := ...
      lookup = map(&ascii[33:128], collator, &ascii[33:128])
      }
   local c, retval
   retval := ""
   every c := !key do
      retval ||:= lookup[ord(c) - 31]
   return retval
end
 
This is inelegant but fast.
 
Is there any way I can have my cake and eat it too?  I wouldn't mind a small
loss in speed, but the difference here seems pretty big.
 
Paul Abrahams
Abrahams@mts.cc.wayne.edu 

alex@LAGUNA.METAPHOR.COM (Bob Alexander) (04/04/91)

Hi Paul --

In your initial procedure (the slow one) it's likely that much of the
time used in repeatedly executing

	   return map(key, collator, &ascii[33:128])

is due to the fact that every call converts the cset, &ascii, to a
string.

Also, there is an optimization in the iconx code for map() such that
the internal translation table is not rebuilt if the second and third
arguments are the same (i.e. identical descriptors) as for the previous
map() call.  That optimization cannot be used in your proc.

Given all that, I'll bet this will execute a lot faster (the proof is
left to the reader :)

	procedure keytrans(key)
	   static collator, ascii
	   initial {
	      collator := ...
	      ascii := &ascii[33:128]
	   }
	   return map(key, collator, ascii)
	end

-- Bob Alexander

Metaphor Computer Systems   (415) 961-3600 x751   alex@metaphor.com
====^=== Mountain View, CA  ...{uunet}!{decwrl,apple}!metaphor!alex