Function frequency: Difference between revisions

m
syntax highlighting fixup automation
m (→‎{{header|Phix}}: command_line() no longer a blocker, so deleted that from the comment)
m (syntax highlighting fixup automation)
Line 10:
 
This will, unfortunately, also catch variable names after an open paren, such as in <code>(let ...)</code> expressions.
<langsyntaxhighlight Lisplang="lisp">(in-package "ACL2")
 
(set-state-ok t)
Line 72:
(invoked-functions "function-freq.lisp" state)
(mv (take 10 (isort-freq-table
(symbol-freq-table fns))) state)))</langsyntaxhighlight>
Output (for itself):
<pre>(((FIRST . 10)
Line 88:
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">source: to :block read arg\0
frequencies: #[]
 
Line 115:
inspectBlock source
 
inspect frequencies</langsyntaxhighlight>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f FUNCTION_FREQUENCY.AWK filename(s).AWK
#
Line 279:
}
}
</syntaxhighlight>
</lang>
<p>Output of running FUNCTION_FREQUENCY.AWK on itself:</p>
<pre>
Line 317:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> INSTALL @lib$+"SORTLIB"
Sort% = FN_sortinit(1,0) : REM Descending
Line 363:
FOR i% = 0 TO C%-1
PRINT func$(i%) " (" ; cnt%(i%) ")"
NEXT</langsyntaxhighlight>
'''Output (for file LBB.BBC):'''
<pre>
Line 380:
=={{header|C}}==
This program treats doesn't differentiate between macros and functions. It works by looking for function calls which are not inside strings or comments. If a function call has a C style comment between the opening brace and the name of the function, this program will not recognize it as a function call.
<syntaxhighlight lang="c">
<lang C>
#define _POSIX_SOURCE
#include <ctype.h>
Line 631:
}
return 0;
}</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
Loading the file itself before scanning it is the quickest way to determine what function bindings would be created.
<langsyntaxhighlight lang="lisp">(defun mapc-tree (fn tree)
"Apply FN to all elements in TREE."
(cond ((consp tree)
Line 668:
(defun top-10 (table)
"Get the top 10 from the source counts TABLE."
(take 10 (sort (hash-to-alist table) '> :key 'cdr)))</langsyntaxhighlight>
{{out}}
<pre>CL-USER> (top-10 (count-source "function-frequency.lisp"))
Line 676:
=={{header|Erlang}}==
This is source code analyse. Mainly because I have never done that before.
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( function_frequency ).
 
Line 708:
parse_all( _IO, {eof, _End}, Acc ) -> Acc;
parse_all( IO, {ok, Tokens, Location}, Acc ) -> parse_all( IO, io:parse_erl_form(IO, '', Location), [Tokens | Acc] ).
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 726:
=={{header|Factor}}==
Let's take a look at the <code>sequences</code> vocabulary/source file from Factor's standard library. This approach does not count word-defining words such as <code>:</code> and <code>M:</code>, nor does it count words like <code>{</code> and <code>[</code>.
<langsyntaxhighlight lang="factor">USING: accessors kernel math.statistics prettyprint sequences
sequences.deep source-files vocabs words ;
 
Line 732:
[ path>source-file top-level-form>> ]
[ vocab-words [ def>> ] [ ] map-as ] bi* compose [ word? ]
deep-filter sorted-histogram <reversed> 7 head .</langsyntaxhighlight>
{{out}}
<pre>
Line 748:
=={{header|Forth}}==
Counts colon definitions, variables, constants, words defined by definers like CREATE..DOES>, etc. Check for levels of top from command line, by default 4. GForth 0.7.0 specific.
<langsyntaxhighlight Forthlang="forth">' noop is bootmessage
 
\ --- LIST OF CONSTANTS
Line 907:
\ Run, ruuun!
stdin ' run execute-parsing-file DEFS @maxfreq rings-vec over DEFS populate-by args>top# .top bye
</syntaxhighlight>
</lang>
Self test:
<pre>
Line 929:
=={{header|Go}}==
Only crude approximation is currently easy in Go. The following parses source code, looks for function call syntax (an expression followed by an argument list) and prints the expression.
<langsyntaxhighlight lang="go">package main
 
import (
Line 988:
func (c calls) Len() int { return len(c) }
func (c calls) Swap(i, j int) { c[i], c[j] = c[j], c[i] }
func (c calls) Less(i, j int) bool { return c[i].count > c[j].count }</langsyntaxhighlight>
Output, when run on source code above:
<pre>
Line 1,007:
Nevertheless, the quick and dirty solution may be given. It finds explicit applications which are distinguished as applications in AST while parsing the Haskell code. As soon as one will try to make this solution cleaner or more precise, ambiguity of the task will emerge immediately.
 
<langsyntaxhighlight lang="haskell">import Language.Haskell.Parser (parseModule)
import Data.List.Split (splitOn)
import Data.List (nub, sortOn, elemIndices)
Line 1,026:
src <- readFile "CountFunctions.hs"
let res = sortOn (negate . fst) $ findApps src
mapM_ (\(n, f) -> putStrLn $ show n ++ "\t" ++ f) res</langsyntaxhighlight>
 
<pre>*Main> main
Line 1,055:
The lowest approach taken here makes no effort to classify the primitives as monads nor dyads, nor as verbs, adverbs, nor conjunctions. Did "-" mean "additive inverse" or indicate subtraction? Does ";" raze or link? J is a multi-instruction single data language. Parentheses around a group of verbs form hooks or forks which affect data flow. The simple top10 verb does not find these important constructs. So we shall ignore them for this exercise.
 
<syntaxhighlight lang="j">
<lang j>
IGNORE=: ;:'y(0)1',CR
 
Line 1,091:
│14655│@ │
└─────┴──┘
</syntaxhighlight>
</lang>
 
=={{header|Julia}}==
{{works with|Julia|0.6}}
 
<langsyntaxhighlight lang="julia">using Printf, DataStructures
 
function funcfreqs(expr::Expr)
Line 1,128:
for (v, f) in freqs
@printf("%10s → %i\n", v, f)
end</langsyntaxhighlight>
 
{{out}}
Line 1,153:
=={{header|LiveCode}}==
Initially based on [http://lessons.livecode.com/m/2592/l/126343-listing-all-the-handlers-in-a-script Listing all the handlers in a script]
<langsyntaxhighlight LiveCodelang="livecode">function handlerNames pScript
put pScript into pScriptCopy
filter pScript with regex pattern "^(on|function).*"
Line 1,181:
put line 1 to 10 of handlers into handlers
return handlers
end handlerNames</langsyntaxhighlight>
 
To use<langsyntaxhighlight LiveCodelang="livecode">put handlerNames(the script of this stack & cr & the script of this card & cr & the script of me)</langsyntaxhighlight>
 
Sample output<langsyntaxhighlight LiveCodelang="livecode">if 8
put 8
return 8
Line 1,194:
factorial 2 -- user def function for other rosetta task
factorialit 2 -- user def function for other rosetta task
mouseUp 2</langsyntaxhighlight>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">programCount[fn_] := Reverse[If[Length[#] > 10, Take[#, -10], #] &[SortBy[Tally[Cases[DownValues[fn], s_Symbol, \[Infinity], Heads -> True]], Last]]]</langsyntaxhighlight>
{{out}}The output of applying this program to itself...<pre>programCount[programCount]
 
Line 1,203:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim"># naive function calling counter
# TODO consider a more sophisticated condition on counting function callings
# without parenthesis which are common in nim lang. Be aware that the AST of
Line 1,248:
total-=1
if total == 0:
break</langsyntaxhighlight>
{{out}}
<pre>
Line 1,265:
=={{header|Perl}}==
We leverage the PPI::Tokenizer module.
<langsyntaxhighlight lang="perl">use PPI::Tokenizer;
my $Tokenizer = PPI::Tokenizer->new( '/path/to/your/script.pl' );
my %counts;
Line 1,280:
foreach my $token (@top_ten_by_occurrence) {
print $counts{$token}, "\t", $token, "\n";
}</langsyntaxhighlight>
{{out}}
When run on itself:
Line 1,297:
As Phix is self hosted, we can modify the compiler (or a copy of it) directly for this task.<br>
Add the line shown to procedure Call() in pmain.e, after the else on line 4938 (at the time of writing)
<!--<langsyntaxhighlight Phixlang="phix">(notonline)-->
<span style="color: #008080;">else</span> <span style="color: #000080;font-style:italic;">-- rType=FUNC|TYPE</span>
<span style="color: #000000;">log_function_call</span><span style="color: #0000FF;">(</span><span style="color: #000000;">rtnNo</span><span style="color: #0000FF;">)</span>
<!--</langsyntaxhighlight>-->
(I may have been a bit too literal about "function" here, specifically "not procedure")
 
Now create our test.exw program, which wraps the entire compiler:
<!--<langsyntaxhighlight Phixlang="phix">(notonline)-->
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- file i/o, etc...</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">func_log</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">new_dict</span><span style="color: #0000FF;">(),</span>
Line 1,335:
<span style="color: #7060A8;">traverse_dict</span><span style="color: #0000FF;">(</span><span style="color: #000000;">visitor</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">func_log</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- invert</span>
<span style="color: #7060A8;">traverse_dict</span><span style="color: #0000FF;">(</span><span style="color: #000000;">visitor</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">func_freq</span><span style="color: #0000FF;">,</span><span style="color: #000000;">rev</span><span style="color: #0000FF;">:=</span><span style="color: #004600;">true</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- top 10</span>
<!--</langsyntaxhighlight>-->
Invoke using "p test -norun test" (note you can omit the ".exw" part of "test.exw")
{{out}}
Line 1,366:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(let Freq NIL
(for "L" (filter pair (extract getd (all)))
(for "F"
Line 1,374:
(accu 'Freq "F" 1) ) )
(for X (head 10 (flip (by cdr sort Freq)))
(tab (-7 4) (car X) (cdr X)) ) )</langsyntaxhighlight>
Output, for the system in debug mode plus the above code:
<pre>quote 310
Line 1,412:
{{works with|Python|3.x}}
This code parses a Python source file using the built-in '''ast''' module and counts simple function calls; it won't process method calls or cases when you call the result of an expression. Also, since constructors are invoked by calling the class, constructor calls are counted as well.
<langsyntaxhighlight lang="python">import ast
 
class CallCountingVisitor(ast.NodeVisitor):
Line 1,435:
for name, count in top10:
print(name,'called',count,'times')
</syntaxhighlight>
</lang>
 
The result of running the program on the ftplib module of Python 3.2:
Line 1,452:
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
(require math)
Line 1,461:
(define counts (sort (hash->list (samples->hash symbols)) >= #:key cdr))
(take counts (min 10 (length counts)))
</syntaxhighlight>
</lang>
Output:
<langsyntaxhighlight lang="racket">
'((define . 4)
(counts . 3)
Line 1,474:
(in-port . 1)
(sort . 1))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
Here we just examine the ast of the Raku compiler (which is written in Raku) to look for function calls.
<syntaxhighlight lang="raku" perl6line>my $text = qqx[raku --target=ast @*ARGS[]];
my %fun;
for $text.lines {
Line 1,485:
}
 
for %fun.invert.sort.reverse[^10] { .value.say }</langsyntaxhighlight>
{{out}}
Here we run it on the strand sort RC entry. Note how Raku considers various operators to really be function calls underneath.
Line 1,503:
===version 1===
This program counts statically. It lacks, however, treatment of comments and literal strings.
<langsyntaxhighlight lang="rexx">fid='pgm.rex'
cnt.=0
funl=''
Line 1,536:
If cnt.fun=1 Then
funl=funl fun
Return</langsyntaxhighlight>
{{out}}
<pre> 1 lines
Line 1,558:
Contents of comments and literal strings are not analyzed.
Neither are function invocations via CALL.
<langsyntaxhighlight lang="rexx">/* REXX ****************************************** Version 11.12.2015 **
* Rexx Tokenizer to find function invocations
*-----------------------------------------------------------------------
Line 2,067:
End
If errtxt<>'' Then Say ' 'errtxt
Exit 12</langsyntaxhighlight>
{{out}}
Result for the above program.
Line 2,095:
=={{header|Sidef}}==
Sidef provides full access to its parser, allowing us to inspect all the declarations within a program.
<langsyntaxhighlight lang="ruby">func foo { }
func bar { }
 
Line 2,108:
" #{entry{:line}}) is used #{entry{:count}} times")
}
}</langsyntaxhighlight>
 
{{out}}
Line 2,120:
This parses all classes of all loaded packages/libraries (takes a few seconds). From the code, it should be obvious how to restrict the search to packages, libraries, classes or individual methods.
 
<langsyntaxhighlight lang="smalltalk">bagOfCalls := Bag new.
Smalltalk allClassesDo:[:cls |
cls instAndClassMethodsDo:[:mthd |
Line 2,128:
(bagOfCalls sortedCounts to:10) do:[:assoc |
Stdout printCR: e'method {assoc value} is called {assoc key} times.'
].</langsyntaxhighlight>
note: messagesSent calls the parser for an AST and enumerates the parse nodes; it does not know, which get inlined and which end up being called actually (in fact, most of the one's below are probably inlined).
 
Line 2,145:
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">package require Tcl 8.6
 
proc examine {filename} {
Line 2,172:
foreach {cmd count} [lrange $cmdinfo 0 19] {
puts [format "%-20s%d" $cmd $count]
}</langsyntaxhighlight>
Sample run (note that the commands found are all standard Tcl commands; they're ''just'' commands so it is natural to expect them to be found):
<pre>
Line 2,202:
 
In the absence of any other feasible approach, we simply search for method/function calls in a given Wren source file and count them to find the 'top ten'.
<langsyntaxhighlight lang="ecmascript">import "io" for File
import "os" for Process
import "/pattern" for Pattern
Line 2,225:
for (mc in methodCalls.take(10)) {
Fmt.print(" $2d $s", mc.value, mc.key)
}</langsyntaxhighlight>
 
{{out}}
10,333

edits