Decorate-sort-undecorate idiom: Difference between revisions

(Added Quackery.)
Line 213:
 
=={{header|Factor}}==
{{works with|Factor |0.99 build 2207}}
<code>map-sort</code> employs the decorate-sort-undecorate idiom, while <code>sort-by</code> does not.
The easiest way is to define your key function as a memoized word. Memoized words store input/output pairs and simply fetch the outputs of inputs they've seen before. Then using the usual <code>sort-by</code> combinator won't recalculate any extraneous lengths.
<syntaxhighlight lang="factor">
USING: prettyprint sequences sorting.extras ;
 
MEMO: length* ( seq -- n ) length ;
 
{ "Rosetta" "Code" "is" "a" "programming" "chrestomathy" "site" }
[ length* ] sort-by .
</syntaxhighlight>
 
A more direct implementation would be:
<syntaxhighlight lang="factor">
USING: assocs prettyprint sequences sorting ;
 
{ "Rosetta" "Code" "is" "a" "programming" "chrestomathy" "site" }
[ length ] zipmap-withsort .
[ last ] sort-by
keys .
</syntaxhighlight>
{{out}}
1,827

edits