Averages/Mode: Difference between revisions

Content added Content deleted
(Complete task for Racket)
(Add Seed7 example)
Line 1,876: Line 1,876:
(filter (lambda (x) (= (cdr x) (apply max (map cdr (helper collection '())))))
(filter (lambda (x) (= (cdr x) (apply max (map cdr (helper collection '())))))
(helper collection '())))</lang>
(helper collection '())))</lang>

=={{header|Seed7}}==
The example below defines the template function <code>createModeFunction</code>, which defines the function <code>mode</code>.
The template <code>createModeFunction</code> is instantiated explicit with <code>createModeFunction(integer)</code>.
Additionally to <code>mode</code> the function <code>str</code> is defined.
The function <code>str</code> is used by the template function
[http://seed7.sourceforge.net/libraries/enable_output.htm#enable_output%28in_type%29 enable_output] to allow writing arrays.
This way the <code>main</code> function can just [http://seed7.sourceforge.net/libraries/enable_output.htm#write%28in_aType%29 write] the mode.

<lang seed7>$ include "seed7_05.s7i";

const proc: createModeFunction (in type: elemType) is func
begin

const func array elemType: mode (in array elemType: data) is func
result
var array elemType: maxElems is 0 times elemType.value;
local
var hash [elemType] integer: counts is (hash [elemType] integer).value;
var elemType: aValue is elemType.value;
var integer: maximum is 0;
begin
for aValue range data do
if aValue in counts then
incr(counts[aValue]);
else
counts @:= [aValue] 1;
end if;
if counts[aValue] > maximum then
maximum := counts[aValue];
maxElems := [] (aValue);
elsif counts[aValue] = maximum then
maxElems &:= aValue;
end if;
end for;
end func;

const func string: str (in array elemType: data) is func
result
var string: result is "";
local
var elemType: anElement is elemType.value;
begin
for anElement range data do
result &:= " " & str(anElement);
end for;
result := result[2 ..];
end func;

enable_output(array elemType);

end func;

createModeFunction(integer);

const proc: main is func
begin
writeln(mode([] (1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17)));
writeln(mode([] (1, 1, 2, 4, 4)));
end func;</lang>

{{out}}
<pre>
6
1 4
</pre>


=={{header|Slate}}==
=={{header|Slate}}==