Omer Chomer Sarig
Omer Chomer Sarig

Reputation: 11

What wrong in this scala code

This function should give back the sum of all the numbers in the list but when I run it I always get back ans=0.

def sum(st: List[Int]): Int = {
  var ans=0 

  def combine(st: List[Int], ans:Int): Int = {
    if (st.isEmpty) ans else combine(st.tail, ans)        
  }
  ans
}

What is wrong with it?

Upvotes: 1

Views: 141

Answers (5)

Jesper
Jesper

Reputation: 206786

You have defined a method combine inside your method sum, but you are not calling combine (other than within combine, so it never gets called). If you don't call the method, it will not be executed; just defining the method doesn't mean it's executed.

If you want to program in the functional style, you should also avoid using mutable variables (var); use immutable values (val) instead.

Also, your combine method is not summing anything (it's not modifying ans anywhere, or using any value in the list).

Upvotes: 2

fracca
fracca

Reputation: 2437

foldLeft, and even better, sum are the preferred option as hedefalk mentioned.

Upvotes: 0

Viktor Hedefalk
Viktor Hedefalk

Reputation: 3914

1) You're not calling the inner method combine - you are just returning ans as it is iniatilized to 0.

2) combine doesn't really do anything

I think the code you wanted to write was the following:

def sum(st: List[Int]): Int = {
  def combine(st: List[Int], ans:Int): Int = {
    if (st.isEmpty) ans else combine(st.tail, ans + st.head)        
  }
  combine(st, 0)
}

but of course a shorter version would be:

st.foldLeft(0)(_ + _)

or just

st.sum

which uses a standard type class instance of Numeric: IntIsIntegral:

http://www.scala-lang.org/api/current/index.html#scala.math.Numeric$$IntIsIntegral$

Upvotes: 3

Denis R.
Denis R.

Reputation: 818

I agree with Brian answer on why your solution does not work.

Moreover, there is an even shorter way to do it with the API of Sequence of Scala (which List implements), using foldLeft :

def sum(st: List[Int]): Int = {
    st.foldLeft(0)(_ + _)
}

Upvotes: 1

Brian Agnew
Brian Agnew

Reputation: 272217

You need to add the head of the list to ans. At the moment you're recursing but not actually using the head of the list.

e.g. I think you need something like the below, in which you add the head of the list to the sum of the remainder.

scala> def sum(st: List[Int]): Int = 
     | {
     | if (st.isEmpty) {
     |    0
     | }
     | else {
     |    st.head + sum(st.tail)
     | }
     | }
sum: (st: List[Int])Int

Upvotes: 5

Related Questions