Averages/Arithmetic mean: Difference between revisions

Content added Content deleted
(→‎{{header|Perl 6}}: Fixed bug with empty argument.)
(Added Scala)
Line 742: Line 742:
<lang ruby>nums = [3, 1, 4, 1, 5, 9]
<lang ruby>nums = [3, 1, 4, 1, 5, 9]
nums.empty? ? 0 : nums.inject(:+) / Float(nums.size)</lang>
nums.empty? ? 0 : nums.inject(:+) / Float(nums.size)</lang>

=={{header|Scala}}==
Using Scala 2.7, this has to be defined for each numeric type:

<lang scala>def mean(s: Seq[Int]) = s.foldLeft(0)(_+_) / s.size</lang>

However, Scala 2.8 gives much more flexibility, but you still have to opt
between integral types and fractional types. For example:

<lang scala>def mean[T](s: Seq[T])(implicit n: Integral[T]) = {
import n._
s.foldLeft(zero)(_+_) / fromInt(s.size)
}</lang>

This can be used with any subclass of <tt>Sequence</tt> on integral types, up
to and including BigInt. One can also create singletons extending <tt>Integral</tt>
for user-defined numeric classes. Likewise, <tt>Integral</tt> can be replaced by
<tt>Fractional</tt> in the code to support fractional types, such as <tt>Float</tt>
and <tt>Double</tt>.

Alas, Scala 2.8 also simplifies the task in another way:

<lang scala>def mean[T](s: Seq[T])(implicit n: Fractional[T]) = n.div(s.sum, n.fromInt(s.size))</lang>

Here we show a function that supports fractional types. Instead of importing the definitions
from <tt>n</tt>, we are calling them on <tt>n</tt> itself. And because we did not import them,
the implicit definitions that would allow us to use <tt>/</tt> were not imported as well.
Finally, we use <tt>sum</tt> instead of <tt>foldLeft</tt>.


=={{header|Scheme}}==
=={{header|Scheme}}==