Sum function call

Hi,

I am new in scala. I tried to run a simple function but I am not getting how to do it. I mean
if I call sum function I don’t now what I have to pass for the first parameter? The second and third is clear its expecting an integer but the first its expecting a function how to pass?
sum(?,2,4)

def sum(f: Int => Int, a: Int, b:Int) : Int =

if(a > b) 0 else f(a) + sum(f,4,3)

sum(?, 2,3)

Thanks!

So that function expects another function, so you can do something like this:

// Using a def
def myFun(i: Int): Int = i + 1
sum(myFun, 2, 3)

// Using a val
val myFun: Int => Int = i => i + 1
sum(myFun, 2, 3)

// Using a lambda
sum((i: Int) => i + 1, 2, 3)

// Using the underscore syntax
sum(_ + 1, 2, 3)

Thanks a lot for the fast reponse. What is exactly this => expression?

Is a function literal (aka lambda), you should already know that since you are already trying to write / use a higher-order function (a function that takes another function as argument)

I have seen that sum function before, I believe it is from a course, so it would be good to see if you skipped some lesson.

Or you may want to take a look to the Scala tour.

Happy coding!

Thanks! Yeah it was from a course where I took this function! I wanted to try how it works.

1 Like