SidiAli
SidiAli

Reputation: 149

Calculating the mean of elements in a list in Scala

I'm trying to write a method that calculates the mean of the elements in a given List in Scala. Here's my code:

def meanElements(list: List[Float]): Float = {
  list match {
    case x :: tail => (x + meanElements(tail))/(list.length)
    case Nil => 0
  }
}

When I call meanElements(List(10,12,14))), the result I get is different than 12. Can someone help?

Upvotes: 1

Views: 8550

Answers (2)

Mahesh Chand
Mahesh Chand

Reputation: 3250

You can simply do it using inbuilt functions:

scala> def mean(list:List[Int]):Int = 
     | if(list.isEmpty) 0 else list.sum/list.size
mean: (list: List[Int])Int

scala> mean(List(10,12,14))
res1: Int = 12

scala> 

Upvotes: 5

janos
janos

Reputation: 124656

The formula is not correct, it should be:

case x :: tail => (x + meanElements(tail) * tail.length) / list.length

But this implementation is performing a lot of divisions and multiplications. It would be better to split the computation of the mean to two steps, calculating the sum first, and then dividing by list.length.

That is, something more like this:

def meanElements(list: List[Float]): Float = sum(list) / list.length

Where sum is a helper function you have to implement. If you don't want to expose its implementation, then you can define it in the body of meanElements. (Or as @ph88 pointed out, it could be as simple as list.reduce(_ + _).)

Upvotes: 2

Related Questions