Decorate-sort-undecorate idiom: Difference between revisions
Add Factor
m (→alternative: comment alt) |
(Add Factor) |
||
Line 152:
{{out}}
<pre>[ "a", "is", "Code", "site", "Rosetta", "programming", "chrestomathy" ]</pre>
=={{header|Factor}}==
{{works with|Factor 0.99 build 2207}}
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 ;
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 ] zip-with
[ last ] sort-by
keys .
</syntaxhighlight>
{{out}}
<pre>{
"a"
"is"
"Code"
"site"
"Rosetta"
"programming"
"chrestomathy"
}</pre>
=={{header|FreeBASIC}}==
|